pqconnection.pp 36 KB

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