pqconnection.pp 49 KB

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