pqconnection.pp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  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. {
  389. TFieldType = (ftUnknown, ftString, ftSmallint, ftInteger, ftWord,
  390. ftBoolean, ftFloat, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime,
  391. ftBytes, ftVarBytes, ftAutoInc, ftBlob, ftMemo, ftGraphic, ftFmtMemo,
  392. ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftFixedChar,
  393. ftWideString, ftLargeint, ftADT, ftArray, ftReference,
  394. ftDataSet, ftOraBlob, ftOraClob, ftVariant, ftInterface,
  395. ftIDispatch, ftGuid, ftTimeStamp, ftFMTBcd, ftFixedWideChar, ftWideMemo);
  396. }
  397. const TypeStrings : array[TFieldType] of string =
  398. (
  399. 'Unknown', // ftUnknown
  400. 'text', // ftString
  401. 'int', // ftSmallint
  402. 'int', // ftInteger
  403. 'int', // ftWord
  404. 'bool', // ftBoolean
  405. 'float', // ftFloat
  406. 'numeric', // ftCurrency
  407. 'numeric', // ftBCD
  408. 'date', // ftDate
  409. 'time', // ftTime
  410. 'timestamp', // ftDateTime
  411. 'Unknown', // ftBytes
  412. 'Unknown', // ftVarBytes
  413. 'Unknown', // ftAutoInc
  414. 'bytea', // ftBlob
  415. 'text', // ftMemo
  416. 'bytea', // ftGraphic
  417. 'text', // ftFmtMemo
  418. 'Unknown', // ftParadoxOle
  419. 'Unknown', // ftDBaseOle
  420. 'Unknown', // ftTypedBinary
  421. 'Unknown', // ftCursor
  422. 'text', // ftFixedChar
  423. 'text', // ftWideString
  424. 'bigint', // ftLargeint
  425. 'Unknown', // ftADT
  426. 'Unknown', // ftArray
  427. 'Unknown', // ftReference
  428. 'Unknown', // ftDataSet
  429. 'Unknown', // ftOraBlob
  430. 'Unknown', // ftOraClob
  431. 'Unknown', // ftVariant
  432. 'Unknown', // ftInterface
  433. 'Unknown', // ftIDispatch
  434. 'Unknown', // ftGuid
  435. 'Unknown', // ftTimeStamp
  436. 'Unknown', // ftFMTBcd
  437. 'Unknown', // ftFixedWideChar
  438. 'Unknown' // ftWideMemo
  439. );
  440. var s : string;
  441. i : integer;
  442. begin
  443. with (cursor as TPQCursor) do
  444. begin
  445. FPrepared := False;
  446. nr := inttostr(FCursorcount);
  447. inc(FCursorCount);
  448. // Prior to v8 there is no support for cursors and parameters.
  449. // So that's not supported.
  450. if FStatementType in [stInsert,stUpdate,stDelete, stSelect] then
  451. begin
  452. tr := TPQTrans(aTransaction.Handle);
  453. // Only available for pq 8.0, so don't use it...
  454. // Res := pqprepare(tr,'prepst'+name+nr,pchar(buf),params.Count,pchar(''));
  455. s := 'prepare prepst'+nr+' ';
  456. if Assigned(AParams) and (AParams.count > 0) then
  457. begin
  458. s := s + '(';
  459. for i := 0 to AParams.count-1 do if TypeStrings[AParams[i].DataType] <> 'Unknown' then
  460. s := s + TypeStrings[AParams[i].DataType] + ','
  461. else
  462. begin
  463. if AParams[i].DataType = ftUnknown then
  464. DatabaseErrorFmt(SUnknownParamFieldType,[AParams[i].Name],self)
  465. else
  466. DatabaseErrorFmt(SUnsupportedParameter,[Fieldtypenames[AParams[i].DataType]],self);
  467. end;
  468. s[length(s)] := ')';
  469. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psPostgreSQL);
  470. end;
  471. s := s + ' as ' + buf;
  472. res := pqexec(tr.PGConn,pchar(s));
  473. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  474. begin
  475. pqclear(res);
  476. DatabaseError(SErrPrepareFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self)
  477. end;
  478. FPrepared := True;
  479. end
  480. else
  481. statement := buf;
  482. end;
  483. end;
  484. procedure TPQConnection.UnPrepareStatement(cursor : TSQLCursor);
  485. begin
  486. with (cursor as TPQCursor) do if FPrepared then
  487. begin
  488. if not tr.ErrorOccured then
  489. begin
  490. PQclear(res);
  491. res := pqexec(tr.PGConn,pchar('deallocate prepst'+nr));
  492. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  493. begin
  494. pqclear(res);
  495. DatabaseError(SErrPrepareFailed + ' (PostgreSQL: ' + PQerrorMessage(tr.PGConn) + ')',self)
  496. end;
  497. pqclear(res);
  498. end;
  499. FPrepared := False;
  500. end;
  501. end;
  502. procedure TPQConnection.Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams);
  503. var ar : array of pchar;
  504. i : integer;
  505. s : string;
  506. ParamNames,ParamValues : array of string;
  507. begin
  508. with cursor as TPQCursor do
  509. begin
  510. if FStatementType in [stInsert,stUpdate,stDelete,stSelect] then
  511. begin
  512. pqclear(res);
  513. if Assigned(AParams) and (AParams.count > 0) then
  514. begin
  515. setlength(ar,Aparams.count);
  516. for i := 0 to AParams.count -1 do if not AParams[i].IsNull then
  517. begin
  518. case AParams[i].DataType of
  519. ftDateTime:
  520. s := FormatDateTime('yyyy-mm-dd hh:nn:ss', AParams[i].AsDateTime);
  521. ftDate:
  522. s := FormatDateTime('yyyy-mm-dd', AParams[i].AsDateTime);
  523. ftTime:
  524. s := FormatDateTime('hh:nn:ss', AParams[i].AsDateTime);
  525. ftFloat, ftCurrency:
  526. Str(AParams[i].AsFloat, s);
  527. else
  528. s := AParams[i].AsString;
  529. end; {case}
  530. GetMem(ar[i],length(s)+1);
  531. StrMove(PChar(ar[i]),Pchar(s),Length(S)+1);
  532. end
  533. else
  534. FreeAndNil(ar[i]);
  535. res := PQexecPrepared(tr.PGConn,pchar('prepst'+nr),Aparams.count,@Ar[0],nil,nil,1);
  536. for i := 0 to AParams.count -1 do
  537. FreeMem(ar[i]);
  538. end
  539. else
  540. res := PQexecPrepared(tr.PGConn,pchar('prepst'+nr),0,nil,nil,nil,1);
  541. end
  542. else
  543. begin
  544. tr := TPQTrans(aTransaction.Handle);
  545. if Assigned(AParams) and (AParams.count > 0) then
  546. begin
  547. setlength(ParamNames,AParams.Count);
  548. setlength(ParamValues,AParams.Count);
  549. for i := 0 to AParams.count -1 do
  550. begin
  551. ParamNames[AParams.count-i-1] := '$'+inttostr(AParams[i].index+1);
  552. ParamValues[AParams.count-i-1] := GetAsSQLText(AParams[i]);
  553. end;
  554. s := stringsreplace(statement,ParamNames,ParamValues,[rfReplaceAll]);
  555. end
  556. else
  557. s := Statement;
  558. res := pqexec(tr.PGConn,pchar(s));
  559. if (PQresultStatus(res) in [PGRES_COMMAND_OK,PGRES_TUPLES_OK]) then
  560. pqclear(res);
  561. end;
  562. if not (PQresultStatus(res) in [PGRES_COMMAND_OK,PGRES_TUPLES_OK]) then
  563. begin
  564. s := PQerrorMessage(tr.PGConn);
  565. pqclear(res);
  566. tr.ErrorOccured := True;
  567. // Don't perform the rollback, only make it possible to do a rollback.
  568. // The other databases also don't do this.
  569. // atransaction.Rollback;
  570. DatabaseError(SErrExecuteFailed + ' (PostgreSQL: ' + s + ')',self);
  571. end;
  572. end;
  573. end;
  574. procedure TPQConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs);
  575. var
  576. i : integer;
  577. size : integer;
  578. fieldtype : tfieldtype;
  579. nFields : integer;
  580. begin
  581. with cursor as TPQCursor do
  582. begin
  583. nFields := PQnfields(Res);
  584. setlength(FieldBinding,nFields);
  585. for i := 0 to nFields-1 do
  586. begin
  587. fieldtype := TranslateFldType(Res, i,size);
  588. with TFieldDef.Create(FieldDefs, FieldDefs.MakeNameUnique(PQfname(Res, i)), fieldtype,size, False, (i + 1)) do
  589. FieldBinding[FieldNo-1] := i;
  590. end;
  591. CurTuple := -1;
  592. end;
  593. end;
  594. function TPQConnection.GetHandle: pointer;
  595. begin
  596. Result := FSQLDatabaseHandle;
  597. end;
  598. function TPQConnection.Fetch(cursor : TSQLCursor) : boolean;
  599. begin
  600. with cursor as TPQCursor do
  601. begin
  602. inc(CurTuple);
  603. Result := (PQntuples(res)>CurTuple);
  604. end;
  605. end;
  606. function TPQConnection.LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  607. type TNumericRecord = record
  608. Digits : SmallInt;
  609. Weight : SmallInt;
  610. Sign : SmallInt;
  611. Scale : Smallint;
  612. end;
  613. var
  614. x,i : integer;
  615. li : Longint;
  616. CurrBuff : pchar;
  617. tel : byte;
  618. dbl : pdouble;
  619. cur : currency;
  620. NumericRecord : ^TNumericRecord;
  621. begin
  622. Createblob := False;
  623. with cursor as TPQCursor do
  624. begin
  625. x := FieldBinding[FieldDef.FieldNo-1];
  626. // Joost, 5 jan 2006: I disabled the following, since it's useful for
  627. // debugging, but it also slows things down. In principle things can only go
  628. // wrong when FieldDefs is changed while the dataset is opened. A user just
  629. // shoudn't do that. ;) (The same is done in IBConnection)
  630. //if PQfname(Res, x) <> FieldDef.Name then
  631. // DatabaseErrorFmt(SFieldNotFound,[FieldDef.Name],self);
  632. if pqgetisnull(res,CurTuple,x)=1 then
  633. result := false
  634. else
  635. begin
  636. CurrBuff := pqgetvalue(res,CurTuple,x);
  637. result := true;
  638. case FieldDef.DataType of
  639. ftInteger, ftSmallint, ftLargeInt,ftfloat :
  640. begin
  641. i := PQfsize(res, x);
  642. case i of // postgres returns big-endian numbers
  643. sizeof(int64) : pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  644. sizeof(integer) : pinteger(buffer)^ := BEtoN(pinteger(CurrBuff)^);
  645. sizeof(smallint) : psmallint(buffer)^ := BEtoN(psmallint(CurrBuff)^);
  646. else
  647. for tel := 1 to i do
  648. pchar(Buffer)[tel-1] := CurrBuff[i-tel];
  649. end; {case}
  650. end;
  651. ftString :
  652. begin
  653. li := pqgetlength(res,curtuple,x);
  654. if li > dsMaxStringSize then li := dsMaxStringSize;
  655. Move(CurrBuff^, Buffer^, li);
  656. pchar(Buffer + li)^ := #0;
  657. end;
  658. ftBlob : Createblob := True;
  659. ftdate :
  660. begin
  661. dbl := pointer(buffer);
  662. dbl^ := BEtoN(plongint(CurrBuff)^) + 36526;
  663. end;
  664. ftDateTime, fttime :
  665. begin
  666. pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  667. dbl := pointer(buffer);
  668. if FIntegerDatetimes then dbl^ := pint64(buffer)^/1000000;
  669. dbl^ := (dbl^+3.1558464E+009)/86400; // postgres counts seconds elapsed since 1-1-2000
  670. // Now convert the mathematically-correct datetime to the
  671. // illogical windows/delphi/fpc TDateTime:
  672. if (dbl^ <= 0) and (frac(dbl^)<0) then
  673. dbl^ := trunc(dbl^)-2-frac(dbl^);
  674. end;
  675. ftBCD:
  676. begin
  677. NumericRecord := pointer(CurrBuff);
  678. NumericRecord^.Digits := BEtoN(NumericRecord^.Digits);
  679. NumericRecord^.Scale := BEtoN(NumericRecord^.Scale);
  680. NumericRecord^.Weight := BEtoN(NumericRecord^.Weight);
  681. inc(pointer(currbuff),sizeof(TNumericRecord));
  682. cur := 0;
  683. if (NumericRecord^.Digits = 0) and (NumericRecord^.Scale = 0) then // = NaN, which is not supported by Currency-type, so we return NULL
  684. result := false
  685. else
  686. begin
  687. for tel := 1 to NumericRecord^.Digits do
  688. begin
  689. cur := cur + beton(pword(currbuff)^) * intpower(10000,-(tel-1)+NumericRecord^.weight);
  690. inc(pointer(currbuff),2);
  691. end;
  692. if BEtoN(NumericRecord^.Sign) <> 0 then cur := -cur;
  693. Move(Cur, Buffer^, sizeof(currency));
  694. end;
  695. end;
  696. ftCurrency :
  697. begin
  698. dbl := pointer(buffer);
  699. dbl^ := BEtoN(PInt64(CurrBuff)^) / 100;
  700. end;
  701. ftBoolean:
  702. pchar(buffer)[0] := CurrBuff[0]
  703. else
  704. result := false;
  705. end;
  706. end;
  707. end;
  708. end;
  709. procedure TPQConnection.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  710. var qry : TSQLQuery;
  711. begin
  712. if not assigned(Transaction) then
  713. DatabaseError(SErrConnTransactionnSet);
  714. qry := tsqlquery.Create(nil);
  715. qry.transaction := Transaction;
  716. qry.database := Self;
  717. with qry do
  718. begin
  719. ReadOnly := True;
  720. sql.clear;
  721. sql.add('select '+
  722. 'ic.relname as indexname, '+
  723. 'tc.relname as tablename, '+
  724. 'ia.attname, '+
  725. 'i.indisprimary, '+
  726. 'i.indisunique '+
  727. 'from '+
  728. 'pg_attribute ta, '+
  729. 'pg_attribute ia, '+
  730. 'pg_class tc, '+
  731. 'pg_class ic, '+
  732. 'pg_index i '+
  733. 'where '+
  734. '(i.indrelid = tc.oid) and '+
  735. '(ta.attrelid = tc.oid) and '+
  736. '(ia.attrelid = i.indexrelid) and '+
  737. '(ic.oid = i.indexrelid) and '+
  738. '(ta.attnum = i.indkey[ia.attnum-1]) and '+
  739. '(upper(tc.relname)=''' + UpperCase(TableName) +''') '+
  740. 'order by '+
  741. 'ic.relname;');
  742. open;
  743. end;
  744. while not qry.eof do with IndexDefs.AddIndexDef do
  745. begin
  746. Name := trim(qry.fields[0].asstring);
  747. Fields := trim(qry.Fields[2].asstring);
  748. If qry.fields[3].asboolean then options := options + [ixPrimary];
  749. If qry.fields[4].asboolean then options := options + [ixUnique];
  750. qry.next;
  751. while (name = qry.fields[0].asstring) and (not qry.eof) do
  752. begin
  753. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  754. qry.next;
  755. end;
  756. end;
  757. qry.close;
  758. qry.free;
  759. end;
  760. function TPQConnection.GetSchemaInfoSQL(SchemaType: TSchemaType;
  761. SchemaObjectName, SchemaPattern: string): string;
  762. var s : string;
  763. begin
  764. case SchemaType of
  765. stTables : 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. '(relowner > 1) and relkind=''r''' +
  775. 'order by relname';
  776. stSysTables : s := 'select '+
  777. 'relfilenode as recno, '+
  778. '''' + DatabaseName + ''' as catalog_name, '+
  779. ''''' as schema_name, '+
  780. 'relname as table_name, '+
  781. '0 as table_type '+
  782. 'from '+
  783. 'pg_class '+
  784. 'where '+
  785. 'relkind=''r''' +
  786. 'order by relname';
  787. stColumns : s := 'select '+
  788. 'a.attnum as recno, '+
  789. ''''' as catalog_name, '+
  790. ''''' as schema_name, '+
  791. 'c.relname as table_name, '+
  792. 'a.attname as column_name, '+
  793. '0 as column_position, '+
  794. '0 as column_type, '+
  795. '0 as column_datatype, '+
  796. ''''' as column_typename, '+
  797. '0 as column_subtype, '+
  798. '0 as column_precision, '+
  799. '0 as column_scale, '+
  800. 'a.atttypmod as column_length, '+
  801. 'not a.attnotnull as column_nullable '+
  802. 'from '+
  803. ' pg_class c, pg_attribute a '+
  804. 'WHERE '+
  805. // This can lead to problems when case-sensitive tablenames are used.
  806. '(c.oid=a.attrelid) and (a.attnum>0) and (not a.attisdropped) and (upper(c.relname)=''' + Uppercase(SchemaObjectName) + ''') ' +
  807. 'order by a.attname';
  808. else
  809. DatabaseError(SMetadataUnavailable)
  810. end; {case}
  811. result := s;
  812. end;
  813. procedure TPQConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  814. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  815. var
  816. x : integer;
  817. li : Longint;
  818. begin
  819. with cursor as TPQCursor do
  820. begin
  821. x := FieldBinding[FieldDef.FieldNo-1];
  822. li := pqgetlength(res,curtuple,x);
  823. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer,li);
  824. Move(pqgetvalue(res,CurTuple,x)^, ABlobBuf^.BlobBuffer^.Buffer^, li);
  825. ABlobBuf^.BlobBuffer^.Size := li;
  826. end;
  827. end;
  828. function TPQConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  829. begin
  830. if assigned(cursor) and assigned((cursor as TPQCursor).res) then
  831. Result := StrToIntDef(PQcmdTuples((cursor as TPQCursor).res),-1)
  832. else
  833. Result := -1;
  834. end;
  835. { TPQConnectionDef }
  836. class function TPQConnectionDef.TypeName: String;
  837. begin
  838. Result:='PostGreSQL';
  839. end;
  840. class function TPQConnectionDef.ConnectionClass: TSQLConnectionClass;
  841. begin
  842. Result:=TPQConnection;
  843. end;
  844. class function TPQConnectionDef.Description: String;
  845. begin
  846. Result:='Connect to a PostGreSQL database directly via the client library';
  847. end;
  848. initialization
  849. RegisterConnection(TPQConnectionDef);
  850. finalization
  851. UnRegisterConnection(TPQConnectionDef);
  852. end.