pqconnection.pp 29 KB

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