pqconnection.pp 25 KB

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