pqconnection.pp 24 KB

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