pqconnection.pp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. '''' + DatabaseName + ''' as catalog_name, '+
  886. 'nspname as schema_name, '+
  887. 'relname as table_name, '+
  888. '0 as table_type '+
  889. 'from '+
  890. 'pg_class c left join pg_namespace n on c.relnamespace=n.oid '+
  891. 'where '+
  892. 'relkind=''r''' +
  893. 'order by relname';
  894. stSysTables : s := 'select '+
  895. 'relfilenode as recno, '+
  896. '''' + DatabaseName + ''' as catalog_name, '+
  897. 'nspname as schema_name, '+
  898. 'relname as table_name, '+
  899. '0 as table_type '+
  900. 'from '+
  901. 'pg_class c left join pg_namespace n on c.relnamespace=n.oid '+
  902. 'where '+
  903. 'relkind=''r'' and nspname=''pg_catalog'' ' + // only system tables
  904. 'order by relname';
  905. stColumns : s := 'select '+
  906. 'a.attnum as recno, '+
  907. ''''' as catalog_name, '+
  908. ''''' as schema_name, '+
  909. 'c.relname as table_name, '+
  910. 'a.attname as column_name, '+
  911. '0 as column_position, '+
  912. '0 as column_type, '+
  913. '0 as column_datatype, '+
  914. ''''' as column_typename, '+
  915. '0 as column_subtype, '+
  916. '0 as column_precision, '+
  917. '0 as column_scale, '+
  918. 'a.atttypmod as column_length, '+
  919. 'not a.attnotnull as column_nullable '+
  920. 'from '+
  921. ' pg_class c, pg_attribute a '+
  922. 'WHERE '+
  923. // This can lead to problems when case-sensitive tablenames are used.
  924. '(c.oid=a.attrelid) and (a.attnum>0) and (not a.attisdropped) and (upper(c.relname)=''' + Uppercase(SchemaObjectName) + ''') ' +
  925. 'order by a.attname';
  926. else
  927. DatabaseError(SMetadataUnavailable)
  928. end; {case}
  929. result := s;
  930. end;
  931. procedure TPQConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  932. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  933. var
  934. x : integer;
  935. li : Longint;
  936. begin
  937. with cursor as TPQCursor do
  938. begin
  939. x := FieldBinding[FieldDef.FieldNo-1];
  940. li := pqgetlength(res,curtuple,x);
  941. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer,li);
  942. Move(pqgetvalue(res,CurTuple,x)^, ABlobBuf^.BlobBuffer^.Buffer^, li);
  943. ABlobBuf^.BlobBuffer^.Size := li;
  944. end;
  945. end;
  946. function TPQConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  947. begin
  948. if assigned(cursor) and assigned((cursor as TPQCursor).res) then
  949. Result := StrToIntDef(PQcmdTuples((cursor as TPQCursor).res),-1)
  950. else
  951. Result := -1;
  952. end;
  953. function TPQConnection.GetConnectionInfo(InfoType: TConnInfoType): string;
  954. begin
  955. Result:='';
  956. try
  957. {$IFDEF LinkDynamically}
  958. InitialisePostgres3;
  959. {$ENDIF}
  960. case InfoType of
  961. citServerType:
  962. Result:=TPQConnectionDef.TypeName;
  963. citServerVersion,
  964. citServerVersionString:
  965. if Connected then
  966. Result:=format('%6.6d', [PQserverVersion(FSQLDatabaseHandle)]);
  967. citClientName:
  968. Result:=TPQConnectionDef.LoadedLibraryName;
  969. else
  970. Result:=inherited GetConnectionInfo(InfoType);
  971. end;
  972. finally
  973. {$IFDEF LinkDynamically}
  974. ReleasePostgres3;
  975. {$ENDIF}
  976. end;
  977. end;
  978. { TPQConnectionDef }
  979. class function TPQConnectionDef.TypeName: String;
  980. begin
  981. Result:='PostgreSQL';
  982. end;
  983. class function TPQConnectionDef.ConnectionClass: TSQLConnectionClass;
  984. begin
  985. Result:=TPQConnection;
  986. end;
  987. class function TPQConnectionDef.Description: String;
  988. begin
  989. Result:='Connect to a PostgreSQL database directly via the client library';
  990. end;
  991. class function TPQConnectionDef.DefaultLibraryName: String;
  992. begin
  993. {$IfDef LinkDynamically}
  994. Result:=pqlib;
  995. {$else}
  996. Result:='';
  997. {$endif}
  998. end;
  999. class function TPQConnectionDef.LoadFunction: TLibraryLoadFunction;
  1000. begin
  1001. {$IfDef LinkDynamically}
  1002. Result:=@InitialisePostgres3;
  1003. {$else}
  1004. Result:=Nil;
  1005. {$endif}
  1006. end;
  1007. class function TPQConnectionDef.UnLoadFunction: TLibraryUnLoadFunction;
  1008. begin
  1009. {$IfDef LinkDynamically}
  1010. Result:=@ReleasePostgres3;
  1011. {$else}
  1012. Result:=Nil;
  1013. {$endif}
  1014. end;
  1015. class function TPQConnectionDef.LoadedLibraryName: string;
  1016. begin
  1017. {$IfDef LinkDynamically}
  1018. Result:=Postgres3LoadedLibrary;
  1019. {$else}
  1020. Result:='';
  1021. {$endif}
  1022. end;
  1023. initialization
  1024. RegisterConnection(TPQConnectionDef);
  1025. finalization
  1026. UnRegisterConnection(TPQConnectionDef);
  1027. end.