pqconnection.pp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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. TPQCursor = Class;
  14. { TPQTrans }
  15. TPQTrans = Class(TSQLHandle)
  16. protected
  17. PGConn : PPGConn;
  18. FList : TThreadList;
  19. Procedure RegisterCursor(Cursor : TPQCursor);
  20. Procedure UnRegisterCursor(Cursor : TPQCursor);
  21. Public
  22. Constructor Create;
  23. Destructor Destroy; override;
  24. end;
  25. // TField and TFieldDef only support a limited amount of fields.
  26. // TFieldBinding and TExtendedFieldType can be used to map PQ types
  27. // on standard fields and retain mapping info.
  28. TExtendedFieldType = (eftNone,eftEnum,eftCitext);
  29. TFieldBinding = record
  30. FieldDef : TSQLDBFieldDef; // FieldDef this is associated with
  31. Index : Integer; // Tuple index
  32. TypeOID : oid; // Filled with type OID if it is not standard.
  33. TypeName : String; // Filled with type name by GetExtendedFieldInfo
  34. ExtendedFieldType: TExtendedFieldType; //
  35. end;
  36. PFieldBinding = ^TFieldBinding;
  37. TFieldBindings = Array of TFieldBinding;
  38. { TPQCursor }
  39. TPQCursor = Class(TSQLCursor)
  40. protected
  41. Statement : string;
  42. StmtName : string;
  43. tr : TPQTrans;
  44. res : PPGresult;
  45. CurTuple : integer;
  46. FieldBinding : TFieldBindings;
  47. Function GetFieldBinding(F : TFieldDef): PFieldBinding;
  48. Public
  49. Destructor Destroy; override;
  50. end;
  51. { EPQDatabaseError }
  52. EPQDatabaseError = class(EDatabaseError)
  53. public
  54. SEVERITY:string;
  55. SQLSTATE: string;
  56. MESSAGE_PRIMARY:string;
  57. MESSAGE_DETAIL:string;
  58. MESSAGE_HINT:string;
  59. STATEMENT_POSITION:string;
  60. end;
  61. { TPQTranConnection }
  62. TPQTranConnection = class
  63. protected
  64. FPGConn : PPGConn;
  65. FTranActive : boolean;
  66. end;
  67. { TPQConnection }
  68. TPQConnection = class (TSQLConnection)
  69. private
  70. FConnectionPool : TThreadList;
  71. FCursorCount : dword;
  72. FConnectString : string;
  73. FIntegerDateTimes : boolean;
  74. FVerboseErrors : Boolean;
  75. protected
  76. // Protected so they can be used by descendents.
  77. procedure CheckConnectionStatus(var conn: PPGconn);
  78. procedure CheckResultError(var res: PPGresult; conn:PPGconn; ErrMsg: string);
  79. function TranslateFldType(res : PPGresult; Tuple : integer; out Size : integer; Out ATypeOID : oid) : TFieldType;
  80. procedure ExecuteDirectPG(const Query : String);
  81. Procedure GetExtendedFieldInfo(cursor: TPQCursor; Bindings : TFieldBindings);
  82. procedure ApplyFieldUpdate(C : TSQLCursor; P: TSQLDBParam; F: TField; UseOldValue: Boolean); override;
  83. Function ErrorOnUnknownType : Boolean;
  84. // Add connection to pool.
  85. procedure AddConnection(T: TPQTranConnection);
  86. // Release connection in pool.
  87. procedure ReleaseConnection(Conn: PPGConn; DoClear : Boolean);
  88. procedure DoInternalConnect; override;
  89. procedure DoInternalDisconnect; override;
  90. function GetHandle : pointer; override;
  91. Function AllocateCursorHandle : TSQLCursor; override;
  92. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  93. Function AllocateTransactionHandle : TSQLHandle; override;
  94. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  95. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); override;
  96. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  97. function Fetch(cursor : TSQLCursor) : boolean; override;
  98. procedure UnPrepareStatement(cursor : TSQLCursor); override;
  99. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  100. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  101. function RollBack(trans : TSQLHandle) : boolean; override;
  102. function Commit(trans : TSQLHandle) : boolean; override;
  103. procedure CommitRetaining(trans : TSQLHandle); override;
  104. function StartImplicitTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  105. function StartDBTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  106. procedure RollBackRetaining(trans : TSQLHandle); override;
  107. procedure UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string); override;
  108. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor;ATransaction : TSQLTransaction); override;
  109. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  110. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  111. function GetNextValueSQL(const SequenceName: string; IncrementBy: Integer): string; override;
  112. public
  113. constructor Create(AOwner : TComponent); override;
  114. destructor Destroy; override;
  115. function GetConnectionInfo(InfoType:TConnInfoType): string; override;
  116. procedure CreateDB; override;
  117. procedure DropDB; override;
  118. published
  119. property DatabaseName;
  120. property KeepConnection;
  121. property LoginPrompt;
  122. property Params;
  123. property OnLogin;
  124. Property VerboseErrors : Boolean Read FVerboseErrors Write FVerboseErrors default true;
  125. end;
  126. { TPQConnectionDef }
  127. TPQConnectionDef = Class(TConnectionDef)
  128. Class Function TypeName : String; override;
  129. Class Function ConnectionClass : TSQLConnectionClass; override;
  130. Class Function Description : String; override;
  131. Class Function DefaultLibraryName : String; override;
  132. Class Function LoadFunction : TLibraryLoadFunction; override;
  133. Class Function UnLoadFunction : TLibraryUnLoadFunction; override;
  134. Class Function LoadedLibraryName: string; override;
  135. end;
  136. implementation
  137. uses math, strutils, FmtBCD;
  138. ResourceString
  139. SErrRollbackFailed = 'Rollback transaction failed';
  140. SErrCommitFailed = 'Commit transaction failed';
  141. SErrConnectionFailed = 'Connection to database failed';
  142. SErrTransactionFailed = 'Start of transacion failed';
  143. SErrExecuteFailed = 'Execution of query failed';
  144. SErrPrepareFailed = 'Preparation of query failed.';
  145. SErrUnPrepareFailed = 'Unpreparation of query failed.';
  146. const Oid_Bool = 16;
  147. Oid_Bytea = 17;
  148. Oid_char = 18;
  149. Oid_Text = 25;
  150. Oid_Oid = 26;
  151. Oid_Name = 19;
  152. Oid_Int8 = 20;
  153. Oid_int2 = 21;
  154. Oid_Int4 = 23;
  155. Oid_JSON = 114;
  156. Oid_Float4 = 700;
  157. Oid_Money = 790;
  158. Oid_Float8 = 701;
  159. Oid_Unknown = 705;
  160. Oid_MacAddr = 829;
  161. Oid_Inet = 869;
  162. Oid_bpchar = 1042;
  163. Oid_varchar = 1043;
  164. oid_date = 1082;
  165. oid_time = 1083;
  166. Oid_timeTZ = 1266;
  167. Oid_timestamp = 1114;
  168. Oid_timestampTZ = 1184;
  169. Oid_interval = 1186;
  170. oid_numeric = 1700;
  171. Oid_uuid = 2950;
  172. { TPQTrans }
  173. constructor TPQTrans.Create;
  174. begin
  175. FList:=TThreadList.Create;
  176. FList.Duplicates:=dupIgnore;
  177. end;
  178. destructor TPQTrans.Destroy;
  179. Var
  180. L : TList;
  181. I : integer;
  182. begin
  183. L:=FList.LockList;
  184. try
  185. For I:=0 to L.Count-1 do
  186. TPQCursor(L[i]).tr:=Nil;
  187. finally
  188. FList.UnlockList;
  189. end;
  190. FreeAndNil(FList);
  191. inherited Destroy;
  192. end;
  193. procedure TPQTrans.RegisterCursor(Cursor: TPQCursor);
  194. begin
  195. FList.Add(Cursor);
  196. Cursor.tr:=Self;
  197. end;
  198. procedure TPQTrans.UnRegisterCursor(Cursor: TPQCursor);
  199. begin
  200. Cursor.tr:=Nil;
  201. FList.Remove(Cursor);
  202. end;
  203. { TPQCursor }
  204. destructor TPQCursor.Destroy;
  205. begin
  206. if Assigned(tr) then
  207. tr.UnRegisterCursor(Self);
  208. inherited Destroy;
  209. end;
  210. function TPQCursor.GetFieldBinding(F: TFieldDef): PFieldBinding;
  211. Var
  212. I : Integer;
  213. begin
  214. Result:=Nil;
  215. if (F=Nil) then exit;
  216. // This is an optimization: it is so for 99% of cases (FieldNo-1=array index)
  217. if F is TSQLDBFieldDef then
  218. Result:=PFieldBinding(TSQLDBFieldDef(F).SQLDBData)
  219. else If (FieldBinding[F.FieldNo-1].FieldDef=F) then
  220. Result:=@FieldBinding[F.FieldNo-1]
  221. else
  222. begin
  223. I:=Length(FieldBinding)-1;
  224. While (I>=0) and (FieldBinding[i].FieldDef<>F) do
  225. Dec(I);
  226. if I>=0 then
  227. Result:=@FieldBinding[i];
  228. end;
  229. end;
  230. { TPQConnection }
  231. constructor TPQConnection.Create(AOwner : TComponent);
  232. begin
  233. inherited;
  234. FConnOptions := FConnOptions + [sqSupportParams, sqSupportEmptyDatabaseName, sqEscapeRepeat, sqEscapeSlash, sqImplicitTransaction,sqSupportReturning,sqSequences];
  235. FieldNameQuoteChars:=DoubleQuotes;
  236. VerboseErrors:=True;
  237. FConnectionPool:=TThreadlist.Create;
  238. end;
  239. destructor TPQConnection.Destroy;
  240. begin
  241. // We must disconnect here. If it is done in inherited, then connection pool is gone.
  242. Connected:=False;
  243. FreeAndNil(FConnectionPool);
  244. inherited destroy;
  245. end;
  246. procedure TPQConnection.CreateDB;
  247. begin
  248. ExecuteDirectPG('CREATE DATABASE ' +DatabaseName);
  249. end;
  250. procedure TPQConnection.DropDB;
  251. begin
  252. ExecuteDirectPG('DROP DATABASE ' +DatabaseName);
  253. end;
  254. procedure TPQConnection.ExecuteDirectPG(const Query: String);
  255. var ASQLDatabaseHandle : PPGConn;
  256. res : PPGresult;
  257. begin
  258. CheckDisConnected;
  259. {$IfDef LinkDynamically}
  260. InitialisePostgres3;
  261. {$EndIf}
  262. FConnectString := '';
  263. if (UserName <> '') then FConnectString := FConnectString + ' user=''' + UserName + '''';
  264. if (Password <> '') then FConnectString := FConnectString + ' password=''' + Password + '''';
  265. if (HostName <> '') then FConnectString := FConnectString + ' host=''' + HostName + '''';
  266. FConnectString := FConnectString + ' dbname=''template1''';
  267. if (Params.Text <> '') then FConnectString := FConnectString + ' '+Params.Text;
  268. ASQLDatabaseHandle := PQconnectdb(pchar(FConnectString));
  269. CheckConnectionStatus(ASQLDatabaseHandle);
  270. res := PQexec(ASQLDatabaseHandle,pchar(query));
  271. CheckResultError(res,ASQLDatabaseHandle,SDBCreateDropFailed);
  272. PQclear(res);
  273. PQFinish(ASQLDatabaseHandle);
  274. {$IfDef LinkDynamically}
  275. ReleasePostgres3;
  276. {$EndIf}
  277. end;
  278. procedure TPQConnection.GetExtendedFieldInfo(cursor: TPQCursor;
  279. Bindings: TFieldBindings);
  280. Var
  281. tt,tc,Tn,S : String;
  282. I,J : Integer;
  283. Res : PPGResult;
  284. toid : oid;
  285. begin
  286. For I:=0 to Length(Bindings)-1 do
  287. if (Bindings[i].TypeOID>0) then
  288. begin
  289. if (S<>'') then
  290. S:=S+', ';
  291. S:=S+IntToStr(Bindings[i].TypeOID);
  292. end;
  293. if (S='') then
  294. exit;
  295. S:='select oid,typname,typtype,typcategory from pg_type where oid in ('+S+') order by oid';
  296. Res:=PQExec(Cursor.tr.PGConn,PChar(S));
  297. if (PQresultStatus(res)<>PGRES_TUPLES_OK) then
  298. CheckResultError(Res,Cursor.tr.PGConn,'Error getting type info');
  299. try
  300. For I:=0 to PQntuples(Res)-1 do
  301. begin
  302. toid:=Strtoint(pqgetvalue(Res,i,0));
  303. tn:=pqgetvalue(Res,i,1);
  304. tt:=pqgetvalue(Res,i,2);
  305. tc:=pqgetvalue(Res,i,3);
  306. J:=length(Bindings)-1;
  307. while (J>= 0) do
  308. begin
  309. if (Bindings[j].TypeOID=toid) then
  310. Case tt of
  311. 'e':
  312. Bindings[j].ExtendedFieldType:=eftEnum;
  313. 'citext':
  314. Bindings[j].ExtendedFieldType:=eftCitext;
  315. end;
  316. Dec(J);
  317. end;
  318. end;
  319. finally
  320. PQClear(Res);
  321. end;
  322. end;
  323. procedure TPQConnection.ApplyFieldUpdate(C : TSQLCursor; P: TSQLDBParam; F: TField;
  324. UseOldValue: Boolean);
  325. begin
  326. inherited ApplyFieldUpdate(C,P, F, UseOldValue);
  327. if (C is TPQCursor) then
  328. P.SQLDBData:=TPQCursor(C).GetFieldBinding(F.FieldDef);
  329. end;
  330. function TPQConnection.ErrorOnUnknownType: Boolean;
  331. begin
  332. Result:=False;
  333. end;
  334. procedure TPQConnection.AddConnection(T: TPQTranConnection);
  335. begin
  336. FConnectionPool.Add(T);
  337. end;
  338. procedure TPQConnection.ReleaseConnection(Conn: PPGConn; DoClear: Boolean);
  339. Var
  340. I : Integer;
  341. L : TList;
  342. T : TPQTranConnection;
  343. begin
  344. L:=FConnectionPool.LockList;
  345. // make connection available in pool
  346. try
  347. for i:=0 to L.Count-1 do
  348. begin
  349. T:=TPQTranConnection(L[i]);
  350. if (T.FPGConn=Conn) then
  351. begin
  352. T.FTranActive:=false;
  353. if DoClear then
  354. T.FPGConn:=Nil;
  355. break;
  356. end;
  357. end
  358. finally
  359. FConnectionPool.UnlockList;
  360. end;
  361. end;
  362. function TPQConnection.GetTransactionHandle(trans : TSQLHandle): pointer;
  363. begin
  364. Result := trans;
  365. end;
  366. function TPQConnection.RollBack(trans : TSQLHandle) : boolean;
  367. var
  368. res : PPGresult;
  369. tr : TPQTrans;
  370. i : Integer;
  371. L : TList;
  372. begin
  373. result := false;
  374. tr := trans as TPQTrans;
  375. // unprepare statements associated with given transaction
  376. L:=tr.FList.LockList;
  377. try
  378. For I:=0 to L.Count-1 do
  379. begin
  380. UnprepareStatement(TPQCursor(L[i]));
  381. TPQCursor(L[i]).tr:=Nil;
  382. end;
  383. L.Clear;
  384. finally
  385. tr.FList.UnlockList;
  386. end;
  387. res := PQexec(tr.PGConn, 'ROLLBACK');
  388. CheckResultError(res,tr.PGConn,SErrRollbackFailed);
  389. PQclear(res);
  390. ReleaseConnection(tr.PGCOnn,false);
  391. result := true;
  392. end;
  393. function TPQConnection.Commit(trans : TSQLHandle) : boolean;
  394. var
  395. res : PPGresult;
  396. tr : TPQTrans;
  397. begin
  398. result := false;
  399. tr := trans as TPQTrans;
  400. res := PQexec(tr.PGConn, 'COMMIT');
  401. CheckResultError(res,tr.PGConn,SErrCommitFailed);
  402. PQclear(res);
  403. //make connection available in pool
  404. ReleaseConnection(tr.PGConn,false);
  405. result := true;
  406. end;
  407. procedure TPQConnection.RollBackRetaining(trans : TSQLHandle);
  408. var
  409. res : PPGresult;
  410. tr : TPQTrans;
  411. begin
  412. tr := trans as TPQTrans;
  413. res := PQexec(tr.PGConn, 'ROLLBACK');
  414. CheckResultError(res,tr.PGConn,SErrRollbackFailed);
  415. PQclear(res);
  416. res := PQexec(tr.PGConn, 'BEGIN');
  417. CheckResultError(res,tr.PGConn,sErrTransactionFailed);
  418. PQclear(res);
  419. end;
  420. procedure TPQConnection.CommitRetaining(trans : TSQLHandle);
  421. var
  422. res : PPGresult;
  423. tr : TPQTrans;
  424. begin
  425. tr := trans as TPQTrans;
  426. res := PQexec(tr.PGConn, 'COMMIT');
  427. CheckResultError(res,tr.PGConn,SErrCommitFailed);
  428. PQclear(res);
  429. res := PQexec(tr.PGConn, 'BEGIN');
  430. CheckResultError(res,tr.PGConn,sErrTransactionFailed);
  431. PQclear(res);
  432. end;
  433. function TPQConnection.StartImplicitTransaction(trans : TSQLHandle; AParams : string) : boolean;
  434. var
  435. i : Integer;
  436. T : TPQTranConnection;
  437. L : TList;
  438. begin
  439. //find an unused connection in the pool
  440. i:=0;
  441. T:=Nil;
  442. L:=FConnectionPool.LockList;
  443. try
  444. while (i<L.Count) do
  445. begin
  446. T:=TPQTranConnection(L[i]);
  447. if (T.FPGConn=nil) or not T.FTranActive then
  448. break
  449. else
  450. T:=Nil;
  451. i:=i+1;
  452. end;
  453. // set to active now, so when we exit critical section,
  454. // it will be marked active and will not be found.
  455. if Assigned(T) then
  456. T.FTranActive:=true;
  457. finally
  458. FConnectionPool.UnLockList;
  459. end;
  460. if (T=Nil) then
  461. begin
  462. T:=TPQTranConnection.Create;
  463. T.FTranActive:=True;
  464. AddConnection(T);
  465. end;
  466. if (T.FPGConn=nil) then
  467. begin
  468. T.FPGConn := PQconnectdb(pchar(FConnectString));
  469. CheckConnectionStatus(T.FPGConn);
  470. if CharSet <> '' then
  471. PQsetClientEncoding(T.FPGConn, pchar(CharSet));
  472. end;
  473. TPQTrans(trans).PGConn := T.FPGConn;
  474. Result := true;
  475. end;
  476. function TPQConnection.StartDBTransaction(trans: TSQLHandle; AParams: string
  477. ): boolean;
  478. Var
  479. res : PPGresult;
  480. tr : TPQTrans;
  481. begin
  482. Result:=StartImplicitTransaction(trans, AParams);
  483. if Result then
  484. begin
  485. tr := trans as TPQTrans;
  486. res := PQexec(tr.PGConn, 'BEGIN');
  487. CheckResultError(res,tr.PGConn,sErrTransactionFailed);
  488. PQclear(res);
  489. end;
  490. end;
  491. procedure TPQConnection.DoInternalConnect;
  492. var
  493. ASQLDatabaseHandle : PPGConn;
  494. T : TPQTranConnection;
  495. begin
  496. {$IfDef LinkDynamically}
  497. InitialisePostgres3;
  498. {$EndIf}
  499. inherited DoInternalConnect;
  500. FConnectString := '';
  501. if (UserName <> '') then FConnectString := FConnectString + ' user=''' + UserName + '''';
  502. if (Password <> '') then FConnectString := FConnectString + ' password=''' + Password + '''';
  503. if (HostName <> '') then FConnectString := FConnectString + ' host=''' + HostName + '''';
  504. if (DatabaseName <> '') then FConnectString := FConnectString + ' dbname=''' + DatabaseName + '''';
  505. if (Params.Text <> '') then FConnectString := FConnectString + ' '+Params.Text;
  506. ASQLDatabaseHandle := PQconnectdb(pchar(FConnectString));
  507. try
  508. CheckConnectionStatus(ASQLDatabaseHandle);
  509. except
  510. DoInternalDisconnect;
  511. raise;
  512. end;
  513. // This only works for pg>=8.0, so timestamps won't work with earlier versions of pg which are compiled with integer_datetimes on
  514. if PQparameterStatus<>nil then
  515. FIntegerDateTimes := PQparameterStatus(ASQLDatabaseHandle,'integer_datetimes') = 'on';
  516. T:=TPQTranConnection.Create;
  517. T.FPGConn:=ASQLDatabaseHandle;
  518. T.FTranActive:=false;
  519. AddConnection(T);
  520. end;
  521. procedure TPQConnection.DoInternalDisconnect;
  522. var
  523. i:integer;
  524. L : TList;
  525. T : TPQTranConnection;
  526. begin
  527. Inherited;
  528. L:=FConnectionPool.LockList;
  529. try
  530. for i:=0 to L.Count-1 do
  531. begin
  532. T:=TPQTranConnection(L[i]);
  533. if assigned(T.FPGConn) then
  534. PQfinish(T.FPGConn);
  535. T.Free;
  536. end;
  537. L.Clear;
  538. finally
  539. FConnectionPool.UnLockList;
  540. end;
  541. {$IfDef LinkDynamically}
  542. ReleasePostgres3;
  543. {$EndIf}
  544. end;
  545. procedure TPQConnection.CheckConnectionStatus(var conn: PPGconn);
  546. var sErr: string;
  547. begin
  548. if (PQstatus(conn) = CONNECTION_BAD) then
  549. begin
  550. sErr := PQerrorMessage(conn);
  551. //make connection available in pool
  552. ReleaseConnection(Conn,True);
  553. PQfinish(conn);
  554. DatabaseError(sErrConnectionFailed + ' (PostgreSQL: ' + sErr + ')', Self);
  555. end;
  556. end;
  557. procedure TPQConnection.CheckResultError(var res: PPGresult; conn: PPGconn;
  558. ErrMsg: string);
  559. Procedure MaybeAdd(Var S : String; Prefix,Msg : String);
  560. begin
  561. if (Msg='') then
  562. exit;
  563. S:=S+LineEnding+Prefix+': '+Msg;
  564. end;
  565. var
  566. E: EPQDatabaseError;
  567. sErr: string;
  568. CompName: string;
  569. SEVERITY: string;
  570. SQLSTATE: string;
  571. MESSAGE_PRIMARY: string;
  572. MESSAGE_DETAIL: string;
  573. MESSAGE_HINT: string;
  574. STATEMENT_POSITION: string;
  575. P : Pchar;
  576. haveError : Boolean;
  577. begin
  578. HaveError:=False;
  579. if (Res=Nil) then
  580. begin
  581. HaveError:=True;
  582. P:=PQerrorMessage(conn);
  583. If Assigned(p) then
  584. ErrMsg:=StrPas(P);
  585. end
  586. else if (PQresultStatus(res) <> PGRES_COMMAND_OK) then
  587. begin
  588. HaveError:=True;
  589. SEVERITY:=PQresultErrorField(res,ord('S'));
  590. SQLSTATE:=PQresultErrorField(res,ord('C'));
  591. MESSAGE_PRIMARY:=PQresultErrorField(res,ord('M'));
  592. MESSAGE_DETAIL:=PQresultErrorField(res,ord('D'));
  593. MESSAGE_HINT:=PQresultErrorField(res,ord('H'));
  594. STATEMENT_POSITION:=PQresultErrorField(res,ord('P'));
  595. sErr:=PQresultErrorMessage(res);
  596. if VerboseErrors then
  597. begin
  598. MaybeAdd(sErr,'Severity',SEVERITY);
  599. MaybeAdd(sErr,'SQL State',SQLSTATE);
  600. MaybeAdd(sErr,'Primary Error',MESSAGE_PRIMARY);
  601. MaybeAdd(sErr,'Error Detail',MESSAGE_DETAIL);
  602. MaybeAdd(sErr,'Hint',MESSAGE_HINT);
  603. MaybeAdd(sErr,'Character',STATEMENT_POSITION);
  604. end;
  605. end;
  606. if HaveError then
  607. begin
  608. if (Self.Name='') then CompName := Self.ClassName else CompName := Self.Name;
  609. E:=EPQDatabaseError.CreateFmt('%s : %s (PostgreSQL: %s)', [CompName, ErrMsg, sErr]);
  610. E.SEVERITY:=SEVERITY;
  611. E.SQLSTATE:=SQLSTATE;
  612. E.MESSAGE_PRIMARY:=MESSAGE_PRIMARY;
  613. E.MESSAGE_DETAIL:=MESSAGE_DETAIL;
  614. E.MESSAGE_HINT:=MESSAGE_HINT;
  615. E.STATEMENT_POSITION:=STATEMENT_POSITION;
  616. PQclear(res);
  617. res:=nil;
  618. if assigned(conn) then
  619. begin
  620. PQFinish(conn);
  621. ReleaseConnection(Conn,True);
  622. end;
  623. raise E;
  624. end;
  625. end;
  626. function TPQConnection.TranslateFldType(res: PPGresult; Tuple: integer; out
  627. Size: integer; out ATypeOID: oid): TFieldType;
  628. const
  629. VARHDRSZ=sizeof(longint);
  630. var
  631. li : longint;
  632. aoid : oid;
  633. begin
  634. Size := 0;
  635. ATypeOID:=0;
  636. AOID:=PQftype(res,Tuple);
  637. case AOID of
  638. Oid_varchar,Oid_bpchar,
  639. Oid_name : begin
  640. Result := ftString;
  641. size := PQfsize(Res, Tuple);
  642. if (size = -1) then
  643. begin
  644. li := PQfmod(res,Tuple);
  645. if li = -1 then
  646. size := dsMaxStringSize
  647. else
  648. size := (li-VARHDRSZ) and $FFFF;
  649. end;
  650. if size > MaxSmallint then size := MaxSmallint;
  651. end;
  652. // Oid_text : Result := ftString;
  653. Oid_text,Oid_JSON : Result := ftMemo;
  654. Oid_Bytea : Result := ftBlob;
  655. Oid_oid : Result := ftInteger;
  656. Oid_int8 : Result := ftLargeInt;
  657. Oid_int4 : Result := ftInteger;
  658. Oid_int2 : Result := ftSmallInt;
  659. Oid_Float4 : Result := ftFloat;
  660. Oid_Float8 : Result := ftFloat;
  661. Oid_TimeStamp,
  662. Oid_TimeStampTZ : Result := ftDateTime;
  663. Oid_Date : Result := ftDate;
  664. Oid_Interval,
  665. Oid_Time,
  666. Oid_TimeTZ : Result := ftTime;
  667. Oid_Bool : Result := ftBoolean;
  668. Oid_Numeric : begin
  669. Result := ftBCD;
  670. li := PQfmod(res,Tuple);
  671. if li = -1 then
  672. size := 4 // No information about the size available, use the maximum value
  673. else
  674. // The precision is the high 16 bits, the scale the
  675. // low 16 bits with an offset of sizeof(int32).
  676. begin
  677. size := (li-VARHDRSZ) and $FFFF;
  678. if (size > MaxBCDScale) or ((li shr 16)-size > MaxBCDPrecision-MaxBCDScale) then
  679. Result := ftFmtBCD;
  680. end;
  681. end;
  682. Oid_Money : Result := ftCurrency;
  683. Oid_char : begin
  684. Result := ftFixedChar;
  685. Size := 1;
  686. end;
  687. Oid_uuid : begin
  688. Result := ftGuid;
  689. Size := 38;
  690. end;
  691. Oid_MacAddr : begin
  692. Result := ftFixedChar;
  693. Size := 17;
  694. end;
  695. Oid_Inet : begin
  696. Result := ftString;
  697. Size := 39;
  698. end;
  699. Oid_Unknown : Result := ftUnknown;
  700. else
  701. Result:=ftUnknown;
  702. ATypeOID:=AOID;
  703. end;
  704. end;
  705. function TPQConnection.AllocateCursorHandle: TSQLCursor;
  706. begin
  707. result := TPQCursor.create;
  708. end;
  709. procedure TPQConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  710. begin
  711. FreeAndNil(cursor);
  712. end;
  713. function TPQConnection.AllocateTransactionHandle: TSQLHandle;
  714. begin
  715. result := TPQTrans.create;
  716. end;
  717. procedure TPQConnection.PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams);
  718. const TypeStrings : array[TFieldType] of string =
  719. (
  720. 'Unknown', // ftUnknown
  721. 'text', // ftString
  722. 'smallint', // ftSmallint
  723. 'int', // ftInteger
  724. 'int', // ftWord
  725. 'bool', // ftBoolean
  726. 'float', // ftFloat
  727. 'money', // ftCurrency
  728. 'numeric', // ftBCD
  729. 'date', // ftDate
  730. 'time', // ftTime
  731. 'timestamp', // ftDateTime
  732. 'Unknown', // ftBytes
  733. 'Unknown', // ftVarBytes
  734. 'Unknown', // ftAutoInc
  735. 'bytea', // ftBlob
  736. 'text', // ftMemo
  737. 'bytea', // ftGraphic
  738. 'text', // ftFmtMemo
  739. 'Unknown', // ftParadoxOle
  740. 'Unknown', // ftDBaseOle
  741. 'Unknown', // ftTypedBinary
  742. 'Unknown', // ftCursor
  743. 'char', // ftFixedChar
  744. 'text', // ftWideString
  745. 'bigint', // ftLargeint
  746. 'Unknown', // ftADT
  747. 'Unknown', // ftArray
  748. 'Unknown', // ftReference
  749. 'Unknown', // ftDataSet
  750. 'Unknown', // ftOraBlob
  751. 'Unknown', // ftOraClob
  752. 'Unknown', // ftVariant
  753. 'Unknown', // ftInterface
  754. 'Unknown', // ftIDispatch
  755. 'uuid', // ftGuid
  756. 'Unknown', // ftTimeStamp
  757. 'numeric', // ftFMTBcd
  758. 'Unknown', // ftFixedWideChar
  759. 'Unknown', // ftWideMemo
  760. 'Unknown', // ftOraTimeStamp
  761. 'Unknown', // ftOraInterval
  762. 'Unknown', // ftLongWord
  763. 'Unknown', // ftShortint
  764. 'Unknown', // ftByte
  765. 'Unknown' // ftExtended
  766. );
  767. var
  768. s,ts : string;
  769. i : integer;
  770. P : TParam;
  771. PQ : TSQLDBParam;
  772. begin
  773. with (cursor as TPQCursor) do
  774. begin
  775. FPrepared := False;
  776. FDirect := False;
  777. // Prior to v8 there is no support for cursors and parameters.
  778. // So that's not supported.
  779. if FStatementType in [stInsert,stUpdate,stDelete, stSelect] then
  780. begin
  781. StmtName := 'prepst'+inttostr(FCursorCount);
  782. InterlockedIncrement(FCursorCount);
  783. TPQTrans(aTransaction.Handle).RegisterCursor(Cursor as TPQCursor);
  784. // Only available for pq 8.0, so don't use it...
  785. // Res := pqprepare(tr,'prepst'+name+nr,pchar(buf),params.Count,pchar(''));
  786. s := 'prepare '+StmtName+' ';
  787. if Assigned(AParams) and (AParams.Count > 0) then
  788. begin
  789. s := s + '(';
  790. for i := 0 to AParams.Count-1 do
  791. begin
  792. P:=AParams[i];
  793. If (P is TSQLDBParam) then
  794. PQ:=TSQLDBParam(P)
  795. else
  796. PQ:=Nil;
  797. TS:=TypeStrings[P.DataType];
  798. if (TS<>'Unknown') then
  799. begin
  800. If Assigned(PQ)
  801. and Assigned(PQ.SQLDBData)
  802. and (PFieldBinding(PQ.SQLDBData)^.ExtendedFieldType=eftEnum) then
  803. ts:='unknown';
  804. s := s + ts + ','
  805. end
  806. else
  807. begin
  808. if AParams[i].DataType = ftUnknown then
  809. begin
  810. if AParams[i].IsNull then
  811. s:=s+' unknown ,'
  812. else
  813. DatabaseErrorFmt(SUnknownParamFieldType,[AParams[i].Name],self)
  814. end
  815. else
  816. DatabaseErrorFmt(SUnsupportedParameter,[Fieldtypenames[AParams[i].DataType]],self);
  817. end;
  818. end;
  819. s[length(s)] := ')';
  820. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psPostgreSQL);
  821. end;
  822. s := s + ' as ' + buf;
  823. if LogEvent(detActualSQL) then
  824. Log(detActualSQL,S);
  825. res := PQexec(tr.PGConn,pchar(s));
  826. CheckResultError(res,nil,SErrPrepareFailed);
  827. // if statement is INSERT, UPDATE, DELETE with RETURNING clause, then
  828. // override the statement type derrived by parsing the query.
  829. if (FStatementType in [stInsert,stUpdate,stDelete]) and (pos('RETURNING', upcase(s)) > 0) then
  830. begin
  831. PQclear(res);
  832. res := PQdescribePrepared(tr.PGConn,pchar(StmtName));
  833. if (PQresultStatus(res) = PGRES_COMMAND_OK) and (PQnfields(res) > 0) then
  834. FStatementType := stSelect;
  835. end;
  836. FPrepared := True;
  837. end
  838. else
  839. begin
  840. if Assigned(AParams) then
  841. Statement := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psPostgreSQL)
  842. else
  843. Statement:=Buf;
  844. FDirect:=True;
  845. end;
  846. end;
  847. end;
  848. procedure TPQConnection.UnPrepareStatement(cursor : TSQLCursor);
  849. begin
  850. with (cursor as TPQCursor) do
  851. begin
  852. PQclear(res);
  853. res:=nil;
  854. if FPrepared then
  855. begin
  856. if assigned(tr) and (PQtransactionStatus(tr.PGConn) <> PQTRANS_INERROR) then
  857. begin
  858. res := PQexec(tr.PGConn,pchar('deallocate '+StmtName));
  859. CheckResultError(res,nil,SErrUnPrepareFailed);
  860. PQclear(res);
  861. res:=nil;
  862. end;
  863. FPrepared := False;
  864. end;
  865. end;
  866. end;
  867. procedure TPQConnection.Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams);
  868. var ar : array of PAnsiChar;
  869. handled : boolean;
  870. l,i : integer;
  871. s : RawByteString;
  872. bd : TBlobData;
  873. lengths,formats : array of integer;
  874. ParamNames,
  875. ParamValues : array of string;
  876. cash: int64;
  877. function FormatTimeInterval(Time: TDateTime): string; // supports Time >= '24:00:00'
  878. var hour, minute, second, millisecond: word;
  879. begin
  880. DecodeTime(Time, hour, minute, second, millisecond);
  881. Result := Format('%.2d:%.2d:%.2d.%.3d',[Trunc(Time)*24+hour,minute,second,millisecond]);
  882. end;
  883. begin
  884. with cursor as TPQCursor do
  885. begin
  886. CurTuple:=-1;
  887. PQclear(res);
  888. if FStatementType in [stInsert,stUpdate,stDelete,stSelect] then
  889. begin
  890. if LogEvent(detParamValue) then
  891. LogParams(AParams);
  892. if Assigned(AParams) and (AParams.Count > 0) then
  893. begin
  894. l:=AParams.Count;
  895. setlength(ar,l);
  896. setlength(lengths,l);
  897. setlength(formats,l);
  898. for i := 0 to AParams.Count -1 do if not AParams[i].IsNull then
  899. begin
  900. handled:=False;
  901. case AParams[i].DataType of
  902. ftDateTime:
  903. s := FormatDateTime('yyyy"-"mm"-"dd hh":"nn":"ss.zzz', AParams[i].AsDateTime);
  904. ftDate:
  905. s := FormatDateTime('yyyy"-"mm"-"dd', AParams[i].AsDateTime);
  906. ftTime:
  907. s := FormatTimeInterval(AParams[i].AsDateTime);
  908. ftFloat:
  909. Str(AParams[i].AsFloat, s);
  910. ftBCD:
  911. Str(AParams[i].AsCurrency, s);
  912. ftCurrency:
  913. begin
  914. cash:=NtoBE(round(AParams[i].AsCurrency*100));
  915. setlength(s, sizeof(cash));
  916. Move(cash, s[1], sizeof(cash));
  917. end;
  918. ftFmtBCD:
  919. s := BCDToStr(AParams[i].AsFMTBCD, FSQLFormatSettings);
  920. ftBlob, ftGraphic:
  921. begin
  922. Handled:=true;
  923. bd:= AParams[i].AsBlob;
  924. l:=length(BD);
  925. if l>0 then
  926. begin
  927. GetMem(ar[i],l+1);
  928. ar[i][l]:=#0;
  929. Move(BD[0],ar[i]^, L);
  930. lengths[i]:=l;
  931. end;
  932. end
  933. else
  934. s := GetAsString(AParams[i]);
  935. end; {case}
  936. if not handled then
  937. begin
  938. l:=length(s);
  939. GetMem(ar[i],l+1);
  940. StrMove(PAnsiChar(ar[i]), PAnsiChar(s), L+1);
  941. lengths[i]:=L;
  942. end;
  943. if (AParams[i].DataType in [ftBlob,ftMemo,ftGraphic,ftCurrency]) then
  944. Formats[i]:=1
  945. else
  946. Formats[i]:=0;
  947. end
  948. else
  949. FreeAndNil(ar[i]);
  950. res := PQexecPrepared(tr.PGConn,pchar(StmtName),AParams.Count,@Ar[0],@Lengths[0],@Formats[0],1);
  951. for i := 0 to AParams.Count -1 do
  952. FreeMem(ar[i]);
  953. end
  954. else
  955. res := PQexecPrepared(tr.PGConn,pchar(StmtName),0,nil,nil,nil,1);
  956. end
  957. else
  958. begin
  959. // RegisterCursor sets tr
  960. TPQTrans(aTransaction.Handle).RegisterCursor(Cursor as TPQCursor);
  961. if Assigned(AParams) and (AParams.Count > 0) then
  962. begin
  963. setlength(ParamNames,AParams.Count);
  964. setlength(ParamValues,AParams.Count);
  965. for i := 0 to AParams.Count -1 do
  966. begin
  967. ParamNames[AParams.Count-i-1] := '$'+inttostr(AParams[i].index+1);
  968. ParamValues[AParams.Count-i-1] := GetAsSQLText(AParams[i]);
  969. end;
  970. s := stringsreplace(Statement,ParamNames,ParamValues,[rfReplaceAll]);
  971. end
  972. else
  973. s := Statement;
  974. res := PQexec(tr.PGConn,pchar(s));
  975. if (PQresultStatus(res) in [PGRES_COMMAND_OK]) then
  976. begin
  977. PQclear(res);
  978. res:=nil;
  979. end;
  980. end;
  981. if assigned(res) and not (PQresultStatus(res) in [PGRES_COMMAND_OK,PGRES_TUPLES_OK]) then
  982. begin
  983. // Don't perform the rollback, only make it possible to do a rollback.
  984. // The other databases also don't do this.
  985. //atransaction.Rollback;
  986. CheckResultError(res,nil,SErrExecuteFailed);
  987. end;
  988. FSelectable := assigned(res) and (PQresultStatus(res)=PGRES_TUPLES_OK);
  989. end;
  990. end;
  991. procedure TPQConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs);
  992. var
  993. i : integer;
  994. asize : integer;
  995. aoid : oid;
  996. fieldtype : tfieldtype;
  997. nFields : integer;
  998. b : Boolean;
  999. Q : TPQCursor;
  1000. FD : TSQLDBFieldDef;
  1001. FB : PFieldBinding;
  1002. begin
  1003. B:=False;
  1004. Q:=cursor as TPQCursor;
  1005. with Q do
  1006. begin
  1007. nFields := PQnfields(Res);
  1008. setlength(FieldBinding,nFields);
  1009. for i := 0 to nFields-1 do
  1010. begin
  1011. fieldtype := TranslateFldType(Res, i, asize, aoid );
  1012. FD := AddFieldDef(FieldDefs, i+1, PQfname(Res, i), fieldtype, asize, -1, False, False, False) as TSQLDBFieldDef;
  1013. With FD do
  1014. begin
  1015. SQLDBData:=@FieldBinding[i];
  1016. FieldBinding[i].Index:=i;
  1017. FieldBinding[i].FieldDef:=FD;
  1018. FieldBinding[i].TypeOID:=aOID;
  1019. B:=B or (aOID>0);
  1020. end;
  1021. end;
  1022. CurTuple := -1;
  1023. end;
  1024. if B then
  1025. begin
  1026. // get all information in 1 go.
  1027. GetExtendedFieldInfo(Q,Q.FieldBinding);
  1028. For I:=0 to Length(Q.FieldBinding)-1 do
  1029. begin
  1030. FB:[email protected][i];
  1031. if (FB^.TypeOID>0) then
  1032. begin
  1033. FD:=FB^.FieldDef;
  1034. Case FB^.ExtendedFieldType of
  1035. eftEnum :
  1036. begin
  1037. FD.DataType:=ftString;
  1038. FD.Size:=64;
  1039. //FD.Attributes:=FD.Attributes+[faReadonly];
  1040. end;
  1041. eftCitext:
  1042. begin
  1043. FD.DataType:=ftMemo;
  1044. end
  1045. else
  1046. if ErrorOnUnknownType then
  1047. DatabaseError('Unhandled field type :'+FB^.TypeName,Self);
  1048. end;
  1049. end;
  1050. end;
  1051. end;
  1052. end;
  1053. function TPQConnection.GetHandle: pointer;
  1054. var
  1055. i:integer;
  1056. L : TList;
  1057. T : TPQTranConnection;
  1058. begin
  1059. result:=nil;
  1060. if not Connected then
  1061. exit;
  1062. //Get any handle that is (still) connected
  1063. L:=FConnectionPool.LockList;
  1064. try
  1065. I:=L.Count-1;
  1066. While (I>=0) and (Result=Nil) do
  1067. begin
  1068. T:=TPQTranConnection(L[i]);
  1069. if assigned(T.FPGConn) and (PQstatus(T.FPGConn)<>CONNECTION_BAD) then
  1070. Result:=T.FPGConn;
  1071. Dec(I);
  1072. end;
  1073. finally
  1074. FConnectionPool.UnLockList;
  1075. end;
  1076. if Result<>Nil then
  1077. exit;
  1078. //Nothing connected!! Reconnect
  1079. // T is element 0 after loop
  1080. if assigned(T.FPGConn) then
  1081. PQreset(T.FPGConn)
  1082. else
  1083. T.FPGConn := PQconnectdb(pchar(FConnectString));
  1084. CheckConnectionStatus(T.FPGConn);
  1085. if CharSet <> '' then
  1086. PQsetClientEncoding(T.FPGConn, pchar(CharSet));
  1087. result:=T.FPGConn;
  1088. end;
  1089. function TPQConnection.Fetch(cursor : TSQLCursor) : boolean;
  1090. begin
  1091. with cursor as TPQCursor do
  1092. begin
  1093. inc(CurTuple);
  1094. Result := (PQntuples(res)>CurTuple);
  1095. end;
  1096. end;
  1097. function TPQConnection.LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  1098. const NBASE=10000;
  1099. DAYS_PER_MONTH=30;
  1100. type TNumericRecord = record
  1101. Digits : SmallInt;
  1102. Weight : SmallInt;
  1103. Sign : SmallInt;
  1104. Scale : Smallint;
  1105. end;
  1106. TIntervalRec = packed record
  1107. time : int64;
  1108. day : longint;
  1109. month : longint;
  1110. end;
  1111. TMacAddrRec = packed record
  1112. a, b, c, d, e, f: byte;
  1113. end;
  1114. TInetRec = packed record
  1115. family : byte;
  1116. bits : byte;
  1117. is_cidr: byte;
  1118. nb : byte;
  1119. ipaddr : array[1..16] of byte;
  1120. end;
  1121. var
  1122. x,i : integer;
  1123. s : string;
  1124. li : Longint;
  1125. CurrBuff : pchar;
  1126. dbl : pdouble;
  1127. cur : currency;
  1128. NumericRecord : ^TNumericRecord;
  1129. guid : TGUID;
  1130. bcd : TBCD;
  1131. macaddr : ^TMacAddrRec;
  1132. inet : ^TInetRec;
  1133. begin
  1134. Createblob := False;
  1135. with cursor as TPQCursor do
  1136. begin
  1137. x := GetFieldBinding(FieldDef)^.Index;
  1138. // Joost, 5 jan 2006: I disabled the following, since it's useful for
  1139. // debugging, but it also slows things down. In principle things can only go
  1140. // wrong when FieldDefs is changed while the dataset is opened. A user just
  1141. // shoudn't do that. ;) (The same is done in IBConnection)
  1142. //if PQfname(Res, x) <> FieldDef.Name then
  1143. // DatabaseErrorFmt(SFieldNotFound,[FieldDef.Name],self);
  1144. if pqgetisnull(res,CurTuple,x)=1 then
  1145. result := false
  1146. else
  1147. begin
  1148. CurrBuff := pqgetvalue(res,CurTuple,x);
  1149. result := true;
  1150. case FieldDef.DataType of
  1151. ftInteger, ftSmallint, ftLargeInt :
  1152. case PQfsize(res, x) of // postgres returns big-endian numbers
  1153. sizeof(int64) : pint64(buffer)^ := BEtoN(pint64(CurrBuff)^); // INT8
  1154. sizeof(integer) : pinteger(buffer)^ := BEtoN(pinteger(CurrBuff)^); // INT4
  1155. sizeof(smallint) : psmallint(buffer)^ := BEtoN(psmallint(CurrBuff)^); // INT2
  1156. end; {case}
  1157. ftFloat :
  1158. case PQfsize(res, x) of // postgres returns big-endian numbers
  1159. sizeof(int64) : // FLOAT8
  1160. pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  1161. sizeof(integer) : // FLOAT4
  1162. begin
  1163. li := BEtoN(pinteger(CurrBuff)^);
  1164. pdouble(buffer)^ := psingle(@li)^
  1165. end;
  1166. end; {case}
  1167. ftString, ftFixedChar :
  1168. begin
  1169. case PQftype(res, x) of
  1170. Oid_MacAddr:
  1171. begin
  1172. macaddr := Pointer(CurrBuff);
  1173. li := FormatBuf(Buffer^, FieldDef.Size, '%.2x:%.2x:%.2x:%.2x:%.2x:%.2x', 29,
  1174. [macaddr^.a,macaddr^.b,macaddr^.c,macaddr^.d,macaddr^.e,macaddr^.f]);
  1175. end;
  1176. Oid_Inet:
  1177. begin
  1178. inet := Pointer(CurrBuff);
  1179. if inet^.nb = 4 then
  1180. li := FormatBuf(Buffer^, FieldDef.Size, '%d.%d.%d.%d', 11,
  1181. [inet^.ipaddr[1],inet^.ipaddr[2],inet^.ipaddr[3],inet^.ipaddr[4]])
  1182. else if inet^.nb = 16 then
  1183. li := FormatBuf(Buffer^, FieldDef.Size, '%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x', 55,
  1184. [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]])
  1185. else
  1186. li := 0;
  1187. end
  1188. else
  1189. begin
  1190. li := pqgetlength(res,curtuple,x);
  1191. if li > FieldDef.Size then li := FieldDef.Size;
  1192. Move(CurrBuff^, Buffer^, li);
  1193. end;
  1194. end;
  1195. pchar(Buffer + li)^ := #0;
  1196. end;
  1197. ftBlob, ftMemo :
  1198. CreateBlob := True;
  1199. ftDate :
  1200. begin
  1201. dbl := pointer(buffer);
  1202. dbl^ := BEtoN(plongint(CurrBuff)^) + 36526;
  1203. end;
  1204. ftDateTime, ftTime :
  1205. begin
  1206. dbl := pointer(buffer);
  1207. if FIntegerDateTimes then
  1208. dbl^ := BEtoN(pint64(CurrBuff)^) / 1000000
  1209. else
  1210. pint64(dbl)^ := BEtoN(pint64(CurrBuff)^);
  1211. case PQftype(res, x) of
  1212. Oid_Timestamp, Oid_TimestampTZ:
  1213. dbl^ := dbl^ + 3.1558464E+009; // postgres counts seconds elapsed since 1-1-2000
  1214. Oid_Interval:
  1215. dbl^ := dbl^ + BEtoN(plongint(CurrBuff+ 8)^) * SecsPerDay
  1216. + BEtoN(plongint(CurrBuff+12)^) * SecsPerDay * DAYS_PER_MONTH;
  1217. end;
  1218. dbl^ := dbl^ / SecsPerDay;
  1219. // Now convert the mathematically-correct datetime to the
  1220. // illogical windows/delphi/fpc TDateTime:
  1221. if (dbl^ <= 0) and (frac(dbl^) < 0) then
  1222. dbl^ := trunc(dbl^)-2-frac(dbl^);
  1223. end;
  1224. ftBCD, ftFmtBCD:
  1225. begin
  1226. NumericRecord := pointer(CurrBuff);
  1227. NumericRecord^.Digits := BEtoN(NumericRecord^.Digits);
  1228. NumericRecord^.Weight := BEtoN(NumericRecord^.Weight);
  1229. NumericRecord^.Sign := BEtoN(NumericRecord^.Sign);
  1230. NumericRecord^.Scale := BEtoN(NumericRecord^.Scale);
  1231. inc(pointer(currbuff),sizeof(TNumericRecord));
  1232. if (NumericRecord^.Digits = 0) and (NumericRecord^.Scale = 0) then // = NaN, which is not supported by Currency-type, so we return NULL
  1233. result := false
  1234. else if FieldDef.DataType = ftBCD then
  1235. begin
  1236. cur := 0;
  1237. for i := 0 to NumericRecord^.Digits-1 do
  1238. begin
  1239. cur := cur + beton(pword(CurrBuff)^) * intpower(NBASE, NumericRecord^.weight-i);
  1240. inc(pointer(CurrBuff),2);
  1241. end;
  1242. if NumericRecord^.Sign <> 0 then cur := -cur;
  1243. Move(Cur, Buffer^, sizeof(currency));
  1244. end
  1245. else //ftFmtBCD
  1246. begin
  1247. bcd := 0;
  1248. for i := 0 to NumericRecord^.Digits-1 do
  1249. begin
  1250. BCDAdd(bcd, beton(pword(CurrBuff)^) * intpower(NBASE, NumericRecord^.weight-i), bcd);
  1251. inc(pointer(CurrBuff),2);
  1252. end;
  1253. if NumericRecord^.Sign <> 0 then BCDNegate(bcd);
  1254. Move(bcd, Buffer^, sizeof(bcd));
  1255. end;
  1256. end;
  1257. ftCurrency :
  1258. begin
  1259. dbl := pointer(buffer);
  1260. dbl^ := BEtoN(PInt64(CurrBuff)^) / 100;
  1261. end;
  1262. ftBoolean:
  1263. pchar(buffer)[0] := CurrBuff[0];
  1264. ftGuid:
  1265. begin
  1266. Move(CurrBuff^, guid, sizeof(guid));
  1267. guid.D1:=BEtoN(guid.D1);
  1268. guid.D2:=BEtoN(guid.D2);
  1269. guid.D3:=BEtoN(guid.D3);
  1270. s:=GUIDToString(guid);
  1271. StrPLCopy(PChar(Buffer), s, FieldDef.Size);
  1272. end
  1273. else
  1274. result := false;
  1275. end;
  1276. end;
  1277. end;
  1278. end;
  1279. procedure TPQConnection.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  1280. var qry : TSQLQuery;
  1281. relname : string;
  1282. begin
  1283. if not assigned(Transaction) then
  1284. DatabaseError(SErrConnTransactionnSet);
  1285. if (length(TableName)>2) and (TableName[1]='"') and (TableName[length(TableName)]='"') then
  1286. relname := QuotedStr(AnsiDequotedStr(TableName, '"'))
  1287. else
  1288. relname := 'lower(' + QuotedStr(TableName) + ')'; // unquoted names are stored lower case in PostgreSQL which is incompatible with the SQL standard
  1289. qry := tsqlquery.Create(nil);
  1290. qry.transaction := Transaction;
  1291. qry.database := Self;
  1292. with qry do
  1293. begin
  1294. ReadOnly := True;
  1295. sql.clear;
  1296. sql.add('select '+
  1297. 'ic.relname as indexname, '+
  1298. 'tc.relname as tablename, '+
  1299. 'ia.attname, '+
  1300. 'i.indisprimary, '+
  1301. 'i.indisunique '+
  1302. 'from '+
  1303. 'pg_attribute ta, '+
  1304. 'pg_attribute ia, '+
  1305. 'pg_class tc, '+
  1306. 'pg_class ic, '+
  1307. 'pg_index i '+
  1308. 'where '+
  1309. '(i.indrelid = tc.oid) and '+
  1310. '(ta.attrelid = tc.oid) and '+
  1311. '(ia.attrelid = i.indexrelid) and '+
  1312. '(ic.oid = i.indexrelid) and '+
  1313. '(ta.attnum = i.indkey[ia.attnum-1]) and '+
  1314. '(tc.relname = ' + relname + ') '+
  1315. 'order by '+
  1316. 'ic.relname;');
  1317. open;
  1318. end;
  1319. while not qry.eof do with IndexDefs.AddIndexDef do
  1320. begin
  1321. Name := trim(qry.fields[0].asstring);
  1322. Fields := trim(qry.Fields[2].asstring);
  1323. If qry.fields[3].asboolean then options := options + [ixPrimary];
  1324. If qry.fields[4].asboolean then options := options + [ixUnique];
  1325. qry.next;
  1326. while (name = qry.fields[0].asstring) and (not qry.eof) do
  1327. begin
  1328. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  1329. qry.next;
  1330. end;
  1331. end;
  1332. qry.close;
  1333. qry.free;
  1334. end;
  1335. function TPQConnection.GetSchemaInfoSQL(SchemaType: TSchemaType;
  1336. SchemaObjectName, SchemaPattern: string): string;
  1337. var s : string;
  1338. begin
  1339. // select * from information_schema.tables with
  1340. // where table_schema [not] in ('pg_catalog','information_schema') may be better.
  1341. // But the following should work:
  1342. case SchemaType of
  1343. stTables : s := 'select '+
  1344. 'relfilenode as recno, '+
  1345. 'current_database() as catalog_name, '+
  1346. 'nspname as schema_name, '+
  1347. 'relname as table_name, '+
  1348. '0 as table_type '+
  1349. 'from pg_class c '+
  1350. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1351. 'where (relkind=''r'') and not (nspname in (''pg_catalog'',''information_schema''))' +
  1352. 'order by relname';
  1353. stSysTables : s := 'select '+
  1354. 'relfilenode as recno, '+
  1355. 'current_database() as catalog_name, '+
  1356. 'nspname as schema_name, '+
  1357. 'relname as table_name, '+
  1358. '0 as table_type '+
  1359. 'from pg_class c '+
  1360. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1361. 'where (relkind=''r'') and nspname in ((''pg_catalog'',''information_schema'')) ' + // only system tables
  1362. 'order by relname';
  1363. stColumns : s := 'select '+
  1364. 'a.attnum as recno, '+
  1365. 'current_database() as catalog_name, '+
  1366. 'nspname as schema_name, '+
  1367. 'c.relname as table_name, '+
  1368. 'a.attname as column_name, '+
  1369. 'a.attnum as column_position, '+
  1370. '0 as column_type, '+
  1371. 'a.atttypid as column_datatype, '+
  1372. 't.typname as column_typename, '+
  1373. '0 as column_subtype, '+
  1374. '0 as column_precision, '+
  1375. '0 as column_scale, '+
  1376. 'a.atttypmod as column_length, '+
  1377. 'not a.attnotnull as column_nullable '+
  1378. 'from pg_class c '+
  1379. 'join pg_attribute a on c.oid=a.attrelid '+
  1380. 'join pg_type t on t.oid=a.atttypid '+
  1381. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1382. // This can lead to problems when case-sensitive tablenames are used.
  1383. 'where (a.attnum>0) and (not a.attisdropped) and (upper(c.relname)=''' + Uppercase(SchemaObjectName) + ''') '+
  1384. 'order by a.attname';
  1385. else
  1386. s := inherited;
  1387. end; {case}
  1388. result := s;
  1389. end;
  1390. function TPQConnection.GetNextValueSQL(const SequenceName: string; IncrementBy: Integer): string;
  1391. begin
  1392. Result := Format('SELECT nextval(''%s'')', [SequenceName]);
  1393. end;
  1394. procedure TPQConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  1395. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  1396. var
  1397. x : integer;
  1398. li : Longint;
  1399. begin
  1400. with cursor as TPQCursor do
  1401. begin
  1402. x := FieldBinding[FieldDef.FieldNo-1].Index;
  1403. li := pqgetlength(res,curtuple,x);
  1404. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer,li);
  1405. Move(pqgetvalue(res,CurTuple,x)^, ABlobBuf^.BlobBuffer^.Buffer^, li);
  1406. ABlobBuf^.BlobBuffer^.Size := li;
  1407. end;
  1408. end;
  1409. function TPQConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  1410. begin
  1411. if assigned(cursor) and assigned((cursor as TPQCursor).res) then
  1412. Result := StrToIntDef(PQcmdTuples((cursor as TPQCursor).res),-1)
  1413. else
  1414. Result := -1;
  1415. end;
  1416. function TPQConnection.GetConnectionInfo(InfoType: TConnInfoType): string;
  1417. begin
  1418. Result:='';
  1419. try
  1420. {$IFDEF LinkDynamically}
  1421. InitialisePostgres3;
  1422. {$ENDIF}
  1423. case InfoType of
  1424. citServerType:
  1425. Result:=TPQConnectionDef.TypeName;
  1426. citServerVersion,
  1427. citServerVersionString:
  1428. if Connected then
  1429. Result:=format('%6.6d', [PQserverVersion(GetHandle)]);
  1430. citClientName:
  1431. Result:=TPQConnectionDef.LoadedLibraryName;
  1432. else
  1433. Result:=inherited GetConnectionInfo(InfoType);
  1434. end;
  1435. finally
  1436. {$IFDEF LinkDynamically}
  1437. ReleasePostgres3;
  1438. {$ENDIF}
  1439. end;
  1440. end;
  1441. { TPQConnectionDef }
  1442. class function TPQConnectionDef.TypeName: String;
  1443. begin
  1444. Result:='PostgreSQL';
  1445. end;
  1446. class function TPQConnectionDef.ConnectionClass: TSQLConnectionClass;
  1447. begin
  1448. Result:=TPQConnection;
  1449. end;
  1450. class function TPQConnectionDef.Description: String;
  1451. begin
  1452. Result:='Connect to a PostgreSQL database directly via the client library';
  1453. end;
  1454. class function TPQConnectionDef.DefaultLibraryName: String;
  1455. begin
  1456. {$IfDef LinkDynamically}
  1457. Result:=pqlib;
  1458. {$else}
  1459. Result:='';
  1460. {$endif}
  1461. end;
  1462. class function TPQConnectionDef.LoadFunction: TLibraryLoadFunction;
  1463. begin
  1464. {$IfDef LinkDynamically}
  1465. Result:=@InitialisePostgres3;
  1466. {$else}
  1467. Result:=Nil;
  1468. {$endif}
  1469. end;
  1470. class function TPQConnectionDef.UnLoadFunction: TLibraryUnLoadFunction;
  1471. begin
  1472. {$IfDef LinkDynamically}
  1473. Result:=@ReleasePostgres3;
  1474. {$else}
  1475. Result:=Nil;
  1476. {$endif}
  1477. end;
  1478. class function TPQConnectionDef.LoadedLibraryName: string;
  1479. begin
  1480. {$IfDef LinkDynamically}
  1481. Result:=Postgres3LoadedLibrary;
  1482. {$else}
  1483. Result:='';
  1484. {$endif}
  1485. end;
  1486. initialization
  1487. RegisterConnection(TPQConnectionDef);
  1488. finalization
  1489. UnRegisterConnection(TPQConnectionDef);
  1490. end.