pqconnection.pp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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 := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psPostgreSQL);
  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. else
  498. pqclear(res);
  499. end;
  500. FPrepared := False;
  501. end;
  502. end;
  503. procedure TPQConnection.Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams);
  504. var ar : array of pchar;
  505. l,i : integer;
  506. s : string;
  507. lengths,formats : array of integer;
  508. ParamNames,
  509. ParamValues : array of string;
  510. begin
  511. with cursor as TPQCursor do
  512. begin
  513. if FStatementType in [stInsert,stUpdate,stDelete,stSelect] then
  514. begin
  515. pqclear(res);
  516. if Assigned(AParams) and (AParams.count > 0) then
  517. begin
  518. l:=Aparams.count;
  519. setlength(ar,l);
  520. setlength(lengths,l);
  521. setlength(formats,l);
  522. for i := 0 to AParams.count -1 do if not AParams[i].IsNull then
  523. begin
  524. case AParams[i].DataType of
  525. ftDateTime:
  526. s := FormatDateTime('yyyy-mm-dd hh:nn:ss', AParams[i].AsDateTime);
  527. ftDate:
  528. s := FormatDateTime('yyyy-mm-dd', AParams[i].AsDateTime);
  529. ftTime:
  530. s := FormatDateTime('hh:nn:ss', AParams[i].AsDateTime);
  531. ftFloat, ftCurrency:
  532. Str(AParams[i].AsFloat, s);
  533. else
  534. s := AParams[i].AsString;
  535. end; {case}
  536. GetMem(ar[i],length(s)+1);
  537. StrMove(PChar(ar[i]),Pchar(s),Length(S)+1);
  538. lengths[i]:=Length(s);
  539. if (AParams[i].DataType in [ftBlob,ftgraphic]) then
  540. formats[i]:=1
  541. else
  542. Formats[i]:=0;
  543. end
  544. else
  545. FreeAndNil(ar[i]);
  546. res := PQexecPrepared(tr.PGConn,pchar('prepst'+nr),Aparams.count,@Ar[0],@Lengths[0],@Formats[0],1);
  547. for i := 0 to AParams.count -1 do
  548. FreeMem(ar[i]);
  549. end
  550. else
  551. res := PQexecPrepared(tr.PGConn,pchar('prepst'+nr),0,nil,nil,nil,1);
  552. end
  553. else
  554. begin
  555. tr := TPQTrans(aTransaction.Handle);
  556. if Assigned(AParams) and (AParams.count > 0) then
  557. begin
  558. setlength(ParamNames,AParams.Count);
  559. setlength(ParamValues,AParams.Count);
  560. for i := 0 to AParams.count -1 do
  561. begin
  562. ParamNames[AParams.count-i-1] := '$'+inttostr(AParams[i].index+1);
  563. ParamValues[AParams.count-i-1] := GetAsSQLText(AParams[i]);
  564. end;
  565. s := stringsreplace(statement,ParamNames,ParamValues,[rfReplaceAll]);
  566. end
  567. else
  568. s := Statement;
  569. res := pqexec(tr.PGConn,pchar(s));
  570. if (PQresultStatus(res) in [PGRES_COMMAND_OK,PGRES_TUPLES_OK]) then
  571. begin
  572. pqclear(res);
  573. res:=nil;
  574. end;
  575. end;
  576. if assigned(res) and not (PQresultStatus(res) in [PGRES_COMMAND_OK,PGRES_TUPLES_OK]) then
  577. begin
  578. s := PQerrorMessage(tr.PGConn);
  579. pqclear(res);
  580. tr.ErrorOccured := True;
  581. // Don't perform the rollback, only make it possible to do a rollback.
  582. // The other databases also don't do this.
  583. // atransaction.Rollback;
  584. DatabaseError(SErrExecuteFailed + ' (PostgreSQL: ' + s + ')',self);
  585. end;
  586. end;
  587. end;
  588. procedure TPQConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs);
  589. var
  590. i : integer;
  591. size : integer;
  592. fieldtype : tfieldtype;
  593. nFields : integer;
  594. begin
  595. with cursor as TPQCursor do
  596. begin
  597. nFields := PQnfields(Res);
  598. setlength(FieldBinding,nFields);
  599. for i := 0 to nFields-1 do
  600. begin
  601. fieldtype := TranslateFldType(Res, i,size);
  602. with TFieldDef.Create(FieldDefs, FieldDefs.MakeNameUnique(PQfname(Res, i)), fieldtype,size, False, (i + 1)) do
  603. FieldBinding[FieldNo-1] := i;
  604. end;
  605. CurTuple := -1;
  606. end;
  607. end;
  608. function TPQConnection.GetHandle: pointer;
  609. begin
  610. Result := FSQLDatabaseHandle;
  611. end;
  612. function TPQConnection.Fetch(cursor : TSQLCursor) : boolean;
  613. begin
  614. with cursor as TPQCursor do
  615. begin
  616. inc(CurTuple);
  617. Result := (PQntuples(res)>CurTuple);
  618. end;
  619. end;
  620. function TPQConnection.LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  621. type TNumericRecord = record
  622. Digits : SmallInt;
  623. Weight : SmallInt;
  624. Sign : SmallInt;
  625. Scale : Smallint;
  626. end;
  627. var
  628. x,i : integer;
  629. li : Longint;
  630. CurrBuff : pchar;
  631. tel : byte;
  632. dbl : pdouble;
  633. cur : currency;
  634. NumericRecord : ^TNumericRecord;
  635. begin
  636. Createblob := False;
  637. with cursor as TPQCursor do
  638. begin
  639. x := FieldBinding[FieldDef.FieldNo-1];
  640. // Joost, 5 jan 2006: I disabled the following, since it's useful for
  641. // debugging, but it also slows things down. In principle things can only go
  642. // wrong when FieldDefs is changed while the dataset is opened. A user just
  643. // shoudn't do that. ;) (The same is done in IBConnection)
  644. //if PQfname(Res, x) <> FieldDef.Name then
  645. // DatabaseErrorFmt(SFieldNotFound,[FieldDef.Name],self);
  646. if pqgetisnull(res,CurTuple,x)=1 then
  647. result := false
  648. else
  649. begin
  650. CurrBuff := pqgetvalue(res,CurTuple,x);
  651. result := true;
  652. case FieldDef.DataType of
  653. ftInteger, ftSmallint, ftLargeInt,ftfloat :
  654. begin
  655. i := PQfsize(res, x);
  656. case i of // postgres returns big-endian numbers
  657. sizeof(int64) : pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  658. sizeof(integer) : pinteger(buffer)^ := BEtoN(pinteger(CurrBuff)^);
  659. sizeof(smallint) : psmallint(buffer)^ := BEtoN(psmallint(CurrBuff)^);
  660. else
  661. for tel := 1 to i do
  662. pchar(Buffer)[tel-1] := CurrBuff[i-tel];
  663. end; {case}
  664. end;
  665. ftString :
  666. begin
  667. li := pqgetlength(res,curtuple,x);
  668. if li > dsMaxStringSize then li := dsMaxStringSize;
  669. Move(CurrBuff^, Buffer^, li);
  670. pchar(Buffer + li)^ := #0;
  671. end;
  672. ftBlob : Createblob := True;
  673. ftdate :
  674. begin
  675. dbl := pointer(buffer);
  676. dbl^ := BEtoN(plongint(CurrBuff)^) + 36526;
  677. end;
  678. ftDateTime, fttime :
  679. begin
  680. pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  681. dbl := pointer(buffer);
  682. if FIntegerDatetimes then dbl^ := pint64(buffer)^/1000000;
  683. dbl^ := (dbl^+3.1558464E+009)/86400; // postgres counts seconds elapsed since 1-1-2000
  684. // Now convert the mathematically-correct datetime to the
  685. // illogical windows/delphi/fpc TDateTime:
  686. if (dbl^ <= 0) and (frac(dbl^)<0) then
  687. dbl^ := trunc(dbl^)-2-frac(dbl^);
  688. end;
  689. ftBCD:
  690. begin
  691. NumericRecord := pointer(CurrBuff);
  692. NumericRecord^.Digits := BEtoN(NumericRecord^.Digits);
  693. NumericRecord^.Scale := BEtoN(NumericRecord^.Scale);
  694. NumericRecord^.Weight := BEtoN(NumericRecord^.Weight);
  695. inc(pointer(currbuff),sizeof(TNumericRecord));
  696. cur := 0;
  697. if (NumericRecord^.Digits = 0) and (NumericRecord^.Scale = 0) then // = NaN, which is not supported by Currency-type, so we return NULL
  698. result := false
  699. else
  700. begin
  701. for tel := 1 to NumericRecord^.Digits do
  702. begin
  703. cur := cur + beton(pword(currbuff)^) * intpower(10000,-(tel-1)+NumericRecord^.weight);
  704. inc(pointer(currbuff),2);
  705. end;
  706. if BEtoN(NumericRecord^.Sign) <> 0 then cur := -cur;
  707. Move(Cur, Buffer^, sizeof(currency));
  708. end;
  709. end;
  710. ftCurrency :
  711. begin
  712. dbl := pointer(buffer);
  713. dbl^ := BEtoN(PInt64(CurrBuff)^) / 100;
  714. end;
  715. ftBoolean:
  716. pchar(buffer)[0] := CurrBuff[0]
  717. else
  718. result := false;
  719. end;
  720. end;
  721. end;
  722. end;
  723. procedure TPQConnection.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  724. var qry : TSQLQuery;
  725. begin
  726. if not assigned(Transaction) then
  727. DatabaseError(SErrConnTransactionnSet);
  728. qry := tsqlquery.Create(nil);
  729. qry.transaction := Transaction;
  730. qry.database := Self;
  731. with qry do
  732. begin
  733. ReadOnly := True;
  734. sql.clear;
  735. sql.add('select '+
  736. 'ic.relname as indexname, '+
  737. 'tc.relname as tablename, '+
  738. 'ia.attname, '+
  739. 'i.indisprimary, '+
  740. 'i.indisunique '+
  741. 'from '+
  742. 'pg_attribute ta, '+
  743. 'pg_attribute ia, '+
  744. 'pg_class tc, '+
  745. 'pg_class ic, '+
  746. 'pg_index i '+
  747. 'where '+
  748. '(i.indrelid = tc.oid) and '+
  749. '(ta.attrelid = tc.oid) and '+
  750. '(ia.attrelid = i.indexrelid) and '+
  751. '(ic.oid = i.indexrelid) and '+
  752. '(ta.attnum = i.indkey[ia.attnum-1]) and '+
  753. '(upper(tc.relname)=''' + UpperCase(TableName) +''') '+
  754. 'order by '+
  755. 'ic.relname;');
  756. open;
  757. end;
  758. while not qry.eof do with IndexDefs.AddIndexDef do
  759. begin
  760. Name := trim(qry.fields[0].asstring);
  761. Fields := trim(qry.Fields[2].asstring);
  762. If qry.fields[3].asboolean then options := options + [ixPrimary];
  763. If qry.fields[4].asboolean then options := options + [ixUnique];
  764. qry.next;
  765. while (name = qry.fields[0].asstring) and (not qry.eof) do
  766. begin
  767. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  768. qry.next;
  769. end;
  770. end;
  771. qry.close;
  772. qry.free;
  773. end;
  774. function TPQConnection.GetSchemaInfoSQL(SchemaType: TSchemaType;
  775. SchemaObjectName, SchemaPattern: string): string;
  776. var s : string;
  777. begin
  778. case SchemaType of
  779. stTables : s := 'select '+
  780. 'relfilenode as recno, '+
  781. '''' + DatabaseName + ''' as catalog_name, '+
  782. ''''' as schema_name, '+
  783. 'relname as table_name, '+
  784. '0 as table_type '+
  785. 'from '+
  786. 'pg_class '+
  787. 'where '+
  788. '(relowner > 1) and relkind=''r''' +
  789. 'order by relname';
  790. stSysTables : s := 'select '+
  791. 'relfilenode as recno, '+
  792. '''' + DatabaseName + ''' as catalog_name, '+
  793. ''''' as schema_name, '+
  794. 'relname as table_name, '+
  795. '0 as table_type '+
  796. 'from '+
  797. 'pg_class '+
  798. 'where '+
  799. 'relkind=''r''' +
  800. 'order by relname';
  801. stColumns : s := 'select '+
  802. 'a.attnum as recno, '+
  803. ''''' as catalog_name, '+
  804. ''''' as schema_name, '+
  805. 'c.relname as table_name, '+
  806. 'a.attname as column_name, '+
  807. '0 as column_position, '+
  808. '0 as column_type, '+
  809. '0 as column_datatype, '+
  810. ''''' as column_typename, '+
  811. '0 as column_subtype, '+
  812. '0 as column_precision, '+
  813. '0 as column_scale, '+
  814. 'a.atttypmod as column_length, '+
  815. 'not a.attnotnull as column_nullable '+
  816. 'from '+
  817. ' pg_class c, pg_attribute a '+
  818. 'WHERE '+
  819. // This can lead to problems when case-sensitive tablenames are used.
  820. '(c.oid=a.attrelid) and (a.attnum>0) and (not a.attisdropped) and (upper(c.relname)=''' + Uppercase(SchemaObjectName) + ''') ' +
  821. 'order by a.attname';
  822. else
  823. DatabaseError(SMetadataUnavailable)
  824. end; {case}
  825. result := s;
  826. end;
  827. procedure TPQConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  828. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  829. var
  830. x : integer;
  831. li : Longint;
  832. begin
  833. with cursor as TPQCursor do
  834. begin
  835. x := FieldBinding[FieldDef.FieldNo-1];
  836. li := pqgetlength(res,curtuple,x);
  837. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer,li);
  838. Move(pqgetvalue(res,CurTuple,x)^, ABlobBuf^.BlobBuffer^.Buffer^, li);
  839. ABlobBuf^.BlobBuffer^.Size := li;
  840. end;
  841. end;
  842. function TPQConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  843. begin
  844. if assigned(cursor) and assigned((cursor as TPQCursor).res) then
  845. Result := StrToIntDef(PQcmdTuples((cursor as TPQCursor).res),-1)
  846. else
  847. Result := -1;
  848. end;
  849. { TPQConnectionDef }
  850. class function TPQConnectionDef.TypeName: String;
  851. begin
  852. Result:='PostGreSQL';
  853. end;
  854. class function TPQConnectionDef.ConnectionClass: TSQLConnectionClass;
  855. begin
  856. Result:=TPQConnection;
  857. end;
  858. class function TPQConnectionDef.Description: String;
  859. begin
  860. Result:='Connect to a PostGreSQL database directly via the client library';
  861. end;
  862. initialization
  863. RegisterConnection(TPQConnectionDef);
  864. finalization
  865. UnRegisterConnection(TPQConnectionDef);
  866. end.