ibconnection.pp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. unit IBConnection;
  2. {$mode objfpc}{$H+}
  3. {$Define LinkDynamically}
  4. interface
  5. uses
  6. Classes, SysUtils, sqldb, db, math, dbconst, bufdataset,
  7. {$IfDef LinkDynamically}
  8. ibase60dyn;
  9. {$Else}
  10. ibase60;
  11. {$EndIf}
  12. type
  13. EIBDatabaseError = class(EDatabaseError)
  14. public
  15. GDSErrorCode : Longint;
  16. end;
  17. { TIBCursor }
  18. TIBCursor = Class(TSQLCursor)
  19. protected
  20. Status : array [0..19] of ISC_STATUS;
  21. Statement : pointer;
  22. SQLDA : PXSQLDA;
  23. in_SQLDA : PXSQLDA;
  24. ParamBinding : array of integer;
  25. FieldBinding : array of integer;
  26. end;
  27. TIBTrans = Class(TSQLHandle)
  28. protected
  29. TransactionHandle : pointer;
  30. TPB : string; // Transaction parameter buffer
  31. Status : array [0..19] of ISC_STATUS;
  32. end;
  33. { TIBConnection }
  34. TIBConnection = class (TSQLConnection)
  35. private
  36. FSQLDatabaseHandle : pointer;
  37. FStatus : array [0..19] of ISC_STATUS;
  38. FDialect : integer;
  39. FBLobSegmentSize : word;
  40. procedure ConnectFB;
  41. procedure SetDBDialect;
  42. procedure AllocSQLDA(var aSQLDA : PXSQLDA;Count : integer);
  43. procedure TranslateFldType(SQLType, SQLLen, SQLScale : integer; var LensSet : boolean;
  44. var TrType : TFieldType; var TrLen : word);
  45. // conversion methods
  46. procedure GetDateTime(CurrBuff, Buffer : pointer; AType : integer);
  47. procedure SetDateTime(CurrBuff: pointer; PTime : TDateTime; AType : integer);
  48. procedure GetFloat(CurrBuff, Buffer : pointer; Field : TFieldDef);
  49. procedure SetFloat(CurrBuff: pointer; Dbl: Double; Size: integer);
  50. procedure CheckError(ProcName : string; Status : PISC_STATUS);
  51. function getMaxBlobSize(blobHandle : TIsc_Blob_Handle) : longInt;
  52. procedure SetParameters(cursor : TSQLCursor;AParams : TParams);
  53. procedure FreeSQLDABuffer(var aSQLDA : PXSQLDA);
  54. protected
  55. procedure DoInternalConnect; override;
  56. procedure DoInternalDisconnect; override;
  57. function GetHandle : pointer; override;
  58. Function AllocateCursorHandle : TSQLCursor; override;
  59. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  60. Function AllocateTransactionHandle : TSQLHandle; override;
  61. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  62. procedure UnPrepareStatement(cursor : TSQLCursor); override;
  63. procedure FreeFldBuffers(cursor : TSQLCursor); override;
  64. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); override;
  65. procedure AddFieldDefs(cursor: TSQLCursor;FieldDefs : TfieldDefs); override;
  66. function Fetch(cursor : TSQLCursor) : boolean; override;
  67. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  68. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  69. function Commit(trans : TSQLHandle) : boolean; override;
  70. function RollBack(trans : TSQLHandle) : boolean; override;
  71. function StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  72. procedure CommitRetaining(trans : TSQLHandle); override;
  73. procedure RollBackRetaining(trans : TSQLHandle); override;
  74. procedure UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string); override;
  75. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  76. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction : TSQLTransaction); override;
  77. public
  78. constructor Create(AOwner : TComponent); override;
  79. procedure CreateDB; override;
  80. procedure DropDB; override;
  81. property BlobSegmentSize : word read FBlobSegmentSize write FBlobSegmentSize;
  82. published
  83. property Dialect : integer read FDialect write FDialect;
  84. property DatabaseName;
  85. property KeepConnection;
  86. property LoginPrompt;
  87. property Params;
  88. property OnLogin;
  89. end;
  90. { TIBConnectionDef }
  91. TIBConnectionDef = Class(TConnectionDef)
  92. Class Function TypeName : String; override;
  93. Class Function ConnectionClass : TSQLConnectionClass; override;
  94. Class Function Description : String; override;
  95. end;
  96. implementation
  97. uses strutils;
  98. type
  99. TTm = packed record
  100. tm_sec : longint;
  101. tm_min : longint;
  102. tm_hour : longint;
  103. tm_mday : longint;
  104. tm_mon : longint;
  105. tm_year : longint;
  106. tm_wday : longint;
  107. tm_yday : longint;
  108. tm_isdst : longint;
  109. __tm_gmtoff : longint;
  110. __tm_zone : Pchar;
  111. end;
  112. procedure TIBConnection.CheckError(ProcName : string; Status : PISC_STATUS);
  113. var
  114. buf : array [0..1024] of char;
  115. Msg : string;
  116. E : EIBDatabaseError;
  117. begin
  118. if ((Status[0] = 1) and (Status[1] <> 0)) then
  119. begin
  120. msg := '';
  121. while isc_interprete(Buf, @Status) > 0 do
  122. Msg := Msg + LineEnding +' -' + StrPas(Buf);
  123. E := EIBDatabaseError.CreateFmt('%s : %s : %s',[self.Name,ProcName,Msg]);
  124. E.GDSErrorCode := Status[1];
  125. Raise E;
  126. end;
  127. end;
  128. constructor TIBConnection.Create(AOwner : TComponent);
  129. begin
  130. inherited;
  131. FConnOptions := FConnOptions + [sqSupportParams] + [sqEscapeRepeat];
  132. FBLobSegmentSize := 80;
  133. end;
  134. function TIBConnection.GetTransactionHandle(trans : TSQLHandle): pointer;
  135. begin
  136. Result := (trans as TIBtrans).TransactionHandle;
  137. end;
  138. function TIBConnection.Commit(trans : TSQLHandle) : boolean;
  139. begin
  140. result := false;
  141. with (trans as TIBTrans) do
  142. if isc_commit_transaction(@Status[0], @TransactionHandle) <> 0 then
  143. CheckError('Commit', Status)
  144. else result := true;
  145. end;
  146. function TIBConnection.RollBack(trans : TSQLHandle) : boolean;
  147. begin
  148. result := false;
  149. if isc_rollback_transaction(@TIBTrans(trans).Status[0], @TIBTrans(trans).TransactionHandle) <> 0 then
  150. CheckError('Rollback', TIBTrans(trans).Status)
  151. else result := true;
  152. end;
  153. function TIBConnection.StartDBTransaction(trans : TSQLHandle;AParams : String) : boolean;
  154. var
  155. DBHandle : pointer;
  156. tr : TIBTrans;
  157. i : integer;
  158. s : string;
  159. begin
  160. result := false;
  161. DBHandle := GetHandle;
  162. tr := trans as TIBtrans;
  163. with tr do
  164. begin
  165. TPB := chr(isc_tpb_version3);
  166. i := 1;
  167. s := ExtractSubStr(AParams,i,stdWordDelims);
  168. while s <> '' do
  169. begin
  170. if s='isc_tpb_write' then TPB := TPB + chr(isc_tpb_write)
  171. else if s='isc_tpb_read' then TPB := TPB + chr(isc_tpb_read)
  172. else if s='isc_tpb_consistency' then TPB := TPB + chr(isc_tpb_consistency)
  173. else if s='isc_tpb_concurrency' then TPB := TPB + chr(isc_tpb_concurrency)
  174. else if s='isc_tpb_read_committed' then TPB := TPB + chr(isc_tpb_read_committed)
  175. else if s='isc_tpb_rec_version' then TPB := TPB + chr(isc_tpb_rec_version)
  176. else if s='isc_tpb_no_rec_version' then TPB := TPB + chr(isc_tpb_no_rec_version)
  177. else if s='isc_tpb_wait' then TPB := TPB + chr(isc_tpb_wait)
  178. else if s='isc_tpb_nowait' then TPB := TPB + chr(isc_tpb_nowait)
  179. else if s='isc_tpb_shared' then TPB := TPB + chr(isc_tpb_shared)
  180. else if s='isc_tpb_protected' then TPB := TPB + chr(isc_tpb_protected)
  181. else if s='isc_tpb_exclusive' then TPB := TPB + chr(isc_tpb_exclusive)
  182. else if s='isc_tpb_lock_read' then TPB := TPB + chr(isc_tpb_lock_read)
  183. else if s='isc_tpb_lock_write' then TPB := TPB + chr(isc_tpb_lock_write)
  184. else if s='isc_tpb_verb_time' then TPB := TPB + chr(isc_tpb_verb_time)
  185. else if s='isc_tpb_commit_time' then TPB := TPB + chr(isc_tpb_commit_time)
  186. else if s='isc_tpb_ignore_limbo' then TPB := TPB + chr(isc_tpb_ignore_limbo)
  187. else if s='isc_tpb_autocommit' then TPB := TPB + chr(isc_tpb_autocommit)
  188. else if s='isc_tpb_restart_requests' then TPB := TPB + chr(isc_tpb_restart_requests)
  189. else if s='isc_tpb_no_auto_undo' then TPB := TPB + chr(isc_tpb_no_auto_undo);
  190. s := ExtractSubStr(AParams,i,stdWordDelims);
  191. end;
  192. TransactionHandle := nil;
  193. if isc_start_transaction(@Status[0], @TransactionHandle, 1,
  194. [@DBHandle, Length(TPB), @TPB[1]]) <> 0 then
  195. CheckError('StartTransaction',Status)
  196. else Result := True;
  197. end;
  198. end;
  199. procedure TIBConnection.CommitRetaining(trans : TSQLHandle);
  200. begin
  201. with trans as TIBtrans do
  202. if isc_commit_retaining(@Status[0], @TransactionHandle) <> 0 then
  203. CheckError('CommitRetaining', Status);
  204. end;
  205. procedure TIBConnection.RollBackRetaining(trans : TSQLHandle);
  206. begin
  207. with trans as TIBtrans do
  208. if isc_rollback_retaining(@Status[0], @TransactionHandle) <> 0 then
  209. CheckError('RollBackRetaining', Status);
  210. end;
  211. procedure TIBConnection.DropDB;
  212. begin
  213. CheckDisConnected;
  214. {$IfDef LinkDynamically}
  215. InitialiseIBase60;
  216. {$EndIf}
  217. ConnectFB;
  218. if isc_drop_database(@FStatus[0], @FSQLDatabaseHandle) <> 0 then
  219. CheckError('DropDB', FStatus);
  220. {$IfDef LinkDynamically}
  221. ReleaseIBase60;
  222. {$EndIf}
  223. end;
  224. procedure TIBConnection.CreateDB;
  225. var ASQLDatabaseHandle,
  226. ASQLTransactionHandle : pointer;
  227. CreateSQL : String;
  228. begin
  229. CheckDisConnected;
  230. {$IfDef LinkDynamically}
  231. InitialiseIBase60;
  232. {$EndIf}
  233. ASQLDatabaseHandle := nil;
  234. ASQLTransactionHandle := nil;
  235. CreateSQL := 'CREATE DATABASE ';
  236. if HostName <> '' then CreateSQL := CreateSQL + ''''+ HostName+':'+DatabaseName + ''''
  237. else CreateSQL := CreateSQL + '''' + DatabaseName + '''';
  238. if isc_dsql_execute_immediate(@FStatus[0],@ASQLDatabaseHandle,@ASQLTransactionHandle,length(CreateSQL),@CreateSQL[1],Dialect,nil) <> 0 then
  239. CheckError('CreateDB', FStatus);
  240. isc_detach_database(@FStatus[0], @ASQLDatabaseHandle);
  241. CheckError('CreateDB', FStatus);
  242. {$IfDef LinkDynamically}
  243. ReleaseIBase60;
  244. {$EndIf}
  245. end;
  246. procedure TIBConnection.DoInternalConnect;
  247. begin
  248. {$IfDef LinkDynamically}
  249. InitialiseIBase60;
  250. {$EndIf}
  251. inherited dointernalconnect;
  252. ConnectFB;
  253. end;
  254. procedure TIBConnection.DoInternalDisconnect;
  255. begin
  256. if not Connected then
  257. begin
  258. FSQLDatabaseHandle := nil;
  259. Exit;
  260. end;
  261. isc_detach_database(@FStatus[0], @FSQLDatabaseHandle);
  262. CheckError('Close', FStatus);
  263. {$IfDef LinkDynamically}
  264. ReleaseIBase60;
  265. {$EndIf}
  266. end;
  267. procedure TIBConnection.SetDBDialect;
  268. var
  269. x : integer;
  270. Len : integer;
  271. Buffer : array [0..1] of byte;
  272. ResBuf : array [0..39] of byte;
  273. begin
  274. Buffer[0] := isc_info_db_sql_dialect;
  275. Buffer[1] := isc_info_end;
  276. if isc_database_info(@FStatus[0], @FSQLDatabaseHandle, Length(Buffer),
  277. pchar(@Buffer[0]), SizeOf(ResBuf), pchar(@ResBuf[0])) <> 0 then
  278. CheckError('SetDBDialect', FStatus);
  279. x := 0;
  280. while x < 40 do
  281. case ResBuf[x] of
  282. isc_info_db_sql_dialect :
  283. begin
  284. Inc(x);
  285. Len := isc_vax_integer(pchar(@ResBuf[x]), 2);
  286. Inc(x, 2);
  287. FDialect := isc_vax_integer(pchar(@ResBuf[x]), Len);
  288. Inc(x, Len);
  289. end;
  290. isc_info_end : Break;
  291. end;
  292. end;
  293. procedure TIBConnection.ConnectFB;
  294. var
  295. ADatabaseName: String;
  296. DPB: string;
  297. begin
  298. DPB := chr(isc_dpb_version1);
  299. if (UserName <> '') then
  300. begin
  301. DPB := DPB + chr(isc_dpb_user_name) + chr(Length(UserName)) + UserName;
  302. if (Password <> '') then
  303. DPB := DPB + chr(isc_dpb_password) + chr(Length(Password)) + Password;
  304. end;
  305. if (Role <> '') then
  306. DPB := DPB + chr(isc_dpb_sql_role_name) + chr(Length(Role)) + Role;
  307. if Length(CharSet) > 0 then
  308. DPB := DPB + Chr(isc_dpb_lc_ctype) + Chr(Length(CharSet)) + CharSet;
  309. FSQLDatabaseHandle := nil;
  310. if HostName <> '' then ADatabaseName := HostName+':'+DatabaseName
  311. else ADatabaseName := DatabaseName;
  312. if isc_attach_database(@FStatus[0], Length(ADatabaseName), @ADatabaseName[1],
  313. @FSQLDatabaseHandle,
  314. Length(DPB), @DPB[1]) <> 0 then
  315. CheckError('DoInternalConnect', FStatus);
  316. SetDBDialect;
  317. end;
  318. procedure TIBConnection.AllocSQLDA(var aSQLDA : PXSQLDA;Count : integer);
  319. begin
  320. FreeSQLDABuffer(aSQLDA);
  321. if count > -1 then
  322. begin
  323. reAllocMem(aSQLDA, XSQLDA_Length(Count));
  324. { Zero out the memory block to avoid problems with exceptions within the
  325. constructor of this class. }
  326. FillChar(aSQLDA^, XSQLDA_Length(Count), 0);
  327. aSQLDA^.Version := sqlda_version1;
  328. aSQLDA^.SQLN := Count;
  329. end
  330. else
  331. reAllocMem(aSQLDA,0);
  332. end;
  333. procedure TIBConnection.TranslateFldType(SQLType, SQLLen, SQLScale : integer; var LensSet : boolean;
  334. var TrType : TFieldType; var TrLen : word);
  335. begin
  336. LensSet := False;
  337. if SQLScale < 0 then
  338. begin
  339. if (SQLScale >= -4) and (SQLScale <= -1) then //in [-4..-1] then
  340. begin
  341. LensSet := True;
  342. TrLen := SQLLen;
  343. TrType := ftBCD
  344. end
  345. else
  346. TrType := ftFMTBcd;
  347. end
  348. else case (SQLType and not 1) of
  349. SQL_VARYING :
  350. begin
  351. LensSet := True;
  352. TrType := ftString;
  353. TrLen := SQLLen;
  354. end;
  355. SQL_TEXT :
  356. begin
  357. LensSet := True;
  358. TrType := ftString;
  359. TrLen := SQLLen;
  360. end;
  361. SQL_TYPE_DATE :
  362. TrType := ftDate{Time};
  363. SQL_TYPE_TIME :
  364. TrType := ftDateTime;
  365. SQL_TIMESTAMP :
  366. TrType := ftDateTime;
  367. SQL_ARRAY :
  368. begin
  369. TrType := ftArray;
  370. LensSet := true;
  371. TrLen := SQLLen;
  372. end;
  373. SQL_BLOB :
  374. begin
  375. TrType := ftBlob;
  376. LensSet := True;
  377. TrLen := SQLLen;
  378. end;
  379. SQL_SHORT :
  380. TrType := ftSmallint;
  381. SQL_LONG :
  382. begin
  383. LensSet := True;
  384. TrLen := 0;
  385. TrType := ftInteger;
  386. end;
  387. SQL_INT64 :
  388. TrType := ftLargeInt;
  389. SQL_DOUBLE :
  390. begin
  391. LensSet := True;
  392. TrLen := SQLLen;
  393. TrType := ftFloat;
  394. end;
  395. SQL_FLOAT :
  396. begin
  397. LensSet := True;
  398. TrLen := SQLLen;
  399. TrType := ftFloat;
  400. end
  401. else
  402. begin
  403. LensSet := True;
  404. TrLen := 0;
  405. TrType := ftUnknown;
  406. end;
  407. end;
  408. end;
  409. Function TIBConnection.AllocateCursorHandle : TSQLCursor;
  410. var curs : TIBCursor;
  411. begin
  412. curs := TIBCursor.create;
  413. curs.sqlda := nil;
  414. curs.statement := nil;
  415. curs.FPrepared := False;
  416. AllocSQLDA(curs.SQLDA,0);
  417. result := curs;
  418. end;
  419. procedure TIBConnection.DeAllocateCursorHandle(var cursor : TSQLCursor);
  420. begin
  421. if assigned(cursor) then with cursor as TIBCursor do
  422. begin
  423. AllocSQLDA(SQLDA,-1);
  424. AllocSQLDA(in_SQLDA,-1);
  425. end;
  426. FreeAndNil(cursor);
  427. end;
  428. Function TIBConnection.AllocateTransactionHandle : TSQLHandle;
  429. begin
  430. result := TIBTrans.create;
  431. end;
  432. procedure TIBConnection.PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams);
  433. var dh : pointer;
  434. tr : pointer;
  435. x : shortint;
  436. begin
  437. with cursor as TIBcursor do
  438. begin
  439. dh := GetHandle;
  440. if isc_dsql_allocate_statement(@Status[0], @dh, @Statement) <> 0 then
  441. CheckError('PrepareStatement', Status);
  442. tr := aTransaction.Handle;
  443. if assigned(AParams) and (AParams.count > 0) then
  444. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psInterbase,paramBinding);
  445. if isc_dsql_prepare(@Status[0], @tr, @Statement, 0, @Buf[1], Dialect, nil) <> 0 then
  446. CheckError('PrepareStatement', Status);
  447. FPrepared := True;
  448. if assigned(AParams) and (AParams.count > 0) then
  449. begin
  450. AllocSQLDA(in_SQLDA,Length(ParamBinding));
  451. if isc_dsql_describe_bind(@Status[0], @Statement, 1, in_SQLDA) <> 0 then
  452. CheckError('PrepareStatement', Status);
  453. if in_SQLDA^.SQLD > in_SQLDA^.SQLN then
  454. DatabaseError(SParameterCountIncorrect,self);
  455. {$R-}
  456. for x := 0 to in_SQLDA^.SQLD - 1 do with in_SQLDA^.SQLVar[x] do
  457. begin
  458. if ((SQLType and not 1) = SQL_VARYING) then
  459. SQLData := AllocMem(in_SQLDA^.SQLVar[x].SQLLen+2)
  460. else
  461. SQLData := AllocMem(in_SQLDA^.SQLVar[x].SQLLen);
  462. if (sqltype and 1) = 1 then New(SQLInd);
  463. end;
  464. {$R+}
  465. end
  466. else
  467. AllocSQLDA(in_SQLDA,0);
  468. if FStatementType = stselect then
  469. begin
  470. FPrepared := False;
  471. if isc_dsql_describe(@Status[0], @Statement, 1, SQLDA) <> 0 then
  472. CheckError('PrepareSelect', Status);
  473. if SQLDA^.SQLD > SQLDA^.SQLN then
  474. begin
  475. AllocSQLDA(SQLDA,SQLDA^.SQLD);
  476. if isc_dsql_describe(@Status[0], @Statement, 1, SQLDA) <> 0 then
  477. CheckError('PrepareSelect', Status);
  478. end;
  479. {$R-}
  480. for x := 0 to SQLDA^.SQLD - 1 do with SQLDA^.SQLVar[x] do
  481. begin
  482. if ((SQLType and not 1) = SQL_VARYING) then
  483. SQLData := AllocMem(SQLDA^.SQLVar[x].SQLLen+2)
  484. else
  485. SQLData := AllocMem(SQLDA^.SQLVar[x].SQLLen);
  486. if (SQLType and 1) = 1 then New(SQLInd);
  487. end;
  488. {$R+}
  489. end;
  490. end;
  491. end;
  492. procedure TIBConnection.UnPrepareStatement(cursor : TSQLCursor);
  493. begin
  494. with cursor as TIBcursor do
  495. begin
  496. if isc_dsql_free_statement(@Status[0], @Statement, DSQL_Drop) <> 0 then
  497. CheckError('FreeStatement', Status);
  498. Statement := nil;
  499. FPrepared := False;
  500. end;
  501. end;
  502. procedure TIBConnection.FreeSQLDABuffer(var aSQLDA : PXSQLDA);
  503. var x : shortint;
  504. begin
  505. {$R-}
  506. if assigned(aSQLDA) then
  507. for x := 0 to aSQLDA^.SQLN - 1 do
  508. begin
  509. reAllocMem(aSQLDA^.SQLVar[x].SQLData,0);
  510. if assigned(aSQLDA^.SQLVar[x].sqlind) then
  511. begin
  512. Dispose(aSQLDA^.SQLVar[x].sqlind);
  513. aSQLDA^.SQLVar[x].sqlind := nil;
  514. end
  515. end;
  516. {$R+}
  517. end;
  518. procedure TIBConnection.FreeFldBuffers(cursor : TSQLCursor);
  519. begin
  520. with cursor as TIBCursor do
  521. begin
  522. FreeSQLDABuffer(SQLDA);
  523. FreeSQLDABuffer(in_SQLDA);
  524. SetLength(FieldBinding,0);
  525. end;
  526. end;
  527. procedure TIBConnection.Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams);
  528. var tr : pointer;
  529. begin
  530. tr := aTransaction.Handle;
  531. if Assigned(APArams) and (AParams.count > 0) then SetParameters(cursor, AParams);
  532. with cursor as TIBCursor do
  533. if isc_dsql_execute2(@Status[0], @tr, @Statement, 1, in_SQLDA, nil) <> 0 then
  534. CheckError('Execute', Status);
  535. end;
  536. procedure TIBConnection.AddFieldDefs(cursor: TSQLCursor;FieldDefs : TfieldDefs);
  537. var
  538. x : integer;
  539. lenset : boolean;
  540. TransLen : word;
  541. TransType : TFieldType;
  542. FD : TFieldDef;
  543. begin
  544. {$R-}
  545. with cursor as TIBCursor do
  546. begin
  547. setlength(FieldBinding,SQLDA^.SQLD);
  548. for x := 0 to SQLDA^.SQLD - 1 do
  549. begin
  550. TranslateFldType(SQLDA^.SQLVar[x].SQLType, SQLDA^.SQLVar[x].SQLLen, SQLDA^.SQLVar[x].SQLScale,
  551. lenset, TransType, TransLen);
  552. FD := TFieldDef.Create(FieldDefs, SQLDA^.SQLVar[x].AliasName, TransType,
  553. TransLen, False, (x + 1));
  554. if TransType = ftBCD then FD.precision := SQLDA^.SQLVar[x].SQLLen;
  555. // FD.DisplayName := SQLDA^.SQLVar[x].AliasName;
  556. FieldBinding[FD.FieldNo-1] := x;
  557. end;
  558. end;
  559. {$R+}
  560. end;
  561. function TIBConnection.GetHandle: pointer;
  562. begin
  563. Result := FSQLDatabaseHandle;
  564. end;
  565. function TIBConnection.Fetch(cursor : TSQLCursor) : boolean;
  566. var
  567. retcode : integer;
  568. begin
  569. with cursor as TIBCursor do
  570. begin
  571. retcode := isc_dsql_fetch(@Status[0], @Statement, 1, SQLDA);
  572. if (retcode <> 0) and (retcode <> 100) then
  573. CheckError('Fetch', Status);
  574. end;
  575. Result := (retcode <> 100);
  576. end;
  577. procedure TIBConnection.SetParameters(cursor : TSQLCursor;AParams : TParams);
  578. var ParNr,SQLVarNr : integer;
  579. s : string;
  580. i : integer;
  581. li : LargeInt;
  582. currbuff : pchar;
  583. w : word;
  584. TransactionHandle : pointer;
  585. blobId : ISC_QUAD;
  586. blobHandle : Isc_blob_Handle;
  587. BlobSize,
  588. BlobBytesWritten : longint;
  589. procedure SetBlobParam;
  590. begin
  591. {$R-}
  592. with cursor as TIBCursor do
  593. begin
  594. TransactionHandle := transaction.Handle;
  595. blobhandle := nil;
  596. if isc_create_blob(@FStatus[0], @FSQLDatabaseHandle, @TransactionHandle, @blobHandle, @blobId) <> 0 then
  597. CheckError('TIBConnection.CreateBlobStream', FStatus);
  598. s := AParams[ParNr].AsString;
  599. BlobSize := length(s);
  600. BlobBytesWritten := 0;
  601. i := 0;
  602. while BlobBytesWritten < (BlobSize-BlobSegmentSize) do
  603. begin
  604. isc_put_segment(@FStatus[0], @blobHandle, BlobSegmentSize, @s[(i*BlobSegmentSize)+1]);
  605. inc(BlobBytesWritten,BlobSegmentSize);
  606. inc(i);
  607. end;
  608. if BlobBytesWritten <> BlobSize then
  609. isc_put_segment(@FStatus[0], @blobHandle, BlobSize-BlobBytesWritten, @s[(i*BlobSegmentSize)+1]);
  610. if isc_close_blob(@FStatus[0], @blobHandle) <> 0 then
  611. CheckError('TIBConnection.CreateBlobStream isc_close_blob', FStatus);
  612. Move(blobId, in_sqlda^.SQLvar[SQLVarNr].SQLData^, in_SQLDA^.SQLVar[SQLVarNr].SQLLen);
  613. end;
  614. {$R+}
  615. end;
  616. begin
  617. {$R-}
  618. with cursor as TIBCursor do for SQLVarNr := 0 to High(ParamBinding){AParams.count-1} do
  619. begin
  620. ParNr := ParamBinding[SQLVarNr];
  621. if AParams[ParNr].IsNull then
  622. begin
  623. If Assigned(in_sqlda^.SQLvar[SQLVarNr].SQLInd) then
  624. in_sqlda^.SQLvar[SQLVarNr].SQLInd^ := -1;
  625. end
  626. else
  627. begin
  628. if assigned(in_sqlda^.SQLvar[SQLVarNr].SQLInd) then in_sqlda^.SQLvar[SQLVarNr].SQLInd^ := 0;
  629. case AParams[ParNr].DataType of
  630. ftInteger :
  631. begin
  632. i := AParams[ParNr].AsInteger;
  633. Move(i, in_sqlda^.SQLvar[SQLVarNr].SQLData^, in_SQLDA^.SQLVar[SQLVarNr].SQLLen);
  634. end;
  635. ftString,ftFixedChar : if ((in_sqlda^.SQLvar[SQLVarNr].SQLType and not 1) = SQL_BLOB) then SetBlobParam else
  636. begin
  637. s := AParams[ParNr].AsString;
  638. w := length(s); // a word is enough, since the max-length of a string in interbase is 32k
  639. if ((in_sqlda^.SQLvar[SQLVarNr].SQLType and not 1) = SQL_VARYING) then
  640. begin
  641. in_sqlda^.SQLvar[SQLVarNr].SQLLen := w;
  642. ReAllocMem(in_sqlda^.SQLvar[SQLVarNr].SQLData,in_SQLDA^.SQLVar[SQLVarNr].SQLLen+2);
  643. CurrBuff := in_sqlda^.SQLvar[SQLVarNr].SQLData;
  644. move(w,CurrBuff^,sizeof(w));
  645. inc(CurrBuff,2);
  646. end
  647. else
  648. CurrBuff := in_sqlda^.SQLvar[SQLVarNr].SQLData;
  649. Move(s[1], CurrBuff^, w);
  650. end;
  651. ftDate, ftTime, ftDateTime:
  652. SetDateTime(in_sqlda^.SQLvar[SQLVarNr].SQLData, AParams[ParNr].AsDateTime, in_SQLDA^.SQLVar[SQLVarNr].SQLType);
  653. ftLargeInt:
  654. begin
  655. li := AParams[ParNr].AsLargeInt;
  656. Move(li, in_sqlda^.SQLvar[SQLVarNr].SQLData^, in_SQLDA^.SQLVar[SQLVarNr].SQLLen);
  657. end;
  658. ftFloat:
  659. SetFloat(in_sqlda^.SQLvar[SQLVarNr].SQLData, AParams[ParNr].AsFloat, in_SQLDA^.SQLVar[SQLVarNr].SQLLen);
  660. ftBlob, ftMemo:
  661. begin
  662. SetBlobParam;
  663. end;
  664. else
  665. DatabaseErrorFmt(SUnsupportedParameter,[Fieldtypenames[AParams[ParNr].DataType]],self);
  666. end {case}
  667. end;
  668. end;
  669. {$R+}
  670. end;
  671. function TIBConnection.LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  672. var
  673. x : integer;
  674. VarcharLen : word;
  675. CurrBuff : pchar;
  676. c : currency;
  677. begin
  678. CreateBlob := False;
  679. with cursor as TIBCursor do
  680. begin
  681. {$R-}
  682. x := FieldBinding[FieldDef.FieldNo-1];
  683. // Joost, 5 jan 2006: I disabled the following, since it's usefull for
  684. // debugging, but it also slows things down. In principle things can only go
  685. // wrong when FieldDefs is changed while the dataset is opened. A user just
  686. // shoudn't do that. ;) (The same is done in PQConnection)
  687. // if SQLDA^.SQLVar[x].AliasName <> FieldDef.Name then
  688. // DatabaseErrorFmt(SFieldNotFound,[FieldDef.Name],self);
  689. if assigned(SQLDA^.SQLVar[x].SQLInd) and (SQLDA^.SQLVar[x].SQLInd^ = -1) then
  690. result := false
  691. else
  692. begin
  693. with SQLDA^.SQLVar[x] do
  694. if ((SQLType and not 1) = SQL_VARYING) then
  695. begin
  696. Move(SQLData^, VarcharLen, 2);
  697. CurrBuff := SQLData + 2;
  698. end
  699. else
  700. begin
  701. CurrBuff := SQLData;
  702. VarCharLen := SQLDA^.SQLVar[x].SQLLen;
  703. end;
  704. Result := true;
  705. case FieldDef.DataType of
  706. ftBCD :
  707. begin
  708. c := 0;
  709. Move(CurrBuff^, c, SQLDA^.SQLVar[x].SQLLen);
  710. c := c*intpower(10,4+SQLDA^.SQLVar[x].SQLScale);
  711. Move(c, buffer^ , sizeof(c));
  712. end;
  713. ftInteger :
  714. begin
  715. FillByte(buffer^,sizeof(Longint),0);
  716. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  717. end;
  718. ftLargeint :
  719. begin
  720. FillByte(buffer^,sizeof(LargeInt),0);
  721. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  722. end;
  723. ftSmallint :
  724. begin
  725. FillByte(buffer^,sizeof(Smallint),0);
  726. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  727. end;
  728. ftDate, ftTime, ftDateTime:
  729. GetDateTime(CurrBuff, Buffer, SQLDA^.SQLVar[x].SQLType);
  730. ftString :
  731. begin
  732. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  733. PChar(Buffer + VarCharLen)^ := #0;
  734. end;
  735. ftFloat :
  736. GetFloat(CurrBuff, Buffer, FieldDef);
  737. ftBlob : begin // load the BlobIb in field's buffer
  738. FillByte(buffer^,sizeof(TBufBlobField),0);
  739. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  740. end
  741. else result := false;
  742. end;
  743. end;
  744. {$R+}
  745. end;
  746. end;
  747. procedure TIBConnection.GetDateTime(CurrBuff, Buffer : pointer; AType : integer);
  748. var
  749. CTime : TTm; // C struct time
  750. STime : TSystemTime; // System time
  751. PTime : TDateTime; // Pascal time
  752. begin
  753. case (AType and not 1) of
  754. SQL_TYPE_DATE :
  755. isc_decode_sql_date(PISC_DATE(CurrBuff), @CTime);
  756. SQL_TYPE_TIME :
  757. isc_decode_sql_time(PISC_TIME(CurrBuff), @CTime);
  758. SQL_TIMESTAMP :
  759. isc_decode_timestamp(PISC_TIMESTAMP(CurrBuff), @CTime);
  760. end;
  761. STime.Year := CTime.tm_year + 1900;
  762. STime.Month := CTime.tm_mon + 1;
  763. STime.Day := CTime.tm_mday;
  764. STime.Hour := CTime.tm_hour;
  765. STime.Minute := CTime.tm_min;
  766. STime.Second := CTime.tm_sec;
  767. STime.Millisecond := 0;
  768. PTime := SystemTimeToDateTime(STime);
  769. Move(PTime, Buffer^, SizeOf(PTime));
  770. end;
  771. procedure TIBConnection.SetDateTime(CurrBuff: pointer; PTime : TDateTime; AType : integer);
  772. var
  773. CTime : TTm; // C struct time
  774. STime : TSystemTime; // System time
  775. begin
  776. DateTimeToSystemTime(PTime,STime);
  777. CTime.tm_year := STime.Year - 1900;
  778. CTime.tm_mon := STime.Month -1;
  779. CTime.tm_mday := STime.Day;
  780. CTime.tm_hour := STime.Hour;
  781. CTime.tm_min := STime.Minute;
  782. CTime.tm_sec := STime.Second;
  783. case (AType and not 1) of
  784. SQL_TYPE_DATE :
  785. isc_encode_sql_date(@CTime, PISC_DATE(CurrBuff));
  786. SQL_TYPE_TIME :
  787. isc_encode_sql_time(@CTime, PISC_TIME(CurrBuff));
  788. SQL_TIMESTAMP :
  789. isc_encode_timestamp(@CTime, PISC_TIMESTAMP(CurrBuff));
  790. end;
  791. end;
  792. function TIBConnection.GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string;
  793. var s : string;
  794. begin
  795. case SchemaType of
  796. stTables : s := 'select '+
  797. 'rdb$relation_id as recno, '+
  798. '''' + DatabaseName + ''' as catalog_name, '+
  799. ''''' as schema_name, '+
  800. 'rdb$relation_name as table_name, '+
  801. '0 as table_type '+
  802. 'from '+
  803. 'rdb$relations '+
  804. 'where '+
  805. '(rdb$system_flag = 0 or rdb$system_flag is null) ' + // and rdb$view_blr is null
  806. 'order by rdb$relation_name';
  807. stSysTables : s := 'select '+
  808. 'rdb$relation_id as recno, '+
  809. '''' + DatabaseName + ''' as catalog_name, '+
  810. ''''' as schema_name, '+
  811. 'rdb$relation_name as table_name, '+
  812. '0 as table_type '+
  813. 'from '+
  814. 'rdb$relations '+
  815. 'where '+
  816. '(rdb$system_flag > 0) ' + // and rdb$view_blr is null
  817. 'order by rdb$relation_name';
  818. stProcedures : s := 'select '+
  819. 'rdb$procedure_id as recno, '+
  820. '''' + DatabaseName + ''' as catalog_name, '+
  821. ''''' as schema_name, '+
  822. 'rdb$procedure_name as proc_name, '+
  823. '0 as proc_type, '+
  824. 'rdb$procedure_inputs as in_params, '+
  825. 'rdb$procedure_outputs as out_params '+
  826. 'from '+
  827. 'rdb$procedures '+
  828. 'WHERE '+
  829. '(rdb$system_flag = 0 or rdb$system_flag is null)';
  830. stColumns : s := 'select '+
  831. 'rdb$field_id as recno, '+
  832. '''' + DatabaseName + ''' as catalog_name, '+
  833. ''''' as schema_name, '+
  834. 'rdb$relation_name as table_name, '+
  835. 'rdb$field_name as column_name, '+
  836. 'rdb$field_position as column_position, '+
  837. '0 as column_type, '+
  838. '0 as column_datatype, '+
  839. ''''' as column_typename, '+
  840. '0 as column_subtype, '+
  841. '0 as column_precision, '+
  842. '0 as column_scale, '+
  843. '0 as column_length, '+
  844. '0 as column_nullable '+
  845. 'from '+
  846. 'rdb$relation_fields '+
  847. 'WHERE '+
  848. '(rdb$system_flag = 0 or rdb$system_flag is null) and (rdb$relation_name = ''' + Uppercase(SchemaObjectName) + ''') ' +
  849. 'order by rdb$field_name';
  850. else
  851. DatabaseError(SMetadataUnavailable)
  852. end; {case}
  853. result := s;
  854. end;
  855. procedure TIBConnection.UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string);
  856. var qry : TSQLQuery;
  857. begin
  858. if not assigned(Transaction) then
  859. DatabaseError(SErrConnTransactionnSet);
  860. qry := tsqlquery.Create(nil);
  861. qry.transaction := Transaction;
  862. qry.database := Self;
  863. with qry do
  864. begin
  865. ReadOnly := True;
  866. sql.clear;
  867. sql.add('select '+
  868. 'ind.rdb$index_name, '+
  869. 'ind.rdb$relation_name, '+
  870. 'ind.rdb$unique_flag, '+
  871. 'ind_seg.rdb$field_name, '+
  872. 'rel_con.rdb$constraint_type '+
  873. 'from '+
  874. 'rdb$index_segments ind_seg, '+
  875. 'rdb$indices ind '+
  876. 'left outer join '+
  877. 'rdb$relation_constraints rel_con '+
  878. 'on '+
  879. 'rel_con.rdb$index_name = ind.rdb$index_name '+
  880. 'where '+
  881. '(ind_seg.rdb$index_name = ind.rdb$index_name) and '+
  882. '(ind.rdb$relation_name=''' + UpperCase(TableName) +''') '+
  883. 'order by '+
  884. 'ind.rdb$index_name;');
  885. open;
  886. end;
  887. IndexDefs.Clear;
  888. while not qry.eof do with IndexDefs.AddIndexDef do
  889. begin
  890. Name := trim(qry.fields[0].asstring);
  891. Fields := trim(qry.Fields[3].asstring);
  892. If qry.fields[4].asstring = 'PRIMARY KEY' then options := options + [ixPrimary];
  893. If qry.fields[2].asinteger = 1 then options := options + [ixUnique];
  894. qry.next;
  895. while (name = trim(qry.fields[0].asstring)) and (not qry.eof) do
  896. begin
  897. Fields := Fields + ';' + trim(qry.Fields[3].asstring);
  898. qry.next;
  899. end;
  900. end;
  901. qry.close;
  902. qry.free;
  903. end;
  904. procedure TIBConnection.SetFloat(CurrBuff: pointer; Dbl: Double; Size: integer);
  905. var
  906. Ext : extended;
  907. Sin : single;
  908. begin
  909. case Size of
  910. 4 :
  911. begin
  912. Sin := Dbl;
  913. Move(Sin, CurrBuff^, 4);
  914. end;
  915. 8 :
  916. begin
  917. Move(Dbl, CurrBuff^, 8);
  918. end;
  919. 10:
  920. begin
  921. Ext := Dbl;
  922. Move(Ext, CurrBuff^, 10);
  923. end;
  924. end;
  925. end;
  926. procedure TIBConnection.GetFloat(CurrBuff, Buffer : pointer; Field : TFieldDef);
  927. var
  928. Ext : extended;
  929. Dbl : double;
  930. Sin : single;
  931. begin
  932. case Field.Size of
  933. 4 :
  934. begin
  935. Move(CurrBuff^, Sin, 4);
  936. Dbl := Sin;
  937. end;
  938. 8 :
  939. begin
  940. Move(CurrBuff^, Dbl, 8);
  941. end;
  942. 10:
  943. begin
  944. Move(CurrBuff^, Ext, 10);
  945. Dbl := double(Ext);
  946. end;
  947. end;
  948. Move(Dbl, Buffer^, 8);
  949. end;
  950. function TIBConnection.getMaxBlobSize(blobHandle : TIsc_Blob_Handle) : longInt;
  951. var
  952. iscInfoBlobMaxSegment : byte = isc_info_blob_max_segment;
  953. blobInfo : array[0..50] of byte;
  954. begin
  955. if isc_blob_info(@Fstatus[0], @blobHandle, sizeof(iscInfoBlobMaxSegment), pchar(@iscInfoBlobMaxSegment), sizeof(blobInfo) - 2, pchar(@blobInfo[0])) <> 0 then
  956. CheckError('isc_blob_info', FStatus);
  957. if blobInfo[0] = isc_info_blob_max_segment then
  958. begin
  959. result := isc_vax_integer(pchar(@blobInfo[3]), isc_vax_integer(pchar(@blobInfo[1]), 2));
  960. end
  961. else
  962. CheckError('isc_blob_info', FStatus);
  963. end;
  964. procedure TIBConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction : TSQLTransaction);
  965. const
  966. isc_segstr_eof = 335544367; // It's not defined in ibase60 but in ibase40. Would it be better to define in ibase60?
  967. var
  968. blobHandle : Isc_blob_Handle;
  969. blobSegment : pointer;
  970. blobSegLen : word;
  971. maxBlobSize : longInt;
  972. TransactionHandle : pointer;
  973. blobId : PISC_QUAD;
  974. ptr : Pointer;
  975. begin
  976. blobId := PISC_QUAD(@(ABlobBuf^.ConnBlobBuffer));
  977. TransactionHandle := Atransaction.Handle;
  978. blobHandle := nil;
  979. if isc_open_blob(@FStatus[0], @FSQLDatabaseHandle, @TransactionHandle, @blobHandle, blobId) <> 0 then
  980. CheckError('TIBConnection.CreateBlobStream', FStatus);
  981. maxBlobSize := getMaxBlobSize(blobHandle);
  982. blobSegment := AllocMem(maxBlobSize);
  983. with ABlobBuf^.BlobBuffer^ do
  984. begin
  985. Size := 0;
  986. while (isc_get_segment(@FStatus[0], @blobHandle, @blobSegLen, maxBlobSize, blobSegment) = 0) do
  987. begin
  988. ReAllocMem(Buffer,Size+blobSegLen);
  989. ptr := Buffer+Size;
  990. move(blobSegment^,ptr^,blobSegLen);
  991. inc(Size,blobSegLen);
  992. end;
  993. end;
  994. freemem(blobSegment);
  995. if FStatus[1] = isc_segstr_eof then
  996. begin
  997. if isc_close_blob(@FStatus[0], @blobHandle) <> 0 then
  998. CheckError('TIBConnection.CreateBlobStream isc_close_blob', FStatus);
  999. end
  1000. else
  1001. CheckError('TIBConnection.CreateBlobStream isc_get_segment', FStatus);
  1002. end;
  1003. { TIBConnectionDef }
  1004. class function TIBConnectionDef.TypeName: String;
  1005. begin
  1006. Result:='Firebird';
  1007. end;
  1008. class function TIBConnectionDef.ConnectionClass: TSQLConnectionClass;
  1009. begin
  1010. Result:=TIBConnection;
  1011. end;
  1012. class function TIBConnectionDef.Description: String;
  1013. begin
  1014. Result:='Connect to Firebird/Interbase directly via the client library';
  1015. end;
  1016. initialization
  1017. RegisterConnection(TIBConnectionDef);
  1018. finalization
  1019. UnRegisterConnection(TIBConnectionDef);
  1020. end.