pqconnection.pp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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];
  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. );
  761. var
  762. s,ts : string;
  763. i : integer;
  764. P : TParam;
  765. PQ : TSQLDBParam;
  766. begin
  767. with (cursor as TPQCursor) do
  768. begin
  769. FPrepared := False;
  770. FDirect := False;
  771. // Prior to v8 there is no support for cursors and parameters.
  772. // So that's not supported.
  773. if FStatementType in [stInsert,stUpdate,stDelete, stSelect] then
  774. begin
  775. StmtName := 'prepst'+inttostr(FCursorCount);
  776. InterlockedIncrement(FCursorCount);
  777. TPQTrans(aTransaction.Handle).RegisterCursor(Cursor as TPQCursor);
  778. // Only available for pq 8.0, so don't use it...
  779. // Res := pqprepare(tr,'prepst'+name+nr,pchar(buf),params.Count,pchar(''));
  780. s := 'prepare '+StmtName+' ';
  781. if Assigned(AParams) and (AParams.Count > 0) then
  782. begin
  783. s := s + '(';
  784. for i := 0 to AParams.Count-1 do
  785. begin
  786. P:=AParams[i];
  787. If (P is TSQLDBParam) then
  788. PQ:=TSQLDBParam(P)
  789. else
  790. PQ:=Nil;
  791. TS:=TypeStrings[P.DataType];
  792. if (TS<>'Unknown') then
  793. begin
  794. If Assigned(PQ)
  795. and Assigned(PQ.SQLDBData)
  796. and (PFieldBinding(PQ.SQLDBData)^.ExtendedFieldType=eftEnum) then
  797. ts:='unknown';
  798. s := s + ts + ','
  799. end
  800. else
  801. begin
  802. if AParams[i].DataType = ftUnknown then
  803. begin
  804. if AParams[i].IsNull then
  805. s:=s+' unknown ,'
  806. else
  807. DatabaseErrorFmt(SUnknownParamFieldType,[AParams[i].Name],self)
  808. end
  809. else
  810. DatabaseErrorFmt(SUnsupportedParameter,[Fieldtypenames[AParams[i].DataType]],self);
  811. end;
  812. end;
  813. s[length(s)] := ')';
  814. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psPostgreSQL);
  815. end;
  816. s := s + ' as ' + buf;
  817. if LogEvent(detActualSQL) then
  818. Log(detActualSQL,S);
  819. res := PQexec(tr.PGConn,pchar(s));
  820. CheckResultError(res,nil,SErrPrepareFailed);
  821. // if statement is INSERT, UPDATE, DELETE with RETURNING clause, then
  822. // override the statement type derrived by parsing the query.
  823. if (FStatementType in [stInsert,stUpdate,stDelete]) and (pos('RETURNING', upcase(s)) > 0) then
  824. begin
  825. PQclear(res);
  826. res := PQdescribePrepared(tr.PGConn,pchar(StmtName));
  827. if (PQresultStatus(res) = PGRES_COMMAND_OK) and (PQnfields(res) > 0) then
  828. FStatementType := stSelect;
  829. end;
  830. FPrepared := True;
  831. end
  832. else
  833. begin
  834. if Assigned(AParams) then
  835. Statement := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psPostgreSQL)
  836. else
  837. Statement:=Buf;
  838. FDirect:=True;
  839. end;
  840. end;
  841. end;
  842. procedure TPQConnection.UnPrepareStatement(cursor : TSQLCursor);
  843. begin
  844. with (cursor as TPQCursor) do
  845. begin
  846. PQclear(res);
  847. res:=nil;
  848. if FPrepared then
  849. begin
  850. if assigned(tr) and (PQtransactionStatus(tr.PGConn) <> PQTRANS_INERROR) then
  851. begin
  852. res := PQexec(tr.PGConn,pchar('deallocate '+StmtName));
  853. CheckResultError(res,nil,SErrUnPrepareFailed);
  854. PQclear(res);
  855. res:=nil;
  856. end;
  857. FPrepared := False;
  858. end;
  859. end;
  860. end;
  861. procedure TPQConnection.Execute(cursor: TSQLCursor;atransaction:tSQLtransaction;AParams : TParams);
  862. var ar : array of PAnsiChar;
  863. handled : boolean;
  864. l,i : integer;
  865. s : RawByteString;
  866. bd : TBlobData;
  867. lengths,formats : array of integer;
  868. ParamNames,
  869. ParamValues : array of string;
  870. cash: int64;
  871. function FormatTimeInterval(Time: TDateTime): string; // supports Time >= '24:00:00'
  872. var hour, minute, second, millisecond: word;
  873. begin
  874. DecodeTime(Time, hour, minute, second, millisecond);
  875. Result := Format('%.2d:%.2d:%.2d.%.3d',[Trunc(Time)*24+hour,minute,second,millisecond]);
  876. end;
  877. begin
  878. with cursor as TPQCursor do
  879. begin
  880. CurTuple:=-1;
  881. PQclear(res);
  882. if FStatementType in [stInsert,stUpdate,stDelete,stSelect] then
  883. begin
  884. if LogEvent(detParamValue) then
  885. LogParams(AParams);
  886. if Assigned(AParams) and (AParams.Count > 0) then
  887. begin
  888. l:=AParams.Count;
  889. setlength(ar,l);
  890. setlength(lengths,l);
  891. setlength(formats,l);
  892. for i := 0 to AParams.Count -1 do if not AParams[i].IsNull then
  893. begin
  894. handled:=False;
  895. case AParams[i].DataType of
  896. ftDateTime:
  897. s := FormatDateTime('yyyy"-"mm"-"dd hh":"nn":"ss.zzz', AParams[i].AsDateTime);
  898. ftDate:
  899. s := FormatDateTime('yyyy"-"mm"-"dd', AParams[i].AsDateTime);
  900. ftTime:
  901. s := FormatTimeInterval(AParams[i].AsDateTime);
  902. ftFloat:
  903. Str(AParams[i].AsFloat, s);
  904. ftBCD:
  905. Str(AParams[i].AsCurrency, s);
  906. ftCurrency:
  907. begin
  908. cash:=NtoBE(round(AParams[i].AsCurrency*100));
  909. setlength(s, sizeof(cash));
  910. Move(cash, s[1], sizeof(cash));
  911. end;
  912. ftFmtBCD:
  913. s := BCDToStr(AParams[i].AsFMTBCD, FSQLFormatSettings);
  914. ftBlob, ftGraphic:
  915. begin
  916. Handled:=true;
  917. bd:= AParams[i].AsBlob;
  918. l:=length(BD);
  919. if l>0 then
  920. begin
  921. GetMem(ar[i],l+1);
  922. ar[i][l]:=#0;
  923. Move(BD[0],ar[i]^, L);
  924. lengths[i]:=l;
  925. end;
  926. end
  927. else
  928. s := GetAsString(AParams[i]);
  929. end; {case}
  930. if not handled then
  931. begin
  932. l:=length(s);
  933. GetMem(ar[i],l+1);
  934. StrMove(PAnsiChar(ar[i]), PAnsiChar(s), L+1);
  935. lengths[i]:=L;
  936. end;
  937. if (AParams[i].DataType in [ftBlob,ftMemo,ftGraphic,ftCurrency]) then
  938. Formats[i]:=1
  939. else
  940. Formats[i]:=0;
  941. end
  942. else
  943. FreeAndNil(ar[i]);
  944. res := PQexecPrepared(tr.PGConn,pchar(StmtName),AParams.Count,@Ar[0],@Lengths[0],@Formats[0],1);
  945. for i := 0 to AParams.Count -1 do
  946. FreeMem(ar[i]);
  947. end
  948. else
  949. res := PQexecPrepared(tr.PGConn,pchar(StmtName),0,nil,nil,nil,1);
  950. end
  951. else
  952. begin
  953. // RegisterCursor sets tr
  954. TPQTrans(aTransaction.Handle).RegisterCursor(Cursor as TPQCursor);
  955. if Assigned(AParams) and (AParams.Count > 0) then
  956. begin
  957. setlength(ParamNames,AParams.Count);
  958. setlength(ParamValues,AParams.Count);
  959. for i := 0 to AParams.Count -1 do
  960. begin
  961. ParamNames[AParams.Count-i-1] := '$'+inttostr(AParams[i].index+1);
  962. ParamValues[AParams.Count-i-1] := GetAsSQLText(AParams[i]);
  963. end;
  964. s := stringsreplace(Statement,ParamNames,ParamValues,[rfReplaceAll]);
  965. end
  966. else
  967. s := Statement;
  968. res := PQexec(tr.PGConn,pchar(s));
  969. if (PQresultStatus(res) in [PGRES_COMMAND_OK]) then
  970. begin
  971. PQclear(res);
  972. res:=nil;
  973. end;
  974. end;
  975. if assigned(res) and not (PQresultStatus(res) in [PGRES_COMMAND_OK,PGRES_TUPLES_OK]) then
  976. begin
  977. // Don't perform the rollback, only make it possible to do a rollback.
  978. // The other databases also don't do this.
  979. //atransaction.Rollback;
  980. CheckResultError(res,nil,SErrExecuteFailed);
  981. end;
  982. FSelectable := assigned(res) and (PQresultStatus(res)=PGRES_TUPLES_OK);
  983. end;
  984. end;
  985. procedure TPQConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs);
  986. var
  987. i : integer;
  988. asize : integer;
  989. aoid : oid;
  990. fieldtype : tfieldtype;
  991. nFields : integer;
  992. b : Boolean;
  993. Q : TPQCursor;
  994. FD : TSQLDBFieldDef;
  995. FB : PFieldBinding;
  996. begin
  997. B:=False;
  998. Q:=cursor as TPQCursor;
  999. with Q do
  1000. begin
  1001. nFields := PQnfields(Res);
  1002. setlength(FieldBinding,nFields);
  1003. for i := 0 to nFields-1 do
  1004. begin
  1005. fieldtype := TranslateFldType(Res, i, asize, aoid );
  1006. FD := AddFieldDef(FieldDefs, i+1, PQfname(Res, i), fieldtype, asize, -1, False, False, False) as TSQLDBFieldDef;
  1007. With FD do
  1008. begin
  1009. SQLDBData:=@FieldBinding[i];
  1010. FieldBinding[i].Index:=i;
  1011. FieldBinding[i].FieldDef:=FD;
  1012. FieldBinding[i].TypeOID:=aOID;
  1013. B:=B or (aOID>0);
  1014. end;
  1015. end;
  1016. CurTuple := -1;
  1017. end;
  1018. if B then
  1019. begin
  1020. // get all information in 1 go.
  1021. GetExtendedFieldInfo(Q,Q.FieldBinding);
  1022. For I:=0 to Length(Q.FieldBinding)-1 do
  1023. begin
  1024. FB:[email protected][i];
  1025. if (FB^.TypeOID>0) then
  1026. begin
  1027. FD:=FB^.FieldDef;
  1028. Case FB^.ExtendedFieldType of
  1029. eftEnum :
  1030. begin
  1031. FD.DataType:=ftString;
  1032. FD.Size:=64;
  1033. //FD.Attributes:=FD.Attributes+[faReadonly];
  1034. end;
  1035. eftCitext:
  1036. begin
  1037. FD.DataType:=ftMemo;
  1038. end
  1039. else
  1040. if ErrorOnUnknownType then
  1041. DatabaseError('Unhandled field type :'+FB^.TypeName,Self);
  1042. end;
  1043. end;
  1044. end;
  1045. end;
  1046. end;
  1047. function TPQConnection.GetHandle: pointer;
  1048. var
  1049. i:integer;
  1050. L : TList;
  1051. T : TPQTranConnection;
  1052. begin
  1053. result:=nil;
  1054. if not Connected then
  1055. exit;
  1056. //Get any handle that is (still) connected
  1057. L:=FConnectionPool.LockList;
  1058. try
  1059. I:=L.Count-1;
  1060. While (I>=0) and (Result=Nil) do
  1061. begin
  1062. T:=TPQTranConnection(L[i]);
  1063. if assigned(T.FPGConn) and (PQstatus(T.FPGConn)<>CONNECTION_BAD) then
  1064. Result:=T.FPGConn;
  1065. Dec(I);
  1066. end;
  1067. finally
  1068. FConnectionPool.UnLockList;
  1069. end;
  1070. if Result<>Nil then
  1071. exit;
  1072. //Nothing connected!! Reconnect
  1073. // T is element 0 after loop
  1074. if assigned(T.FPGConn) then
  1075. PQreset(T.FPGConn)
  1076. else
  1077. T.FPGConn := PQconnectdb(pchar(FConnectString));
  1078. CheckConnectionStatus(T.FPGConn);
  1079. if CharSet <> '' then
  1080. PQsetClientEncoding(T.FPGConn, pchar(CharSet));
  1081. result:=T.FPGConn;
  1082. end;
  1083. function TPQConnection.Fetch(cursor : TSQLCursor) : boolean;
  1084. begin
  1085. with cursor as TPQCursor do
  1086. begin
  1087. inc(CurTuple);
  1088. Result := (PQntuples(res)>CurTuple);
  1089. end;
  1090. end;
  1091. function TPQConnection.LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  1092. const NBASE=10000;
  1093. DAYS_PER_MONTH=30;
  1094. type TNumericRecord = record
  1095. Digits : SmallInt;
  1096. Weight : SmallInt;
  1097. Sign : SmallInt;
  1098. Scale : Smallint;
  1099. end;
  1100. TIntervalRec = packed record
  1101. time : int64;
  1102. day : longint;
  1103. month : longint;
  1104. end;
  1105. TMacAddrRec = packed record
  1106. a, b, c, d, e, f: byte;
  1107. end;
  1108. TInetRec = packed record
  1109. family : byte;
  1110. bits : byte;
  1111. is_cidr: byte;
  1112. nb : byte;
  1113. ipaddr : array[1..16] of byte;
  1114. end;
  1115. var
  1116. x,i : integer;
  1117. s : string;
  1118. li : Longint;
  1119. CurrBuff : pchar;
  1120. dbl : pdouble;
  1121. cur : currency;
  1122. NumericRecord : ^TNumericRecord;
  1123. guid : TGUID;
  1124. bcd : TBCD;
  1125. macaddr : ^TMacAddrRec;
  1126. inet : ^TInetRec;
  1127. begin
  1128. Createblob := False;
  1129. with cursor as TPQCursor do
  1130. begin
  1131. x := GetFieldBinding(FieldDef)^.Index;
  1132. // Joost, 5 jan 2006: I disabled the following, since it's useful for
  1133. // debugging, but it also slows things down. In principle things can only go
  1134. // wrong when FieldDefs is changed while the dataset is opened. A user just
  1135. // shoudn't do that. ;) (The same is done in IBConnection)
  1136. //if PQfname(Res, x) <> FieldDef.Name then
  1137. // DatabaseErrorFmt(SFieldNotFound,[FieldDef.Name],self);
  1138. if pqgetisnull(res,CurTuple,x)=1 then
  1139. result := false
  1140. else
  1141. begin
  1142. CurrBuff := pqgetvalue(res,CurTuple,x);
  1143. result := true;
  1144. case FieldDef.DataType of
  1145. ftInteger, ftSmallint, ftLargeInt :
  1146. case PQfsize(res, x) of // postgres returns big-endian numbers
  1147. sizeof(int64) : pint64(buffer)^ := BEtoN(pint64(CurrBuff)^); // INT8
  1148. sizeof(integer) : pinteger(buffer)^ := BEtoN(pinteger(CurrBuff)^); // INT4
  1149. sizeof(smallint) : psmallint(buffer)^ := BEtoN(psmallint(CurrBuff)^); // INT2
  1150. end; {case}
  1151. ftFloat :
  1152. case PQfsize(res, x) of // postgres returns big-endian numbers
  1153. sizeof(int64) : // FLOAT8
  1154. pint64(buffer)^ := BEtoN(pint64(CurrBuff)^);
  1155. sizeof(integer) : // FLOAT4
  1156. begin
  1157. li := BEtoN(pinteger(CurrBuff)^);
  1158. pdouble(buffer)^ := psingle(@li)^
  1159. end;
  1160. end; {case}
  1161. ftString, ftFixedChar :
  1162. begin
  1163. case PQftype(res, x) of
  1164. Oid_MacAddr:
  1165. begin
  1166. macaddr := Pointer(CurrBuff);
  1167. li := FormatBuf(Buffer^, FieldDef.Size, '%.2x:%.2x:%.2x:%.2x:%.2x:%.2x', 29,
  1168. [macaddr^.a,macaddr^.b,macaddr^.c,macaddr^.d,macaddr^.e,macaddr^.f]);
  1169. end;
  1170. Oid_Inet:
  1171. begin
  1172. inet := Pointer(CurrBuff);
  1173. if inet^.nb = 4 then
  1174. li := FormatBuf(Buffer^, FieldDef.Size, '%d.%d.%d.%d', 11,
  1175. [inet^.ipaddr[1],inet^.ipaddr[2],inet^.ipaddr[3],inet^.ipaddr[4]])
  1176. else if inet^.nb = 16 then
  1177. li := FormatBuf(Buffer^, FieldDef.Size, '%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x:%x%.2x', 55,
  1178. [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]])
  1179. else
  1180. li := 0;
  1181. end
  1182. else
  1183. begin
  1184. li := pqgetlength(res,curtuple,x);
  1185. if li > FieldDef.Size then li := FieldDef.Size;
  1186. Move(CurrBuff^, Buffer^, li);
  1187. end;
  1188. end;
  1189. pchar(Buffer + li)^ := #0;
  1190. end;
  1191. ftBlob, ftMemo :
  1192. CreateBlob := True;
  1193. ftDate :
  1194. begin
  1195. dbl := pointer(buffer);
  1196. dbl^ := BEtoN(plongint(CurrBuff)^) + 36526;
  1197. end;
  1198. ftDateTime, ftTime :
  1199. begin
  1200. dbl := pointer(buffer);
  1201. if FIntegerDateTimes then
  1202. dbl^ := BEtoN(pint64(CurrBuff)^) / 1000000
  1203. else
  1204. pint64(dbl)^ := BEtoN(pint64(CurrBuff)^);
  1205. case PQftype(res, x) of
  1206. Oid_Timestamp, Oid_TimestampTZ:
  1207. dbl^ := dbl^ + 3.1558464E+009; // postgres counts seconds elapsed since 1-1-2000
  1208. Oid_Interval:
  1209. dbl^ := dbl^ + BEtoN(plongint(CurrBuff+ 8)^) * SecsPerDay
  1210. + BEtoN(plongint(CurrBuff+12)^) * SecsPerDay * DAYS_PER_MONTH;
  1211. end;
  1212. dbl^ := dbl^ / SecsPerDay;
  1213. // Now convert the mathematically-correct datetime to the
  1214. // illogical windows/delphi/fpc TDateTime:
  1215. if (dbl^ <= 0) and (frac(dbl^) < 0) then
  1216. dbl^ := trunc(dbl^)-2-frac(dbl^);
  1217. end;
  1218. ftBCD, ftFmtBCD:
  1219. begin
  1220. NumericRecord := pointer(CurrBuff);
  1221. NumericRecord^.Digits := BEtoN(NumericRecord^.Digits);
  1222. NumericRecord^.Weight := BEtoN(NumericRecord^.Weight);
  1223. NumericRecord^.Sign := BEtoN(NumericRecord^.Sign);
  1224. NumericRecord^.Scale := BEtoN(NumericRecord^.Scale);
  1225. inc(pointer(currbuff),sizeof(TNumericRecord));
  1226. if (NumericRecord^.Digits = 0) and (NumericRecord^.Scale = 0) then // = NaN, which is not supported by Currency-type, so we return NULL
  1227. result := false
  1228. else if FieldDef.DataType = ftBCD then
  1229. begin
  1230. cur := 0;
  1231. for i := 0 to NumericRecord^.Digits-1 do
  1232. begin
  1233. cur := cur + beton(pword(CurrBuff)^) * intpower(NBASE, NumericRecord^.weight-i);
  1234. inc(pointer(CurrBuff),2);
  1235. end;
  1236. if NumericRecord^.Sign <> 0 then cur := -cur;
  1237. Move(Cur, Buffer^, sizeof(currency));
  1238. end
  1239. else //ftFmtBCD
  1240. begin
  1241. bcd := 0;
  1242. for i := 0 to NumericRecord^.Digits-1 do
  1243. begin
  1244. BCDAdd(bcd, beton(pword(CurrBuff)^) * intpower(NBASE, NumericRecord^.weight-i), bcd);
  1245. inc(pointer(CurrBuff),2);
  1246. end;
  1247. if NumericRecord^.Sign <> 0 then BCDNegate(bcd);
  1248. Move(bcd, Buffer^, sizeof(bcd));
  1249. end;
  1250. end;
  1251. ftCurrency :
  1252. begin
  1253. dbl := pointer(buffer);
  1254. dbl^ := BEtoN(PInt64(CurrBuff)^) / 100;
  1255. end;
  1256. ftBoolean:
  1257. pchar(buffer)[0] := CurrBuff[0];
  1258. ftGuid:
  1259. begin
  1260. Move(CurrBuff^, guid, sizeof(guid));
  1261. guid.D1:=BEtoN(guid.D1);
  1262. guid.D2:=BEtoN(guid.D2);
  1263. guid.D3:=BEtoN(guid.D3);
  1264. s:=GUIDToString(guid);
  1265. StrPLCopy(PChar(Buffer), s, FieldDef.Size);
  1266. end
  1267. else
  1268. result := false;
  1269. end;
  1270. end;
  1271. end;
  1272. end;
  1273. procedure TPQConnection.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  1274. var qry : TSQLQuery;
  1275. relname : string;
  1276. begin
  1277. if not assigned(Transaction) then
  1278. DatabaseError(SErrConnTransactionnSet);
  1279. if (length(TableName)>2) and (TableName[1]='"') and (TableName[length(TableName)]='"') then
  1280. relname := QuotedStr(AnsiDequotedStr(TableName, '"'))
  1281. else
  1282. relname := 'lower(' + QuotedStr(TableName) + ')'; // unquoted names are stored lower case in PostgreSQL which is incompatible with the SQL standard
  1283. qry := tsqlquery.Create(nil);
  1284. qry.transaction := Transaction;
  1285. qry.database := Self;
  1286. with qry do
  1287. begin
  1288. ReadOnly := True;
  1289. sql.clear;
  1290. sql.add('select '+
  1291. 'ic.relname as indexname, '+
  1292. 'tc.relname as tablename, '+
  1293. 'ia.attname, '+
  1294. 'i.indisprimary, '+
  1295. 'i.indisunique '+
  1296. 'from '+
  1297. 'pg_attribute ta, '+
  1298. 'pg_attribute ia, '+
  1299. 'pg_class tc, '+
  1300. 'pg_class ic, '+
  1301. 'pg_index i '+
  1302. 'where '+
  1303. '(i.indrelid = tc.oid) and '+
  1304. '(ta.attrelid = tc.oid) and '+
  1305. '(ia.attrelid = i.indexrelid) and '+
  1306. '(ic.oid = i.indexrelid) and '+
  1307. '(ta.attnum = i.indkey[ia.attnum-1]) and '+
  1308. '(tc.relname = ' + relname + ') '+
  1309. 'order by '+
  1310. 'ic.relname;');
  1311. open;
  1312. end;
  1313. while not qry.eof do with IndexDefs.AddIndexDef do
  1314. begin
  1315. Name := trim(qry.fields[0].asstring);
  1316. Fields := trim(qry.Fields[2].asstring);
  1317. If qry.fields[3].asboolean then options := options + [ixPrimary];
  1318. If qry.fields[4].asboolean then options := options + [ixUnique];
  1319. qry.next;
  1320. while (name = qry.fields[0].asstring) and (not qry.eof) do
  1321. begin
  1322. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  1323. qry.next;
  1324. end;
  1325. end;
  1326. qry.close;
  1327. qry.free;
  1328. end;
  1329. function TPQConnection.GetSchemaInfoSQL(SchemaType: TSchemaType;
  1330. SchemaObjectName, SchemaPattern: string): string;
  1331. var s : string;
  1332. begin
  1333. // select * from information_schema.tables with
  1334. // where table_schema [not] in ('pg_catalog','information_schema') may be better.
  1335. // But the following should work:
  1336. case SchemaType of
  1337. stTables : s := 'select '+
  1338. 'relfilenode as recno, '+
  1339. 'current_database() as catalog_name, '+
  1340. 'nspname as schema_name, '+
  1341. 'relname as table_name, '+
  1342. '0 as table_type '+
  1343. 'from pg_class c '+
  1344. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1345. 'where (relkind=''r'') and not (nspname in (''pg_catalog'',''information_schema''))' +
  1346. 'order by relname';
  1347. stSysTables : s := 'select '+
  1348. 'relfilenode as recno, '+
  1349. 'current_database() as catalog_name, '+
  1350. 'nspname as schema_name, '+
  1351. 'relname as table_name, '+
  1352. '0 as table_type '+
  1353. 'from pg_class c '+
  1354. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1355. 'where (relkind=''r'') and nspname in ((''pg_catalog'',''information_schema'')) ' + // only system tables
  1356. 'order by relname';
  1357. stColumns : s := 'select '+
  1358. 'a.attnum as recno, '+
  1359. 'current_database() as catalog_name, '+
  1360. 'nspname as schema_name, '+
  1361. 'c.relname as table_name, '+
  1362. 'a.attname as column_name, '+
  1363. 'a.attnum as column_position, '+
  1364. '0 as column_type, '+
  1365. 'a.atttypid as column_datatype, '+
  1366. 't.typname as column_typename, '+
  1367. '0 as column_subtype, '+
  1368. '0 as column_precision, '+
  1369. '0 as column_scale, '+
  1370. 'a.atttypmod as column_length, '+
  1371. 'not a.attnotnull as column_nullable '+
  1372. 'from pg_class c '+
  1373. 'join pg_attribute a on c.oid=a.attrelid '+
  1374. 'join pg_type t on t.oid=a.atttypid '+
  1375. 'left join pg_namespace n on c.relnamespace=n.oid '+
  1376. // This can lead to problems when case-sensitive tablenames are used.
  1377. 'where (a.attnum>0) and (not a.attisdropped) and (upper(c.relname)=''' + Uppercase(SchemaObjectName) + ''') '+
  1378. 'order by a.attname';
  1379. else
  1380. s := inherited;
  1381. end; {case}
  1382. result := s;
  1383. end;
  1384. function TPQConnection.GetNextValueSQL(const SequenceName: string; IncrementBy: Integer): string;
  1385. begin
  1386. Result := Format('SELECT nextval(''%s'')', [SequenceName]);
  1387. end;
  1388. procedure TPQConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  1389. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  1390. var
  1391. x : integer;
  1392. li : Longint;
  1393. begin
  1394. with cursor as TPQCursor do
  1395. begin
  1396. x := FieldBinding[FieldDef.FieldNo-1].Index;
  1397. li := pqgetlength(res,curtuple,x);
  1398. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer,li);
  1399. Move(pqgetvalue(res,CurTuple,x)^, ABlobBuf^.BlobBuffer^.Buffer^, li);
  1400. ABlobBuf^.BlobBuffer^.Size := li;
  1401. end;
  1402. end;
  1403. function TPQConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  1404. begin
  1405. if assigned(cursor) and assigned((cursor as TPQCursor).res) then
  1406. Result := StrToIntDef(PQcmdTuples((cursor as TPQCursor).res),-1)
  1407. else
  1408. Result := -1;
  1409. end;
  1410. function TPQConnection.GetConnectionInfo(InfoType: TConnInfoType): string;
  1411. begin
  1412. Result:='';
  1413. try
  1414. {$IFDEF LinkDynamically}
  1415. InitialisePostgres3;
  1416. {$ENDIF}
  1417. case InfoType of
  1418. citServerType:
  1419. Result:=TPQConnectionDef.TypeName;
  1420. citServerVersion,
  1421. citServerVersionString:
  1422. if Connected then
  1423. Result:=format('%6.6d', [PQserverVersion(GetHandle)]);
  1424. citClientName:
  1425. Result:=TPQConnectionDef.LoadedLibraryName;
  1426. else
  1427. Result:=inherited GetConnectionInfo(InfoType);
  1428. end;
  1429. finally
  1430. {$IFDEF LinkDynamically}
  1431. ReleasePostgres3;
  1432. {$ENDIF}
  1433. end;
  1434. end;
  1435. { TPQConnectionDef }
  1436. class function TPQConnectionDef.TypeName: String;
  1437. begin
  1438. Result:='PostgreSQL';
  1439. end;
  1440. class function TPQConnectionDef.ConnectionClass: TSQLConnectionClass;
  1441. begin
  1442. Result:=TPQConnection;
  1443. end;
  1444. class function TPQConnectionDef.Description: String;
  1445. begin
  1446. Result:='Connect to a PostgreSQL database directly via the client library';
  1447. end;
  1448. class function TPQConnectionDef.DefaultLibraryName: String;
  1449. begin
  1450. {$IfDef LinkDynamically}
  1451. Result:=pqlib;
  1452. {$else}
  1453. Result:='';
  1454. {$endif}
  1455. end;
  1456. class function TPQConnectionDef.LoadFunction: TLibraryLoadFunction;
  1457. begin
  1458. {$IfDef LinkDynamically}
  1459. Result:=@InitialisePostgres3;
  1460. {$else}
  1461. Result:=Nil;
  1462. {$endif}
  1463. end;
  1464. class function TPQConnectionDef.UnLoadFunction: TLibraryUnLoadFunction;
  1465. begin
  1466. {$IfDef LinkDynamically}
  1467. Result:=@ReleasePostgres3;
  1468. {$else}
  1469. Result:=Nil;
  1470. {$endif}
  1471. end;
  1472. class function TPQConnectionDef.LoadedLibraryName: string;
  1473. begin
  1474. {$IfDef LinkDynamically}
  1475. Result:=Postgres3LoadedLibrary;
  1476. {$else}
  1477. Result:='';
  1478. {$endif}
  1479. end;
  1480. initialization
  1481. RegisterConnection(TPQConnectionDef);
  1482. finalization
  1483. UnRegisterConnection(TPQConnectionDef);
  1484. end.