pqconnection.pp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. unit pqconnection;
  2. {$mode objfpc}{$H+}
  3. {$Define LinkDynamically}
  4. interface
  5. uses
  6. Classes, SysUtils, sqldb, db, dbconst,
  7. {$IfDef LinkDynamically}
  8. postgres3dyn;
  9. {$Else}
  10. postgres3;
  11. {$EndIf}
  12. type
  13. TPQTrans = Class(TSQLHandle)
  14. protected
  15. PGConn : PPGConn;
  16. ErrorOccured : boolean;
  17. end;
  18. TPQCursor = Class(TSQLCursor)
  19. protected
  20. Statement : string;
  21. tr : TPQTrans;
  22. res : PPGresult;
  23. CurTuple : integer;
  24. Nr : string;
  25. end;
  26. { TPQConnection }
  27. TPQConnection = class (TSQLConnection)
  28. private
  29. FCursorCount : word;
  30. FConnectString : string;
  31. FSQLDatabaseHandle : pointer;
  32. FIntegerDateTimes : boolean;
  33. function TranslateFldType(Type_Oid : integer) : TFieldType;
  34. procedure ExecuteDirectPG(const Query : String);
  35. protected
  36. procedure DoInternalConnect; override;
  37. procedure DoInternalDisconnect; override;
  38. function GetHandle : pointer; override;
  39. Function AllocateCursorHandle : TSQLCursor; override;
  40. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  41. Function AllocateTransactionHandle : TSQLHandle; override;
  42. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  43. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); override;
  44. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  45. function Fetch(cursor : TSQLCursor) : boolean; override;
  46. procedure UnPrepareStatement(cursor : TSQLCursor); override;
  47. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer) : boolean; override;
  48. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  49. function RollBack(trans : TSQLHandle) : boolean; override;
  50. function Commit(trans : TSQLHandle) : boolean; override;
  51. procedure CommitRetaining(trans : TSQLHandle); override;
  52. function StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  53. procedure RollBackRetaining(trans : TSQLHandle); override;
  54. procedure UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string); override;
  55. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  56. public
  57. constructor Create(AOwner : TComponent); override;
  58. procedure CreateDB; override;
  59. procedure DropDB; override;
  60. published
  61. property DatabaseName;
  62. property KeepConnection;
  63. property LoginPrompt;
  64. property Params;
  65. property OnLogin;
  66. end;
  67. implementation
  68. uses math;
  69. ResourceString
  70. SErrRollbackFailed = 'Rollback transaction failed';
  71. SErrCommitFailed = 'Commit transaction failed';
  72. SErrConnectionFailed = 'Connection to database failed';
  73. SErrTransactionFailed = 'Start of transacion failed';
  74. SErrClearSelection = 'Clear of selection failed';
  75. SErrExecuteFailed = 'Execution of query failed';
  76. SErrFieldDefsFailed = 'Can not extract field information from query';
  77. SErrFetchFailed = 'Fetch of data failed';
  78. SErrPrepareFailed = 'Preparation of query failed.';
  79. const Oid_Bool = 16;
  80. Oid_Text = 25;
  81. Oid_Oid = 26;
  82. Oid_Name = 19;
  83. Oid_Int8 = 20;
  84. Oid_int2 = 21;
  85. Oid_Int4 = 23;
  86. Oid_Float4 = 700;
  87. Oid_Float8 = 701;
  88. Oid_Unknown = 705;
  89. Oid_bpchar = 1042;
  90. Oid_varchar = 1043;
  91. Oid_timestamp = 1114;
  92. oid_date = 1082;
  93. oid_time = 1083;
  94. oid_numeric = 1700;
  95. constructor TPQConnection.Create(AOwner : TComponent);
  96. begin
  97. inherited;
  98. FConnOptions := FConnOptions + [sqSupportParams];
  99. end;
  100. procedure TPQConnection.CreateDB;
  101. begin
  102. ExecuteDirectPG('CREATE DATABASE ' +DatabaseName);
  103. end;
  104. procedure TPQConnection.DropDB;
  105. begin
  106. ExecuteDirectPG('DROP DATABASE ' +DatabaseName);
  107. end;
  108. procedure TPQConnection.ExecuteDirectPG(const query : string);
  109. var ASQLDatabaseHandle : PPGConn;
  110. res : PPGresult;
  111. msg : String;
  112. begin
  113. CheckDisConnected;
  114. {$IfDef LinkDynamically}
  115. InitialisePostgres3;
  116. {$EndIf}
  117. FConnectString := '';
  118. if (UserName <> '') then FConnectString := FConnectString + ' user=''' + UserName + '''';
  119. if (Password <> '') then FConnectString := FConnectString + ' password=''' + Password + '''';
  120. if (HostName <> '') then FConnectString := FConnectString + ' host=''' + HostName + '''';
  121. FConnectString := FConnectString + ' dbname=''template1''';
  122. if (Params.Text <> '') then FConnectString := FConnectString + ' '+Params.Text;
  123. ASQLDatabaseHandle := PQconnectdb(pchar(FConnectString));
  124. if (PQstatus(ASQLDatabaseHandle) = CONNECTION_BAD) then
  125. begin
  126. msg := PQerrorMessage(ASQLDatabaseHandle);
  127. PQFinish(ASQLDatabaseHandle);
  128. DatabaseError(sErrConnectionFailed + ' (PostgreSQL: ' + Msg + ')',self);
  129. end;
  130. res := PQexec(ASQLDatabaseHandle,pchar(query));
  131. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  132. begin
  133. msg := PQerrorMessage(ASQLDatabaseHandle);
  134. PQclear(res);
  135. PQFinish(ASQLDatabaseHandle);
  136. DatabaseError(SDBCreateDropFailed + ' (PostgreSQL: ' + Msg + ')',self);
  137. end
  138. else
  139. begin
  140. PQclear(res);
  141. PQFinish(ASQLDatabaseHandle);
  142. end;
  143. {$IfDef LinkDynamically}
  144. ReleasePostgres3;
  145. {$EndIf}
  146. end;
  147. function TPQConnection.GetTransactionHandle(trans : TSQLHandle): pointer;
  148. begin
  149. Result := trans;
  150. end;
  151. function TPQConnection.RollBack(trans : TSQLHandle) : boolean;
  152. var
  153. res : PPGresult;
  154. tr : TPQTrans;
  155. begin
  156. result := false;
  157. tr := trans as TPQTrans;
  158. res := PQexec(tr.PGConn, 'ROLLBACK');
  159. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  160. begin
  161. PQclear(res);
  162. result := false;
  163. DatabaseError(SErrRollbackFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self);
  164. end
  165. else
  166. begin
  167. PQclear(res);
  168. PQFinish(tr.PGConn);
  169. result := true;
  170. end;
  171. end;
  172. function TPQConnection.Commit(trans : TSQLHandle) : boolean;
  173. var
  174. res : PPGresult;
  175. tr : TPQTrans;
  176. begin
  177. result := false;
  178. tr := trans as TPQTrans;
  179. res := PQexec(tr.PGConn, 'COMMIT');
  180. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  181. begin
  182. PQclear(res);
  183. result := false;
  184. DatabaseError(SErrCommitFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self);
  185. end
  186. else
  187. begin
  188. PQclear(res);
  189. PQFinish(tr.PGConn);
  190. result := true;
  191. end;
  192. end;
  193. function TPQConnection.StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean;
  194. var
  195. res : PPGresult;
  196. tr : TPQTrans;
  197. msg : string;
  198. begin
  199. result := false;
  200. tr := trans as TPQTrans;
  201. tr.PGConn := PQconnectdb(pchar(FConnectString));
  202. if (PQstatus(tr.PGConn) = CONNECTION_BAD) then
  203. begin
  204. result := false;
  205. PQFinish(tr.PGConn);
  206. DatabaseError(SErrConnectionFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self);
  207. end
  208. else
  209. begin
  210. tr.ErrorOccured := False;
  211. res := PQexec(tr.PGConn, 'BEGIN');
  212. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  213. begin
  214. result := false;
  215. PQclear(res);
  216. msg := PQerrorMessage(tr.PGConn);
  217. PQFinish(tr.PGConn);
  218. DatabaseError(sErrTransactionFailed + ' (PostgreSQL: ' + msg + ')',self);
  219. end
  220. else
  221. begin
  222. PQclear(res);
  223. result := true;
  224. end;
  225. end;
  226. end;
  227. procedure TPQConnection.RollBackRetaining(trans : TSQLHandle);
  228. var
  229. res : PPGresult;
  230. tr : TPQTrans;
  231. msg : string;
  232. begin
  233. tr := trans as TPQTrans;
  234. res := PQexec(tr.PGConn, 'ROLLBACK');
  235. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  236. begin
  237. PQclear(res);
  238. DatabaseError(SErrRollbackFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self);
  239. end
  240. else
  241. begin
  242. PQclear(res);
  243. res := PQexec(tr.PGConn, 'BEGIN');
  244. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  245. begin
  246. PQclear(res);
  247. msg := PQerrorMessage(tr.PGConn);
  248. PQFinish(tr.PGConn);
  249. DatabaseError(sErrTransactionFailed + ' (PostgreSQL: ' + msg + ')',self);
  250. end
  251. else
  252. PQclear(res);
  253. end;
  254. end;
  255. procedure TPQConnection.CommitRetaining(trans : TSQLHandle);
  256. var
  257. res : PPGresult;
  258. tr : TPQTrans;
  259. msg : string;
  260. begin
  261. tr := trans as TPQTrans;
  262. res := PQexec(tr.PGConn, 'COMMIT');
  263. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  264. begin
  265. PQclear(res);
  266. DatabaseError(SErrCommitFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self);
  267. end
  268. else
  269. begin
  270. PQclear(res);
  271. res := PQexec(tr.PGConn, 'BEGIN');
  272. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  273. begin
  274. PQclear(res);
  275. msg := PQerrorMessage(tr.PGConn);
  276. PQFinish(tr.PGConn);
  277. DatabaseError(sErrTransactionFailed + ' (PostgreSQL: ' + msg + ')',self);
  278. end
  279. else
  280. PQclear(res);
  281. end;
  282. end;
  283. procedure TPQConnection.DoInternalConnect;
  284. var msg : string;
  285. begin
  286. {$IfDef LinkDynamically}
  287. InitialisePostgres3;
  288. {$EndIf}
  289. inherited dointernalconnect;
  290. FConnectString := '';
  291. if (UserName <> '') then FConnectString := FConnectString + ' user=''' + UserName + '''';
  292. if (Password <> '') then FConnectString := FConnectString + ' password=''' + Password + '''';
  293. if (HostName <> '') then FConnectString := FConnectString + ' host=''' + HostName + '''';
  294. if (DatabaseName <> '') then FConnectString := FConnectString + ' dbname=''' + DatabaseName + '''';
  295. if (Params.Text <> '') then FConnectString := FConnectString + ' '+Params.Text;
  296. FSQLDatabaseHandle := PQconnectdb(pchar(FConnectString));
  297. if (PQstatus(FSQLDatabaseHandle) = CONNECTION_BAD) then
  298. begin
  299. msg := PQerrorMessage(FSQLDatabaseHandle);
  300. dointernaldisconnect;
  301. DatabaseError(sErrConnectionFailed + ' (PostgreSQL: ' + msg + ')',self);
  302. end;
  303. // This does only work for pg>=8.0, so timestamps won't work with earlier versions of pg which are compiled with integer_datetimes on
  304. FIntegerDatetimes := pqparameterstatus(FSQLDatabaseHandle,'integer_datetimes') = 'on';
  305. end;
  306. procedure TPQConnection.DoInternalDisconnect;
  307. begin
  308. PQfinish(FSQLDatabaseHandle);
  309. {$IfDef LinkDynamically}
  310. ReleasePostgres3;
  311. {$EndIf}
  312. end;
  313. function TPQConnection.TranslateFldType(Type_Oid : integer) : TFieldType;
  314. begin
  315. case Type_Oid of
  316. Oid_varchar,Oid_bpchar,
  317. Oid_name : Result := ftstring;
  318. // Oid_text : Result := ftstring;
  319. Oid_text : Result := ftBlob;
  320. Oid_oid : Result := ftInteger;
  321. Oid_int8 : Result := ftLargeInt;
  322. Oid_int4 : Result := ftInteger;
  323. Oid_int2 : Result := ftSmallInt;
  324. Oid_Float4 : Result := ftFloat;
  325. Oid_Float8 : Result := ftFloat;
  326. Oid_TimeStamp : Result := ftDateTime;
  327. Oid_Date : Result := ftDate;
  328. Oid_Time : Result := ftTime;
  329. Oid_Bool : Result := ftBoolean;
  330. Oid_Numeric : Result := ftBCD;
  331. Oid_Unknown : Result := ftUnknown;
  332. else
  333. Result := ftUnknown;
  334. end;
  335. end;
  336. Function TPQConnection.AllocateCursorHandle : TSQLCursor;
  337. begin
  338. result := TPQCursor.create;
  339. end;
  340. Procedure TPQConnection.DeAllocateCursorHandle(var cursor : TSQLCursor);
  341. begin
  342. FreeAndNil(cursor);
  343. end;
  344. Function TPQConnection.AllocateTransactionHandle : TSQLHandle;
  345. begin
  346. result := TPQTrans.create;
  347. end;
  348. procedure TPQConnection.PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams);
  349. const TypeStrings : array[TFieldType] of string =
  350. (
  351. 'Unknown',
  352. 'text',
  353. 'int',
  354. 'int',
  355. 'int',
  356. 'bool',
  357. 'float',
  358. 'numeric',
  359. 'numeric',
  360. 'date',
  361. 'time',
  362. 'timestamp',
  363. 'Unknown',
  364. 'Unknown',
  365. 'Unknown',
  366. 'Unknown',
  367. 'Unknown',
  368. 'Unknown',
  369. 'Unknown',
  370. 'Unknown',
  371. 'Unknown',
  372. 'Unknown',
  373. 'Unknown',
  374. 'Unknown',
  375. 'Unknown',
  376. 'int',
  377. 'Unknown',
  378. 'Unknown',
  379. 'Unknown',
  380. 'Unknown',
  381. 'Unknown',
  382. 'Unknown',
  383. 'Unknown',
  384. 'Unknown',
  385. 'Unknown',
  386. 'Unknown',
  387. 'Unknown',
  388. 'Unknown'
  389. );
  390. var s : string;
  391. i : integer;
  392. begin
  393. with (cursor as TPQCursor) do
  394. begin
  395. FPrepared := False;
  396. nr := inttostr(FCursorcount);
  397. inc(FCursorCount);
  398. // Prior to v8 there is no support for cursors and parameters.
  399. // So that's not supported.
  400. if FStatementType in [stInsert,stUpdate,stDelete, stSelect] then
  401. begin
  402. tr := TPQTrans(aTransaction.Handle);
  403. // Only available for pq 8.0, so don't use it...
  404. // Res := pqprepare(tr,'prepst'+name+nr,pchar(buf),params.Count,pchar(''));
  405. s := 'prepare prepst'+nr+' ';
  406. if Assigned(AParams) and (AParams.count > 0) then
  407. begin
  408. s := s + '(';
  409. for i := 0 to AParams.count-1 do if TypeStrings[AParams[i].DataType] <> 'Unknown' then
  410. s := s + TypeStrings[AParams[i].DataType] + ','
  411. else
  412. begin
  413. if AParams[i].DataType = ftUnknown then DatabaseErrorFmt(SUnknownParamFieldType,[AParams[i].Name],self)
  414. else DatabaseErrorFmt(SUnsupportedParameter,[Fieldtypenames[AParams[i].DataType]],self);
  415. end;
  416. s[length(s)] := ')';
  417. buf := AParams.ParseSQL(buf,false,psPostgreSQL);
  418. end;
  419. s := s + ' as ' + buf;
  420. res := pqexec(tr.PGConn,pchar(s));
  421. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  422. begin
  423. pqclear(res);
  424. DatabaseError(SErrPrepareFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self)
  425. end;
  426. FPrepared := True;
  427. end
  428. else
  429. statement := buf;
  430. end;
  431. end;
  432. procedure TPQConnection.UnPrepareStatement(cursor : TSQLCursor);
  433. begin
  434. with (cursor as TPQCursor) do if FPrepared then
  435. begin
  436. if not tr.ErrorOccured then
  437. begin
  438. res := pqexec(tr.PGConn,pchar('deallocate prepst'+nr));
  439. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  440. begin
  441. pqclear(res);
  442. DatabaseError(SErrPrepareFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self)
  443. end;
  444. pqclear(res);
  445. end;
  446. FPrepared := False;
  447. end;
  448. end;
  449. procedure TPQConnection.Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams);
  450. var ar : array of pchar;
  451. i : integer;
  452. s : string;
  453. begin
  454. with cursor as TPQCursor do
  455. begin
  456. if FStatementType in [stInsert,stUpdate,stDelete,stSelect] then
  457. begin
  458. if Assigned(AParams) and (AParams.count > 0) then
  459. begin
  460. setlength(ar,Aparams.count);
  461. for i := 0 to AParams.count -1 do if not AParams[i].IsNull then
  462. begin
  463. case AParams[i].DataType of
  464. ftdatetime : s := formatdatetime('YYYY-MM-DD',AParams[i].AsDateTime);
  465. ftdate : s := formatdatetime('YYYY-MM-DD',AParams[i].AsDateTime);
  466. else
  467. s := AParams[i].asstring;
  468. end; {case}
  469. GetMem(ar[i],length(s)+1);
  470. StrMove(PChar(ar[i]),Pchar(s),Length(S)+1);
  471. end
  472. else
  473. FreeAndNil(ar[i]);
  474. res := PQexecPrepared(tr.PGConn,pchar('prepst'+nr),Aparams.count,@Ar[0],nil,nil,1);
  475. for i := 0 to AParams.count -1 do
  476. FreeMem(ar[i]);
  477. end
  478. else
  479. res := PQexecPrepared(tr.PGConn,pchar('prepst'+nr),0,nil,nil,nil,1);
  480. end
  481. else
  482. begin
  483. tr := TPQTrans(aTransaction.Handle);
  484. s := statement;
  485. //Should be altered, just like in TSQLQuery.ApplyRecUpdate
  486. if assigned(AParams) then for i := 0 to AParams.count-1 do
  487. s := stringreplace(s,':'+AParams[i].Name,AParams[i].asstring,[rfReplaceAll,rfIgnoreCase]);
  488. res := pqexec(tr.PGConn,pchar(s));
  489. end;
  490. if not (PQresultStatus(res) in [PGRES_COMMAND_OK,PGRES_TUPLES_OK]) then
  491. begin
  492. s := PQerrorMessage(tr.PGConn);
  493. pqclear(res);
  494. tr.ErrorOccured := True;
  495. // Don't perform the rollback, only make it possible to do a rollback.
  496. // The other databases also don't do this.
  497. // atransaction.Rollback;
  498. DatabaseError(SErrExecuteFailed + ' (PostgreSQL: ' + s + ')',self);
  499. end;
  500. end;
  501. end;
  502. procedure TPQConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs);
  503. var
  504. i : integer;
  505. size : integer;
  506. st : string;
  507. fieldtype : tfieldtype;
  508. nFields : integer;
  509. begin
  510. with cursor as TPQCursor do
  511. begin
  512. nFields := PQnfields(Res);
  513. for i := 0 to nFields-1 do
  514. begin
  515. size := PQfsize(Res, i);
  516. fieldtype := TranslateFldType(PQftype(Res, i));
  517. if (fieldtype = ftstring) and (size = -1) then
  518. begin
  519. size := pqfmod(res,i)-4;
  520. if size = -5 then size := dsMaxStringSize;
  521. end
  522. else if fieldtype = ftdate then
  523. size := sizeof(double)
  524. else if fieldtype = ftblob then
  525. size := 0;
  526. TFieldDef.Create(FieldDefs, PQfname(Res, i), fieldtype,size, False, (i + 1));
  527. end;
  528. CurTuple := -1;
  529. end;
  530. end;
  531. function TPQConnection.GetHandle: pointer;
  532. begin
  533. Result := FSQLDatabaseHandle;
  534. end;
  535. function TPQConnection.Fetch(cursor : TSQLCursor) : boolean;
  536. var st : string;
  537. begin
  538. with cursor as TPQCursor do
  539. begin
  540. inc(CurTuple);
  541. Result := (PQntuples(res)>CurTuple);
  542. end;
  543. end;
  544. function TPQConnection.LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer) : boolean;
  545. type TNumericRecord = record
  546. Digits : SmallInt;
  547. Weight : SmallInt;
  548. Sign : SmallInt;
  549. Scale : Smallint;
  550. end;
  551. var
  552. x,i : integer;
  553. li : Longint;
  554. CurrBuff : pchar;
  555. tel : byte;
  556. dbl : pdouble;
  557. cur : currency;
  558. NumericRecord : ^TNumericRecord;
  559. s : string;
  560. begin
  561. with cursor as TPQCursor do
  562. begin
  563. for x := 0 to PQnfields(res)-1 do
  564. if PQfname(Res, x) = FieldDef.Name then break;
  565. if PQfname(Res, x) <> FieldDef.Name then
  566. DatabaseErrorFmt(SFieldNotFound,[FieldDef.Name],self);
  567. if pqgetisnull(res,CurTuple,x)=1 then
  568. result := false
  569. else
  570. begin
  571. i := PQfsize(res, x);
  572. CurrBuff := pqgetvalue(res,CurTuple,x);
  573. result := true;
  574. case FieldDef.DataType of
  575. ftInteger, ftSmallint, ftLargeInt,ftfloat :
  576. begin
  577. case i of // postgres returns big-endian numbers
  578. sizeof(int64) : pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  579. sizeof(integer) : pinteger(buffer)^ := BEtoN(pinteger(CurrBuff)^);
  580. sizeof(smallint) : psmallint(buffer)^ := BEtoN(psmallint(CurrBuff)^);
  581. else
  582. for tel := 1 to i do
  583. pchar(Buffer)[tel-1] := CurrBuff[i-tel];
  584. end; {case}
  585. end;
  586. ftString :
  587. begin
  588. li := pqgetlength(res,curtuple,x);
  589. Move(CurrBuff^, Buffer^, li);
  590. pchar(Buffer + li)^ := #0;
  591. i := pqfmod(res,x)-3;
  592. end;
  593. ftBlob :
  594. begin
  595. li := pqgetlength(res,curtuple,x);
  596. setlength(s,li);
  597. Move(CurrBuff^, s[1], li);
  598. i := fBlobStrings.Add(S);
  599. Move(I, Buffer^, SizeOf(Integer));
  600. end;
  601. ftdate :
  602. begin
  603. dbl := pointer(buffer);
  604. dbl^ := BEtoN(plongint(CurrBuff)^) + 36526;
  605. i := sizeof(double);
  606. end;
  607. ftDateTime, fttime :
  608. begin
  609. pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  610. dbl := pointer(buffer);
  611. if FIntegerDatetimes then dbl^ := pint64(buffer)^/1000000;
  612. dbl^ := (dbl^+3.1558464E+009)/86400; // postgres counts seconds elapsed since 1-1-2000
  613. // Now convert the mathematically-correct datetime to the
  614. // illogical windows/delphi/fpc TDateTime:
  615. if (dbl^ <= 0) and (frac(dbl^)<0) then
  616. dbl^ := trunc(dbl^)-2-frac(dbl^);
  617. end;
  618. ftBCD:
  619. begin
  620. NumericRecord := pointer(CurrBuff);
  621. NumericRecord^.Digits := BEtoN(NumericRecord^.Digits);
  622. NumericRecord^.Scale := BEtoN(NumericRecord^.Scale);
  623. NumericRecord^.Weight := BEtoN(NumericRecord^.Weight);
  624. inc(pointer(currbuff),sizeof(TNumericRecord));
  625. cur := 0;
  626. if (NumericRecord^.Digits = 0) and (NumericRecord^.Scale = 0) then // = NaN, which is not supported by Currency-type, so we return NULL
  627. result := false
  628. else
  629. begin
  630. for tel := 1 to NumericRecord^.Digits do
  631. begin
  632. cur := cur + beton(pword(currbuff)^) * intpower(10000,-(tel-1)+NumericRecord^.weight);
  633. inc(pointer(currbuff),2);
  634. end;
  635. if BEtoN(NumericRecord^.Sign) <> 0 then cur := -cur;
  636. Move(Cur, Buffer^, sizeof(currency));
  637. end;
  638. end;
  639. ftBoolean:
  640. pchar(buffer)[0] := CurrBuff[0]
  641. else
  642. result := false;
  643. end;
  644. end;
  645. end;
  646. end;
  647. procedure TPQConnection.UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string);
  648. var qry : TSQLQuery;
  649. begin
  650. if not assigned(Transaction) then
  651. DatabaseError(SErrConnTransactionnSet);
  652. qry := tsqlquery.Create(nil);
  653. qry.transaction := Transaction;
  654. qry.database := Self;
  655. with qry do
  656. begin
  657. ReadOnly := True;
  658. sql.clear;
  659. sql.add('select '+
  660. 'ic.relname as indexname, '+
  661. 'tc.relname as tablename, '+
  662. 'ia.attname, '+
  663. 'i.indisprimary, '+
  664. 'i.indisunique '+
  665. 'from '+
  666. 'pg_attribute ta, '+
  667. 'pg_attribute ia, '+
  668. 'pg_class tc, '+
  669. 'pg_class ic, '+
  670. 'pg_index i '+
  671. 'where '+
  672. '(i.indrelid = tc.oid) and '+
  673. '(ta.attrelid = tc.oid) and '+
  674. '(ia.attrelid = i.indexrelid) and '+
  675. '(ic.oid = i.indexrelid) and '+
  676. '(ta.attnum = i.indkey[ia.attnum-1]) and '+
  677. '(upper(tc.relname)=''' + UpperCase(TableName) +''') '+
  678. 'order by '+
  679. 'ic.relname;');
  680. open;
  681. end;
  682. while not qry.eof do with IndexDefs.AddIndexDef do
  683. begin
  684. Name := trim(qry.fields[0].asstring);
  685. Fields := trim(qry.Fields[2].asstring);
  686. If qry.fields[3].asboolean then options := options + [ixPrimary];
  687. If qry.fields[4].asboolean then options := options + [ixUnique];
  688. qry.next;
  689. while (name = qry.fields[0].asstring) and (not qry.eof) do
  690. begin
  691. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  692. qry.next;
  693. end;
  694. end;
  695. qry.close;
  696. qry.free;
  697. end;
  698. function TPQConnection.GetSchemaInfoSQL(SchemaType: TSchemaType;
  699. SchemaObjectName, SchemaPattern: string): string;
  700. var s : string;
  701. begin
  702. case SchemaType of
  703. stTables : s := 'select '+
  704. 'relfilenode as recno, '+
  705. '''' + DatabaseName + ''' as catalog_name, '+
  706. ''''' as schema_name, '+
  707. 'relname as table_name, '+
  708. '0 as table_type '+
  709. 'from '+
  710. 'pg_class '+
  711. 'where '+
  712. '(relowner > 1) and relkind=''r''' +
  713. 'order by relname';
  714. stSysTables : s := 'select '+
  715. 'relfilenode as recno, '+
  716. '''' + DatabaseName + ''' as catalog_name, '+
  717. ''''' as schema_name, '+
  718. 'relname as table_name, '+
  719. '0 as table_type '+
  720. 'from '+
  721. 'pg_class '+
  722. 'where '+
  723. 'relkind=''r''' +
  724. 'order by relname';
  725. else
  726. DatabaseError(SMetadataUnavailable)
  727. end; {case}
  728. result := s;
  729. end;
  730. end.