pqconnection.pp 24 KB

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