pqconnection.pp 26 KB

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