pqconnection.pp 48 KB

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