pqconnection.pp 29 KB

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