pqconnection.pp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  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. end;
  17. TPQCursor = Class(TSQLCursor)
  18. protected
  19. Statement : string;
  20. StmtName : string;
  21. tr : TPQTrans;
  22. res : PPGresult;
  23. CurTuple : integer;
  24. FieldBinding : array of integer;
  25. end;
  26. EPQDatabaseError = class(EDatabaseError)
  27. public
  28. SEVERITY:string;
  29. SQLSTATE: string;
  30. MESSAGE_PRIMARY:string;
  31. MESSAGE_DETAIL:string;
  32. MESSAGE_HINT:string;
  33. STATEMENT_POSITION:string;
  34. end;
  35. TPQTranConnection = class
  36. protected
  37. FPGConn : PPGConn;
  38. FTranActive : boolean
  39. end;
  40. { TPQConnection }
  41. TPQConnection = class (TSQLConnection)
  42. private
  43. FConnectionPool : array of TPQTranConnection;
  44. FCursorCount : word;
  45. FConnectString : string;
  46. FIntegerDateTimes : boolean;
  47. FVerboseErrors : Boolean;
  48. procedure CheckConnectionStatus(var conn: PPGconn);
  49. procedure CheckResultError(var res: PPGresult; conn:PPGconn; ErrMsg: string);
  50. function TranslateFldType(res : PPGresult; Tuple : integer; out Size : integer) : TFieldType;
  51. procedure ExecuteDirectPG(const Query : String);
  52. protected
  53. procedure DoInternalConnect; override;
  54. procedure DoInternalDisconnect; override;
  55. function GetHandle : pointer; override;
  56. Function AllocateCursorHandle : TSQLCursor; override;
  57. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  58. Function AllocateTransactionHandle : TSQLHandle; override;
  59. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  60. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); override;
  61. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  62. function Fetch(cursor : TSQLCursor) : boolean; override;
  63. procedure UnPrepareStatement(cursor : TSQLCursor); override;
  64. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  65. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  66. function RollBack(trans : TSQLHandle) : boolean; override;
  67. function Commit(trans : TSQLHandle) : boolean; override;
  68. procedure CommitRetaining(trans : TSQLHandle); override;
  69. function StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  70. procedure RollBackRetaining(trans : TSQLHandle); override;
  71. procedure UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string); override;
  72. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  73. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor;ATransaction : TSQLTransaction); override;
  74. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  75. public
  76. constructor Create(AOwner : TComponent); override;
  77. function GetConnectionInfo(InfoType:TConnInfoType): string; override;
  78. procedure CreateDB; override;
  79. procedure DropDB; override;
  80. published
  81. property DatabaseName;
  82. property KeepConnection;
  83. property LoginPrompt;
  84. property Params;
  85. property OnLogin;
  86. Property VerboseErrors : Boolean Read FVerboseErrors Write FVerboseErrors default true;
  87. end;
  88. { TPQConnectionDef }
  89. TPQConnectionDef = Class(TConnectionDef)
  90. Class Function TypeName : String; override;
  91. Class Function ConnectionClass : TSQLConnectionClass; override;
  92. Class Function Description : String; override;
  93. Class Function DefaultLibraryName : String; override;
  94. Class Function LoadFunction : TLibraryLoadFunction; override;
  95. Class Function UnLoadFunction : TLibraryUnLoadFunction; override;
  96. Class Function LoadedLibraryName: string; override;
  97. end;
  98. implementation
  99. uses math, strutils, FmtBCD;
  100. ResourceString
  101. SErrRollbackFailed = 'Rollback transaction failed';
  102. SErrCommitFailed = 'Commit transaction failed';
  103. SErrConnectionFailed = 'Connection to database failed';
  104. SErrTransactionFailed = 'Start of transacion failed';
  105. SErrClearSelection = 'Clear of selection failed';
  106. SErrExecuteFailed = 'Execution of query failed';
  107. SErrFieldDefsFailed = 'Can not extract field information from query';
  108. SErrFetchFailed = 'Fetch of data failed';
  109. SErrPrepareFailed = 'Preparation of query failed.';
  110. SErrUnPrepareFailed = 'Unpreparation of query failed.';
  111. const Oid_Bool = 16;
  112. Oid_Bytea = 17;
  113. Oid_char = 18;
  114. Oid_Text = 25;
  115. Oid_Oid = 26;
  116. Oid_Name = 19;
  117. Oid_Int8 = 20;
  118. Oid_int2 = 21;
  119. Oid_Int4 = 23;
  120. Oid_Float4 = 700;
  121. Oid_Money = 790;
  122. Oid_Float8 = 701;
  123. Oid_Unknown = 705;
  124. Oid_MacAddr = 829;
  125. Oid_Inet = 869;
  126. Oid_bpchar = 1042;
  127. Oid_varchar = 1043;
  128. oid_date = 1082;
  129. oid_time = 1083;
  130. Oid_timeTZ = 1266;
  131. Oid_timestamp = 1114;
  132. Oid_timestampTZ = 1184;
  133. Oid_interval = 1186;
  134. oid_numeric = 1700;
  135. Oid_uuid = 2950;
  136. constructor TPQConnection.Create(AOwner : TComponent);
  137. begin
  138. inherited;
  139. FConnOptions := FConnOptions + [sqSupportParams] + [sqEscapeRepeat] + [sqEscapeSlash];
  140. FieldNameQuoteChars:=DoubleQuotes;
  141. VerboseErrors:=True;
  142. end;
  143. procedure TPQConnection.CreateDB;
  144. begin
  145. ExecuteDirectPG('CREATE DATABASE ' +DatabaseName);
  146. end;
  147. procedure TPQConnection.DropDB;
  148. begin
  149. ExecuteDirectPG('DROP DATABASE ' +DatabaseName);
  150. end;
  151. procedure TPQConnection.ExecuteDirectPG(const query : string);
  152. var ASQLDatabaseHandle : PPGConn;
  153. res : PPGresult;
  154. begin
  155. CheckDisConnected;
  156. {$IfDef LinkDynamically}
  157. InitialisePostgres3;
  158. {$EndIf}
  159. FConnectString := '';
  160. if (UserName <> '') then FConnectString := FConnectString + ' user=''' + UserName + '''';
  161. if (Password <> '') then FConnectString := FConnectString + ' password=''' + Password + '''';
  162. if (HostName <> '') then FConnectString := FConnectString + ' host=''' + HostName + '''';
  163. FConnectString := FConnectString + ' dbname=''template1''';
  164. if (Params.Text <> '') then FConnectString := FConnectString + ' '+Params.Text;
  165. ASQLDatabaseHandle := PQconnectdb(pchar(FConnectString));
  166. CheckConnectionStatus(ASQLDatabaseHandle);
  167. res := PQexec(ASQLDatabaseHandle,pchar(query));
  168. CheckResultError(res,ASQLDatabaseHandle,SDBCreateDropFailed);
  169. PQclear(res);
  170. PQFinish(ASQLDatabaseHandle);
  171. {$IfDef LinkDynamically}
  172. ReleasePostgres3;
  173. {$EndIf}
  174. end;
  175. function TPQConnection.GetTransactionHandle(trans : TSQLHandle): pointer;
  176. begin
  177. Result := trans;
  178. end;
  179. function TPQConnection.RollBack(trans : TSQLHandle) : boolean;
  180. var
  181. res : PPGresult;
  182. tr : TPQTrans;
  183. i : Integer;
  184. begin
  185. result := false;
  186. tr := trans as TPQTrans;
  187. res := PQexec(tr.PGConn, 'ROLLBACK');
  188. CheckResultError(res,tr.PGConn,SErrRollbackFailed);
  189. PQclear(res);
  190. //make connection available in pool
  191. for i:=0 to length(FConnectionPool)-1 do
  192. if FConnectionPool[i].FPGConn=tr.PGConn then
  193. begin
  194. FConnectionPool[i].FTranActive:=false;
  195. break;
  196. end;
  197. result := true;
  198. end;
  199. function TPQConnection.Commit(trans : TSQLHandle) : boolean;
  200. var
  201. res : PPGresult;
  202. tr : TPQTrans;
  203. i : Integer;
  204. begin
  205. result := false;
  206. tr := trans as TPQTrans;
  207. res := PQexec(tr.PGConn, 'COMMIT');
  208. CheckResultError(res,tr.PGConn,SErrCommitFailed);
  209. PQclear(res);
  210. //make connection available in pool
  211. for i:=0 to length(FConnectionPool)-1 do
  212. if FConnectionPool[i].FPGConn=tr.PGConn then
  213. begin
  214. FConnectionPool[i].FTranActive:=false;
  215. break;
  216. end;
  217. result := true;
  218. end;
  219. function TPQConnection.StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean;
  220. var
  221. res : PPGresult;
  222. tr : TPQTrans;
  223. i : Integer;
  224. begin
  225. result:=false;
  226. tr := trans as TPQTrans;
  227. //find an unused connection in the pool
  228. i:=0;
  229. while i<length(FConnectionPool) do
  230. if (FConnectionPool[i].FPGConn=nil) or not FConnectionPool[i].FTranActive then
  231. break
  232. else
  233. i:=i+1;
  234. if i=length(FConnectionPool) then //create a new connection
  235. begin
  236. tr.PGConn := PQconnectdb(pchar(FConnectString));
  237. CheckConnectionStatus(tr.PGConn);
  238. if CharSet <> '' then
  239. PQsetClientEncoding(tr.PGConn, pchar(CharSet));
  240. //store the new connection
  241. SetLength(FConnectionPool,i+1);
  242. FConnectionPool[i]:=TPQTranConnection.Create;
  243. FConnectionPool[i].FPGConn:=tr.PGConn;
  244. FConnectionPool[i].FTranActive:=true;
  245. end
  246. else //re-use existing connection
  247. begin
  248. tr.PGConn:=FConnectionPool[i].FPGConn;
  249. FConnectionPool[i].FTranActive:=true;
  250. end;
  251. res := PQexec(tr.PGConn, 'BEGIN');
  252. CheckResultError(res,tr.PGConn,sErrTransactionFailed);
  253. PQclear(res);
  254. result := true;
  255. end;
  256. procedure TPQConnection.RollBackRetaining(trans : TSQLHandle);
  257. var
  258. res : PPGresult;
  259. tr : TPQTrans;
  260. begin
  261. tr := trans as TPQTrans;
  262. res := PQexec(tr.PGConn, 'ROLLBACK');
  263. CheckResultError(res,tr.PGConn,SErrRollbackFailed);
  264. PQclear(res);
  265. res := PQexec(tr.PGConn, 'BEGIN');
  266. CheckResultError(res,tr.PGConn,sErrTransactionFailed);
  267. PQclear(res);
  268. end;
  269. procedure TPQConnection.CommitRetaining(trans : TSQLHandle);
  270. var
  271. res : PPGresult;
  272. tr : TPQTrans;
  273. begin
  274. tr := trans as TPQTrans;
  275. res := PQexec(tr.PGConn, 'COMMIT');
  276. CheckResultError(res,tr.PGConn,SErrCommitFailed);
  277. PQclear(res);
  278. res := PQexec(tr.PGConn, 'BEGIN');
  279. CheckResultError(res,tr.PGConn,sErrTransactionFailed);
  280. PQclear(res);
  281. end;
  282. procedure TPQConnection.DoInternalConnect;
  283. var ASQLDatabaseHandle : PPGConn;
  284. begin
  285. {$IfDef LinkDynamically}
  286. InitialisePostgres3;
  287. {$EndIf}
  288. inherited DoInternalConnect;
  289. FConnectString := '';
  290. if (UserName <> '') then FConnectString := FConnectString + ' user=''' + UserName + '''';
  291. if (Password <> '') then FConnectString := FConnectString + ' password=''' + Password + '''';
  292. if (HostName <> '') then FConnectString := FConnectString + ' host=''' + HostName + '''';
  293. if (DatabaseName <> '') then FConnectString := FConnectString + ' dbname=''' + DatabaseName + '''';
  294. if (Params.Text <> '') then FConnectString := FConnectString + ' '+Params.Text;
  295. ASQLDatabaseHandle := PQconnectdb(pchar(FConnectString));
  296. try
  297. CheckConnectionStatus(ASQLDatabaseHandle);
  298. except
  299. DoInternalDisconnect;
  300. raise;
  301. end;
  302. // This only works for pg>=8.0, so timestamps won't work with earlier versions of pg which are compiled with integer_datetimes on
  303. if PQparameterStatus<>nil then
  304. FIntegerDateTimes := PQparameterStatus(ASQLDatabaseHandle,'integer_datetimes') = 'on';
  305. SetLength(FConnectionPool,1);
  306. FConnectionPool[0]:=TPQTranConnection.Create;
  307. FConnectionPool[0].FPGConn:=ASQLDatabaseHandle;
  308. FConnectionPool[0].FTranActive:=false;
  309. end;
  310. procedure TPQConnection.DoInternalDisconnect;
  311. var i:integer;
  312. begin
  313. Inherited;
  314. for i:=0 to length(FConnectionPool)-1 do
  315. begin
  316. if assigned(FConnectionPool[i].FPGConn) then
  317. PQfinish(FConnectionPool[i].FPGConn);
  318. FConnectionPool[i].Free;
  319. end;
  320. Setlength(FConnectionPool,0);
  321. {$IfDef LinkDynamically}
  322. ReleasePostgres3;
  323. {$EndIf}
  324. end;
  325. procedure TPQConnection.CheckConnectionStatus(var conn: PPGconn);
  326. var sErr: string;
  327. i: integer;
  328. begin
  329. if (PQstatus(conn) = CONNECTION_BAD) then
  330. begin
  331. sErr := PQerrorMessage(conn);
  332. //make connection available in pool
  333. for i:=0 to length(FConnectionPool)-1 do
  334. if FConnectionPool[i].FPGConn=conn then
  335. begin
  336. FConnectionPool[i].FPGConn:=nil;
  337. FConnectionPool[i].FTranActive:=false;
  338. break;
  339. end;
  340. PQfinish(conn);
  341. DatabaseError(sErrConnectionFailed + ' (PostgreSQL: ' + sErr + ')', Self);
  342. end;
  343. end;
  344. procedure TPQConnection.CheckResultError(var res: PPGresult; conn: PPGconn;
  345. ErrMsg: string);
  346. Procedure MaybeAdd(Var S : String; Prefix,Msg : String);
  347. begin
  348. if (Msg='') then
  349. exit;
  350. S:=S+LineEnding+Prefix+': '+Msg;
  351. end;
  352. var
  353. E: EPQDatabaseError;
  354. sErr: string;
  355. CompName: string;
  356. SEVERITY: string;
  357. SQLSTATE: string;
  358. MESSAGE_PRIMARY: string;
  359. MESSAGE_DETAIL: string;
  360. MESSAGE_HINT: string;
  361. STATEMENT_POSITION: string;
  362. i:Integer;
  363. begin
  364. if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  365. begin
  366. SEVERITY:=PQresultErrorField(res,ord('S'));
  367. SQLSTATE:=PQresultErrorField(res,ord('C'));
  368. MESSAGE_PRIMARY:=PQresultErrorField(res,ord('M'));
  369. MESSAGE_DETAIL:=PQresultErrorField(res,ord('D'));
  370. MESSAGE_HINT:=PQresultErrorField(res,ord('H'));
  371. STATEMENT_POSITION:=PQresultErrorField(res,ord('P'));
  372. sErr:=PQresultErrorMessage(res);
  373. if VerboseErrors then
  374. begin
  375. MaybeAdd(sErr,'Severity',SEVERITY);
  376. MaybeAdd(sErr,'SQL State',SQLSTATE);
  377. MaybeAdd(sErr,'Primary Error',MESSAGE_PRIMARY);
  378. MaybeAdd(sErr,'Error Detail',MESSAGE_DETAIL);
  379. MaybeAdd(sErr,'Hint',MESSAGE_HINT);
  380. MaybeAdd(sErr,'Character',STATEMENT_POSITION);
  381. end;
  382. if (Self.Name='') then CompName := Self.ClassName else CompName := Self.Name;
  383. E:=EPQDatabaseError.CreateFmt('%s : %s (PostgreSQL: %s)', [CompName, ErrMsg, sErr]);
  384. E.SEVERITY:=SEVERITY;
  385. E.SQLSTATE:=SQLSTATE;
  386. E.MESSAGE_PRIMARY:=MESSAGE_PRIMARY;
  387. E.MESSAGE_DETAIL:=MESSAGE_DETAIL;
  388. E.MESSAGE_HINT:=MESSAGE_HINT;
  389. E.STATEMENT_POSITION:=STATEMENT_POSITION;
  390. PQclear(res);
  391. res:=nil;
  392. if assigned(conn) then
  393. begin
  394. PQFinish(conn);
  395. //make connection available in pool
  396. for i:=0 to length(FConnectionPool)-1 do
  397. if FConnectionPool[i].FPGConn=conn then
  398. begin
  399. FConnectionPool[i].FPGConn:=nil;
  400. FConnectionPool[i].FTranActive:=false;
  401. break;
  402. end;
  403. end;
  404. raise E;
  405. end;
  406. end;
  407. function TPQConnection.TranslateFldType(res : PPGresult; Tuple : integer; out Size : integer) : TFieldType;
  408. const VARHDRSZ=sizeof(longint);
  409. var li : longint;
  410. begin
  411. Size := 0;
  412. case PQftype(res,Tuple) of
  413. Oid_varchar,Oid_bpchar,
  414. Oid_name : begin
  415. Result := ftstring;
  416. size := PQfsize(Res, Tuple);
  417. if (size = -1) then
  418. begin
  419. li := PQfmod(res,Tuple);
  420. if li = -1 then
  421. size := dsMaxStringSize
  422. else
  423. size := (li-VARHDRSZ) and $FFFF;
  424. end;
  425. if size > MaxSmallint then size := MaxSmallint;
  426. end;
  427. // Oid_text : Result := ftstring;
  428. Oid_text : Result := ftMemo;
  429. Oid_Bytea : Result := ftBlob;
  430. Oid_oid : Result := ftInteger;
  431. Oid_int8 : Result := ftLargeInt;
  432. Oid_int4 : Result := ftInteger;
  433. Oid_int2 : Result := ftSmallInt;
  434. Oid_Float4 : Result := ftFloat;
  435. Oid_Float8 : Result := ftFloat;
  436. Oid_TimeStamp,
  437. Oid_TimeStampTZ : Result := ftDateTime;
  438. Oid_Date : Result := ftDate;
  439. Oid_Interval,
  440. Oid_Time,
  441. Oid_TimeTZ : Result := ftTime;
  442. Oid_Bool : Result := ftBoolean;
  443. Oid_Numeric : begin
  444. Result := ftBCD;
  445. li := PQfmod(res,Tuple);
  446. if li = -1 then
  447. size := 4 // No information about the size available, use the maximum value
  448. else
  449. // The precision is the high 16 bits, the scale the
  450. // low 16 bits with an offset of sizeof(int32).
  451. begin
  452. size := (li-VARHDRSZ) and $FFFF;
  453. if (size > MaxBCDScale) or ((li shr 16)-size > MaxBCDPrecision-MaxBCDScale) then
  454. Result := ftFmtBCD;
  455. end;
  456. end;
  457. Oid_Money : Result := ftCurrency;
  458. Oid_char : begin
  459. Result := ftFixedChar;
  460. Size := 1;
  461. end;
  462. Oid_uuid : begin
  463. Result := ftGuid;
  464. Size := 38;
  465. end;
  466. Oid_MacAddr : begin
  467. Result := ftFixedChar;
  468. Size := 17;
  469. end;
  470. Oid_Inet : begin
  471. Result := ftString;
  472. Size := 39;
  473. end;
  474. Oid_Unknown : Result := ftUnknown;
  475. else
  476. Result := ftUnknown;
  477. end;
  478. end;
  479. Function TPQConnection.AllocateCursorHandle : TSQLCursor;
  480. begin
  481. result := TPQCursor.create;
  482. end;
  483. Procedure TPQConnection.DeAllocateCursorHandle(var cursor : TSQLCursor);
  484. begin
  485. FreeAndNil(cursor);
  486. end;
  487. Function TPQConnection.AllocateTransactionHandle : TSQLHandle;
  488. begin
  489. result := TPQTrans.create;
  490. end;
  491. procedure TPQConnection.PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams);
  492. const TypeStrings : array[TFieldType] of string =
  493. (
  494. 'Unknown', // ftUnknown
  495. 'text', // ftString
  496. 'smallint', // ftSmallint
  497. 'int', // ftInteger
  498. 'int', // ftWord
  499. 'bool', // ftBoolean
  500. 'float', // ftFloat
  501. 'money', // ftCurrency
  502. 'numeric', // ftBCD
  503. 'date', // ftDate
  504. 'time', // ftTime
  505. 'timestamp', // ftDateTime
  506. 'Unknown', // ftBytes
  507. 'Unknown', // ftVarBytes
  508. 'Unknown', // ftAutoInc
  509. 'bytea', // ftBlob
  510. 'text', // ftMemo
  511. 'bytea', // ftGraphic
  512. 'text', // ftFmtMemo
  513. 'Unknown', // ftParadoxOle
  514. 'Unknown', // ftDBaseOle
  515. 'Unknown', // ftTypedBinary
  516. 'Unknown', // ftCursor
  517. 'char', // ftFixedChar
  518. 'text', // ftWideString
  519. 'bigint', // ftLargeint
  520. 'Unknown', // ftADT
  521. 'Unknown', // ftArray
  522. 'Unknown', // ftReference
  523. 'Unknown', // ftDataSet
  524. 'Unknown', // ftOraBlob
  525. 'Unknown', // ftOraClob
  526. 'Unknown', // ftVariant
  527. 'Unknown', // ftInterface
  528. 'Unknown', // ftIDispatch
  529. 'uuid', // ftGuid
  530. 'Unknown', // ftTimeStamp
  531. 'numeric', // ftFMTBcd
  532. 'Unknown', // ftFixedWideChar
  533. 'Unknown' // ftWideMemo
  534. );
  535. var s : string;
  536. i : integer;
  537. begin
  538. with (cursor as TPQCursor) do
  539. begin
  540. FPrepared := False;
  541. // Prior to v8 there is no support for cursors and parameters.
  542. // So that's not supported.
  543. if FStatementType in [stInsert,stUpdate,stDelete, stSelect] then
  544. begin
  545. StmtName := 'prepst'+inttostr(FCursorCount);
  546. inc(FCursorCount);
  547. tr := TPQTrans(aTransaction.Handle);
  548. // Only available for pq 8.0, so don't use it...
  549. // Res := pqprepare(tr,'prepst'+name+nr,pchar(buf),params.Count,pchar(''));
  550. s := 'prepare '+StmtName+' ';
  551. if Assigned(AParams) and (AParams.Count > 0) then
  552. begin
  553. s := s + '(';
  554. for i := 0 to AParams.Count-1 do
  555. if TypeStrings[AParams[i].DataType] <> 'Unknown' then
  556. s := s + TypeStrings[AParams[i].DataType] + ','
  557. else
  558. begin
  559. if AParams[i].DataType = ftUnknown then
  560. begin
  561. if AParams[i].IsNull then
  562. s:=s+' unknown ,'
  563. else
  564. DatabaseErrorFmt(SUnknownParamFieldType,[AParams[i].Name],self)
  565. end
  566. else
  567. DatabaseErrorFmt(SUnsupportedParameter,[Fieldtypenames[AParams[i].DataType]],self);
  568. end;
  569. s[length(s)] := ')';
  570. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psPostgreSQL);
  571. end;
  572. s := s + ' as ' + buf;
  573. if LogEvent(detPrepare) then
  574. Log(detPrepare,S);
  575. res := PQexec(tr.PGConn,pchar(s));
  576. CheckResultError(res,nil,SErrPrepareFailed);
  577. // if statement is INSERT, UPDATE, DELETE with RETURNING clause, then
  578. // override the statement type derrived by parsing the query.
  579. if (FStatementType in [stInsert,stUpdate,stDelete]) and (pos('RETURNING', upcase(s)) > 0) then
  580. begin
  581. PQclear(res);
  582. res := PQdescribePrepared(tr.PGConn,pchar(StmtName));
  583. if (PQresultStatus(res) = PGRES_COMMAND_OK) and (PQnfields(res) > 0) then
  584. FStatementType := stSelect;
  585. end;
  586. FPrepared := True;
  587. end
  588. else
  589. Statement := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psPostgreSQL);
  590. end;
  591. end;
  592. procedure TPQConnection.UnPrepareStatement(cursor : TSQLCursor);
  593. begin
  594. with (cursor as TPQCursor) do
  595. begin
  596. PQclear(res);
  597. res:=nil;
  598. if FPrepared then
  599. begin
  600. if PQtransactionStatus(tr.PGConn) <> PQTRANS_INERROR then
  601. begin
  602. res := PQexec(tr.PGConn,pchar('deallocate '+StmtName));
  603. CheckResultError(res,nil,SErrUnPrepareFailed);
  604. PQclear(res);
  605. res:=nil;
  606. end;
  607. FPrepared := False;
  608. end;
  609. end;
  610. end;
  611. procedure TPQConnection.Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams);
  612. var ar : array of pchar;
  613. l,i : integer;
  614. s : string;
  615. lengths,formats : array of integer;
  616. ParamNames,
  617. ParamValues : array of string;
  618. cash: int64;
  619. begin
  620. with cursor as TPQCursor do
  621. begin
  622. PQclear(res);
  623. if FStatementType in [stInsert,stUpdate,stDelete,stSelect] then
  624. begin
  625. if Assigned(AParams) and (AParams.Count > 0) then
  626. begin
  627. l:=AParams.Count;
  628. setlength(ar,l);
  629. setlength(lengths,l);
  630. setlength(formats,l);
  631. for i := 0 to AParams.Count -1 do if not AParams[i].IsNull then
  632. begin
  633. case AParams[i].DataType of
  634. ftDateTime:
  635. s := FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', AParams[i].AsDateTime);
  636. ftDate:
  637. s := FormatDateTime('yyyy-mm-dd', AParams[i].AsDateTime);
  638. ftTime:
  639. s := FormatDateTime('hh:nn:ss.zzz', AParams[i].AsDateTime);
  640. ftFloat, ftBCD:
  641. Str(AParams[i].AsFloat, s);
  642. ftCurrency:
  643. begin
  644. cash:=NtoBE(round(AParams[i].AsCurrency*100));
  645. setlength(s, sizeof(cash));
  646. Move(cash, s[1], sizeof(cash));
  647. end;
  648. ftFmtBCD:
  649. s := BCDToStr(AParams[i].AsFMTBCD, FSQLFormatSettings);
  650. else
  651. s := AParams[i].AsString;
  652. end; {case}
  653. GetMem(ar[i],length(s)+1);
  654. StrMove(PChar(ar[i]),Pchar(s),Length(S)+1);
  655. lengths[i]:=Length(s);
  656. if (AParams[i].DataType in [ftBlob,ftMemo,ftGraphic,ftCurrency]) then
  657. Formats[i]:=1
  658. else
  659. Formats[i]:=0;
  660. end
  661. else
  662. FreeAndNil(ar[i]);
  663. res := PQexecPrepared(tr.PGConn,pchar(StmtName),AParams.Count,@Ar[0],@Lengths[0],@Formats[0],1);
  664. for i := 0 to AParams.Count -1 do
  665. FreeMem(ar[i]);
  666. end
  667. else
  668. res := PQexecPrepared(tr.PGConn,pchar(StmtName),0,nil,nil,nil,1);
  669. end
  670. else
  671. begin
  672. tr := TPQTrans(aTransaction.Handle);
  673. if Assigned(AParams) and (AParams.Count > 0) then
  674. begin
  675. setlength(ParamNames,AParams.Count);
  676. setlength(ParamValues,AParams.Count);
  677. for i := 0 to AParams.Count -1 do
  678. begin
  679. ParamNames[AParams.Count-i-1] := '$'+inttostr(AParams[i].index+1);
  680. ParamValues[AParams.Count-i-1] := GetAsSQLText(AParams[i]);
  681. end;
  682. s := stringsreplace(Statement,ParamNames,ParamValues,[rfReplaceAll]);
  683. end
  684. else
  685. s := Statement;
  686. res := PQexec(tr.PGConn,pchar(s));
  687. if (PQresultStatus(res) in [PGRES_COMMAND_OK]) then
  688. begin
  689. PQclear(res);
  690. res:=nil;
  691. end;
  692. end;
  693. if assigned(res) and not (PQresultStatus(res) in [PGRES_COMMAND_OK,PGRES_TUPLES_OK]) then
  694. begin
  695. // Don't perform the rollback, only make it possible to do a rollback.
  696. // The other databases also don't do this.
  697. //atransaction.Rollback;
  698. CheckResultError(res,nil,SErrExecuteFailed);
  699. end;
  700. FSelectable := assigned(res) and (PQresultStatus(res)=PGRES_TUPLES_OK);
  701. end;
  702. end;
  703. procedure TPQConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs);
  704. var
  705. i : integer;
  706. size : integer;
  707. fieldtype : tfieldtype;
  708. nFields : integer;
  709. begin
  710. with cursor as TPQCursor do
  711. begin
  712. nFields := PQnfields(Res);
  713. setlength(FieldBinding,nFields);
  714. for i := 0 to nFields-1 do
  715. begin
  716. fieldtype := TranslateFldType(Res, i,size);
  717. with TFieldDef.Create(FieldDefs, FieldDefs.MakeNameUnique(PQfname(Res, i)), fieldtype,size, False, (i + 1)) do
  718. FieldBinding[FieldNo-1] := i;
  719. end;
  720. CurTuple := -1;
  721. end;
  722. end;
  723. function TPQConnection.GetHandle: pointer;
  724. var
  725. i:integer;
  726. begin
  727. result:=nil;
  728. if not Connected then
  729. exit;
  730. //Get any handle that is (still) connected
  731. for i:=0 to length(FConnectionPool)-1 do
  732. if assigned(FConnectionPool[i].FPGConn) and (PQstatus(FConnectionPool[i].FPGConn)<>CONNECTION_BAD) then
  733. begin
  734. Result :=FConnectionPool[i].FPGConn;
  735. exit;
  736. end;
  737. //Nothing connected!! Reconnect
  738. if assigned(FConnectionPool[0].FPGConn) then
  739. PQreset(FConnectionPool[0].FPGConn)
  740. else
  741. FConnectionPool[0].FPGConn := PQconnectdb(pchar(FConnectString));
  742. CheckConnectionStatus(FConnectionPool[0].FPGConn);
  743. if CharSet <> '' then
  744. PQsetClientEncoding(FConnectionPool[0].FPGConn, pchar(CharSet));
  745. result:=FConnectionPool[0].FPGConn;
  746. end;
  747. function TPQConnection.Fetch(cursor : TSQLCursor) : boolean;
  748. begin
  749. with cursor as TPQCursor do
  750. begin
  751. inc(CurTuple);
  752. Result := (PQntuples(res)>CurTuple);
  753. end;
  754. end;
  755. function TPQConnection.LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  756. const NBASE=10000;
  757. DAYS_PER_MONTH=30;
  758. type TNumericRecord = record
  759. Digits : SmallInt;
  760. Weight : SmallInt;
  761. Sign : SmallInt;
  762. Scale : Smallint;
  763. end;
  764. TIntervalRec = packed record
  765. time : int64;
  766. day : longint;
  767. month : longint;
  768. end;
  769. TMacAddrRec = packed record
  770. a, b, c, d, e, f: byte;
  771. end;
  772. TInetRec = packed record
  773. family : byte;
  774. bits : byte;
  775. is_cidr: byte;
  776. nb : byte;
  777. ipaddr : array[1..16] of byte;
  778. end;
  779. var
  780. x,i : integer;
  781. s : string;
  782. li : Longint;
  783. CurrBuff : pchar;
  784. dbl : pdouble;
  785. cur : currency;
  786. NumericRecord : ^TNumericRecord;
  787. guid : TGUID;
  788. bcd : TBCD;
  789. macaddr : ^TMacAddrRec;
  790. inet : ^TInetRec;
  791. begin
  792. Createblob := False;
  793. with cursor as TPQCursor do
  794. begin
  795. x := FieldBinding[FieldDef.FieldNo-1];
  796. // Joost, 5 jan 2006: I disabled the following, since it's useful for
  797. // debugging, but it also slows things down. In principle things can only go
  798. // wrong when FieldDefs is changed while the dataset is opened. A user just
  799. // shoudn't do that. ;) (The same is done in IBConnection)
  800. //if PQfname(Res, x) <> FieldDef.Name then
  801. // DatabaseErrorFmt(SFieldNotFound,[FieldDef.Name],self);
  802. if pqgetisnull(res,CurTuple,x)=1 then
  803. result := false
  804. else
  805. begin
  806. CurrBuff := pqgetvalue(res,CurTuple,x);
  807. result := true;
  808. case FieldDef.DataType of
  809. ftInteger, ftSmallint, ftLargeInt :
  810. case PQfsize(res, x) of // postgres returns big-endian numbers
  811. sizeof(int64) : pint64(buffer)^ := BEtoN(pint64(CurrBuff)^); // INT8
  812. sizeof(integer) : pinteger(buffer)^ := BEtoN(pinteger(CurrBuff)^); // INT4
  813. sizeof(smallint) : psmallint(buffer)^ := BEtoN(psmallint(CurrBuff)^); // INT2
  814. end; {case}
  815. ftFloat :
  816. case PQfsize(res, x) of // postgres returns big-endian numbers
  817. sizeof(int64) : // FLOAT8
  818. pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  819. sizeof(integer) : // FLOAT4
  820. begin
  821. li := BEtoN(pinteger(CurrBuff)^);
  822. pdouble(buffer)^ := psingle(@li)^
  823. end;
  824. end; {case}
  825. ftString, ftFixedChar :
  826. begin
  827. case PQftype(res, x) of
  828. Oid_MacAddr:
  829. begin
  830. macaddr := Pointer(CurrBuff);
  831. li := FormatBuf(Buffer^, FieldDef.Size, '%.2x:%.2x:%.2x:%.2x:%.2x:%.2x', 29,
  832. [macaddr^.a,macaddr^.b,macaddr^.c,macaddr^.d,macaddr^.e,macaddr^.f]);
  833. end;
  834. Oid_Inet:
  835. begin
  836. inet := Pointer(CurrBuff);
  837. if inet^.nb = 4 then
  838. li := FormatBuf(Buffer^, FieldDef.Size, '%d.%d.%d.%d', 11,
  839. [inet^.ipaddr[1],inet^.ipaddr[2],inet^.ipaddr[3],inet^.ipaddr[4]])
  840. else if inet^.nb = 16 then
  841. li := FormatBuf(Buffer^, FieldDef.Size, '%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x', 55,
  842. [inet^.ipaddr[1],inet^.ipaddr[2],inet^.ipaddr[3],inet^.ipaddr[4],inet^.ipaddr[5],inet^.ipaddr[6],inet^.ipaddr[7],inet^.ipaddr[8],inet^.ipaddr[9],inet^.ipaddr[10],inet^.ipaddr[11],inet^.ipaddr[12],inet^.ipaddr[13],inet^.ipaddr[14],inet^.ipaddr[15],inet^.ipaddr[16]])
  843. else
  844. li := 0;
  845. end
  846. else
  847. begin
  848. li := pqgetlength(res,curtuple,x);
  849. if li > FieldDef.Size then li := FieldDef.Size;
  850. Move(CurrBuff^, Buffer^, li);
  851. end;
  852. end;
  853. pchar(Buffer + li)^ := #0;
  854. end;
  855. ftBlob, ftMemo :
  856. CreateBlob := True;
  857. ftDate :
  858. begin
  859. dbl := pointer(buffer);
  860. dbl^ := BEtoN(plongint(CurrBuff)^) + 36526;
  861. end;
  862. ftDateTime, ftTime :
  863. begin
  864. dbl := pointer(buffer);
  865. if FIntegerDateTimes then
  866. dbl^ := BEtoN(pint64(CurrBuff)^) / 1000000
  867. else
  868. pint64(dbl)^ := BEtoN(pint64(CurrBuff)^);
  869. case PQftype(res, x) of
  870. Oid_Timestamp, Oid_TimestampTZ:
  871. dbl^ := dbl^ + 3.1558464E+009; // postgres counts seconds elapsed since 1-1-2000
  872. Oid_Interval:
  873. dbl^ := dbl^ + BEtoN(plongint(CurrBuff+ 8)^) * SecsPerDay
  874. + BEtoN(plongint(CurrBuff+12)^) * SecsPerDay * DAYS_PER_MONTH;
  875. end;
  876. dbl^ := dbl^ / SecsPerDay;
  877. // Now convert the mathematically-correct datetime to the
  878. // illogical windows/delphi/fpc TDateTime:
  879. if (dbl^ <= 0) and (frac(dbl^) < 0) then
  880. dbl^ := trunc(dbl^)-2-frac(dbl^);
  881. end;
  882. ftBCD, ftFmtBCD:
  883. begin
  884. NumericRecord := pointer(CurrBuff);
  885. NumericRecord^.Digits := BEtoN(NumericRecord^.Digits);
  886. NumericRecord^.Weight := BEtoN(NumericRecord^.Weight);
  887. NumericRecord^.Sign := BEtoN(NumericRecord^.Sign);
  888. NumericRecord^.Scale := BEtoN(NumericRecord^.Scale);
  889. inc(pointer(currbuff),sizeof(TNumericRecord));
  890. if (NumericRecord^.Digits = 0) and (NumericRecord^.Scale = 0) then // = NaN, which is not supported by Currency-type, so we return NULL
  891. result := false
  892. else if FieldDef.DataType = ftBCD then
  893. begin
  894. cur := 0;
  895. for i := 0 to NumericRecord^.Digits-1 do
  896. begin
  897. cur := cur + beton(pword(CurrBuff)^) * intpower(NBASE, NumericRecord^.weight-i);
  898. inc(pointer(CurrBuff),2);
  899. end;
  900. if NumericRecord^.Sign <> 0 then cur := -cur;
  901. Move(Cur, Buffer^, sizeof(currency));
  902. end
  903. else //ftFmtBCD
  904. begin
  905. bcd := 0;
  906. for i := 0 to NumericRecord^.Digits-1 do
  907. begin
  908. BCDAdd(bcd, beton(pword(CurrBuff)^) * intpower(NBASE, NumericRecord^.weight-i), bcd);
  909. inc(pointer(CurrBuff),2);
  910. end;
  911. if NumericRecord^.Sign <> 0 then BCDNegate(bcd);
  912. Move(bcd, Buffer^, sizeof(bcd));
  913. end;
  914. end;
  915. ftCurrency :
  916. begin
  917. dbl := pointer(buffer);
  918. dbl^ := BEtoN(PInt64(CurrBuff)^) / 100;
  919. end;
  920. ftBoolean:
  921. pchar(buffer)[0] := CurrBuff[0];
  922. ftGuid:
  923. begin
  924. Move(CurrBuff^, guid, sizeof(guid));
  925. guid.D1:=BEtoN(guid.D1);
  926. guid.D2:=BEtoN(guid.D2);
  927. guid.D3:=BEtoN(guid.D3);
  928. s:=GUIDToString(guid);
  929. StrPLCopy(PChar(Buffer), s, FieldDef.Size);
  930. end
  931. else
  932. result := false;
  933. end;
  934. end;
  935. end;
  936. end;
  937. procedure TPQConnection.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  938. var qry : TSQLQuery;
  939. relname : string;
  940. begin
  941. if not assigned(Transaction) then
  942. DatabaseError(SErrConnTransactionnSet);
  943. if (length(TableName)>2) and (TableName[1]='"') and (TableName[length(TableName)]='"') then
  944. relname := QuotedStr(AnsiDequotedStr(TableName, '"'))
  945. else
  946. relname := 'lower(' + QuotedStr(TableName) + ')'; // unquoted names are stored lower case in PostgreSQL which is incompatible with the SQL standard
  947. qry := tsqlquery.Create(nil);
  948. qry.transaction := Transaction;
  949. qry.database := Self;
  950. with qry do
  951. begin
  952. ReadOnly := True;
  953. sql.clear;
  954. sql.add('select '+
  955. 'ic.relname as indexname, '+
  956. 'tc.relname as tablename, '+
  957. 'ia.attname, '+
  958. 'i.indisprimary, '+
  959. 'i.indisunique '+
  960. 'from '+
  961. 'pg_attribute ta, '+
  962. 'pg_attribute ia, '+
  963. 'pg_class tc, '+
  964. 'pg_class ic, '+
  965. 'pg_index i '+
  966. 'where '+
  967. '(i.indrelid = tc.oid) and '+
  968. '(ta.attrelid = tc.oid) and '+
  969. '(ia.attrelid = i.indexrelid) and '+
  970. '(ic.oid = i.indexrelid) and '+
  971. '(ta.attnum = i.indkey[ia.attnum-1]) and '+
  972. '(tc.relname = ' + relname + ') '+
  973. 'order by '+
  974. 'ic.relname;');
  975. open;
  976. end;
  977. while not qry.eof do with IndexDefs.AddIndexDef do
  978. begin
  979. Name := trim(qry.fields[0].asstring);
  980. Fields := trim(qry.Fields[2].asstring);
  981. If qry.fields[3].asboolean then options := options + [ixPrimary];
  982. If qry.fields[4].asboolean then options := options + [ixUnique];
  983. qry.next;
  984. while (name = qry.fields[0].asstring) and (not qry.eof) do
  985. begin
  986. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  987. qry.next;
  988. end;
  989. end;
  990. qry.close;
  991. qry.free;
  992. end;
  993. function TPQConnection.GetSchemaInfoSQL(SchemaType: TSchemaType;
  994. SchemaObjectName, SchemaPattern: string): string;
  995. var s : string;
  996. begin
  997. // select * from information_schema.tables with
  998. // where table_schema [not] in ('pg_catalog','information_schema') may be better.
  999. // But the following should work:
  1000. case SchemaType of
  1001. stTables : s := 'select '+
  1002. 'relfilenode as recno, '+
  1003. 'current_database() as catalog_name, '+
  1004. 'nspname as schema_name, '+
  1005. 'relname as table_name, '+
  1006. '0 as table_type '+
  1007. 'from pg_class c '+
  1008. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1009. 'where (relkind=''r'') and not (nspname in (''pg_catalog'',''information_schema''))' +
  1010. 'order by relname';
  1011. stSysTables : s := 'select '+
  1012. 'relfilenode as recno, '+
  1013. 'current_database() as catalog_name, '+
  1014. 'nspname as schema_name, '+
  1015. 'relname as table_name, '+
  1016. '0 as table_type '+
  1017. 'from pg_class c '+
  1018. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1019. 'where (relkind=''r'') and nspname in ((''pg_catalog'',''information_schema'')) ' + // only system tables
  1020. 'order by relname';
  1021. stColumns : s := 'select '+
  1022. 'a.attnum as recno, '+
  1023. 'current_database() as catalog_name, '+
  1024. 'nspname as schema_name, '+
  1025. 'c.relname as table_name, '+
  1026. 'a.attname as column_name, '+
  1027. '0 as column_position, '+
  1028. '0 as column_type, '+
  1029. '0 as column_datatype, '+
  1030. ''''' as column_typename, '+
  1031. '0 as column_subtype, '+
  1032. '0 as column_precision, '+
  1033. '0 as column_scale, '+
  1034. 'a.atttypmod as column_length, '+
  1035. 'not a.attnotnull as column_nullable '+
  1036. 'from pg_class c '+
  1037. 'join pg_attribute a on c.oid=a.attrelid '+
  1038. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1039. // This can lead to problems when case-sensitive tablenames are used.
  1040. 'where (a.attnum>0) and (not a.attisdropped) and (upper(c.relname)=''' + Uppercase(SchemaObjectName) + ''') '+
  1041. 'order by a.attname';
  1042. else
  1043. s := inherited;
  1044. end; {case}
  1045. result := s;
  1046. end;
  1047. procedure TPQConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  1048. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  1049. var
  1050. x : integer;
  1051. li : Longint;
  1052. begin
  1053. with cursor as TPQCursor do
  1054. begin
  1055. x := FieldBinding[FieldDef.FieldNo-1];
  1056. li := pqgetlength(res,curtuple,x);
  1057. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer,li);
  1058. Move(pqgetvalue(res,CurTuple,x)^, ABlobBuf^.BlobBuffer^.Buffer^, li);
  1059. ABlobBuf^.BlobBuffer^.Size := li;
  1060. end;
  1061. end;
  1062. function TPQConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  1063. begin
  1064. if assigned(cursor) and assigned((cursor as TPQCursor).res) then
  1065. Result := StrToIntDef(PQcmdTuples((cursor as TPQCursor).res),-1)
  1066. else
  1067. Result := -1;
  1068. end;
  1069. function TPQConnection.GetConnectionInfo(InfoType: TConnInfoType): string;
  1070. begin
  1071. Result:='';
  1072. try
  1073. {$IFDEF LinkDynamically}
  1074. InitialisePostgres3;
  1075. {$ENDIF}
  1076. case InfoType of
  1077. citServerType:
  1078. Result:=TPQConnectionDef.TypeName;
  1079. citServerVersion,
  1080. citServerVersionString:
  1081. if Connected then
  1082. Result:=format('%6.6d', [PQserverVersion(GetHandle)]);
  1083. citClientName:
  1084. Result:=TPQConnectionDef.LoadedLibraryName;
  1085. else
  1086. Result:=inherited GetConnectionInfo(InfoType);
  1087. end;
  1088. finally
  1089. {$IFDEF LinkDynamically}
  1090. ReleasePostgres3;
  1091. {$ENDIF}
  1092. end;
  1093. end;
  1094. { TPQConnectionDef }
  1095. class function TPQConnectionDef.TypeName: String;
  1096. begin
  1097. Result:='PostgreSQL';
  1098. end;
  1099. class function TPQConnectionDef.ConnectionClass: TSQLConnectionClass;
  1100. begin
  1101. Result:=TPQConnection;
  1102. end;
  1103. class function TPQConnectionDef.Description: String;
  1104. begin
  1105. Result:='Connect to a PostgreSQL database directly via the client library';
  1106. end;
  1107. class function TPQConnectionDef.DefaultLibraryName: String;
  1108. begin
  1109. {$IfDef LinkDynamically}
  1110. Result:=pqlib;
  1111. {$else}
  1112. Result:='';
  1113. {$endif}
  1114. end;
  1115. class function TPQConnectionDef.LoadFunction: TLibraryLoadFunction;
  1116. begin
  1117. {$IfDef LinkDynamically}
  1118. Result:=@InitialisePostgres3;
  1119. {$else}
  1120. Result:=Nil;
  1121. {$endif}
  1122. end;
  1123. class function TPQConnectionDef.UnLoadFunction: TLibraryUnLoadFunction;
  1124. begin
  1125. {$IfDef LinkDynamically}
  1126. Result:=@ReleasePostgres3;
  1127. {$else}
  1128. Result:=Nil;
  1129. {$endif}
  1130. end;
  1131. class function TPQConnectionDef.LoadedLibraryName: string;
  1132. begin
  1133. {$IfDef LinkDynamically}
  1134. Result:=Postgres3LoadedLibrary;
  1135. {$else}
  1136. Result:='';
  1137. {$endif}
  1138. end;
  1139. initialization
  1140. RegisterConnection(TPQConnectionDef);
  1141. finalization
  1142. UnRegisterConnection(TPQConnectionDef);
  1143. end.