pqconnection.pp 31 KB

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