pqconnection.pp 22 KB

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