pqconnection.pp 22 KB

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