ibconnection.pp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. unit IBConnection;
  2. {$mode objfpc}{$H+}
  3. {$Define LinkDynamically}
  4. interface
  5. uses
  6. Classes, SysUtils, sqldb, db, dbconst, bufdataset,
  7. {$IfDef LinkDynamically}
  8. ibase60dyn;
  9. {$Else}
  10. ibase60;
  11. {$EndIf}
  12. const
  13. DEFDIALECT = 3;
  14. MAXBLOBSEGMENTSIZE = 65535; //Maximum number of bytes that fit in a blob segment.
  15. type
  16. EIBDatabaseError = class(EDatabaseError)
  17. public
  18. GDSErrorCode : Longint;
  19. end;
  20. { TIBCursor }
  21. TIBCursor = Class(TSQLCursor)
  22. protected
  23. Status : array [0..19] of ISC_STATUS;
  24. Statement : pointer;
  25. SQLDA : PXSQLDA;
  26. in_SQLDA : PXSQLDA;
  27. ParamBinding : array of integer;
  28. FieldBinding : array of integer;
  29. end;
  30. TIBTrans = Class(TSQLHandle)
  31. protected
  32. TransactionHandle : pointer;
  33. TPB : string; // Transaction parameter buffer
  34. Status : array [0..19] of ISC_STATUS;
  35. end;
  36. { TIBConnection }
  37. TIBConnection = class (TSQLConnection)
  38. private
  39. FSQLDatabaseHandle : pointer;
  40. FStatus : array [0..19] of ISC_STATUS;
  41. FDialect : integer;
  42. FDBDialect : integer;
  43. FBLobSegmentSize : word; //required for backward compatibilty; not used
  44. procedure ConnectFB;
  45. function GetDialect: integer;
  46. procedure AllocSQLDA(var aSQLDA : PXSQLDA;Count : integer);
  47. procedure TranslateFldType(SQLType, SQLSubType, SQLLen, SQLScale : integer;
  48. var TrType : TFieldType; var TrLen : word);
  49. // conversion methods
  50. procedure GetDateTime(CurrBuff, Buffer : pointer; AType : integer);
  51. procedure SetDateTime(CurrBuff: pointer; PTime : TDateTime; AType : integer);
  52. procedure GetFloat(CurrBuff, Buffer : pointer; Size : Byte);
  53. procedure SetFloat(CurrBuff: pointer; Dbl: Double; Size: integer);
  54. procedure CheckError(ProcName : string; Status : PISC_STATUS);
  55. procedure SetParameters(cursor : TSQLCursor; aTransation : TSQLTransaction; AParams : TParams);
  56. procedure FreeSQLDABuffer(var aSQLDA : PXSQLDA);
  57. function IsDialectStored: boolean;
  58. protected
  59. procedure DoConnect; override;
  60. procedure DoInternalConnect; override;
  61. procedure DoInternalDisconnect; override;
  62. function GetHandle : pointer; override;
  63. Function AllocateCursorHandle : TSQLCursor; override;
  64. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  65. Function AllocateTransactionHandle : TSQLHandle; override;
  66. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  67. procedure UnPrepareStatement(cursor : TSQLCursor); override;
  68. procedure FreeFldBuffers(cursor : TSQLCursor); override;
  69. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); override;
  70. procedure AddFieldDefs(cursor: TSQLCursor;FieldDefs : TfieldDefs); override;
  71. function Fetch(cursor : TSQLCursor) : boolean; override;
  72. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  73. function GetBlobSize(blobHandle : TIsc_Blob_Handle) : LongInt;
  74. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  75. function Commit(trans : TSQLHandle) : boolean; override;
  76. function RollBack(trans : TSQLHandle) : boolean; override;
  77. function StartdbTransaction(trans : TSQLHandle; AParams : string) : boolean; override;
  78. procedure CommitRetaining(trans : TSQLHandle); override;
  79. procedure RollBackRetaining(trans : TSQLHandle); override;
  80. procedure UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string); override;
  81. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  82. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction : TSQLTransaction); override;
  83. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  84. public
  85. constructor Create(AOwner : TComponent); override;
  86. procedure CreateDB; override;
  87. procedure DropDB; override;
  88. //Segment size is not used in the code; property kept for backward compatibility
  89. property BlobSegmentSize : word read FBlobSegmentSize write FBlobSegmentSize; deprecated;
  90. function GetDBDialect: integer;
  91. published
  92. property DatabaseName;
  93. property Dialect : integer read GetDialect write FDialect stored IsDialectStored default DEFDIALECT;
  94. property KeepConnection;
  95. property LoginPrompt;
  96. property Params;
  97. property OnLogin;
  98. end;
  99. { TIBConnectionDef }
  100. TIBConnectionDef = Class(TConnectionDef)
  101. Class Function TypeName : String; override;
  102. Class Function ConnectionClass : TSQLConnectionClass; override;
  103. Class Function Description : String; override;
  104. Class Function DefaultLibraryName : String; override;
  105. Class Function LoadFunction : TLibraryLoadFunction; override;
  106. Class Function UnLoadFunction : TLibraryUnLoadFunction; override;
  107. end;
  108. implementation
  109. uses
  110. strutils, FmtBCD;
  111. type
  112. TTm = packed record
  113. tm_sec : longint;
  114. tm_min : longint;
  115. tm_hour : longint;
  116. tm_mday : longint;
  117. tm_mon : longint;
  118. tm_year : longint;
  119. tm_wday : longint;
  120. tm_yday : longint;
  121. tm_isdst : longint;
  122. __tm_gmtoff : longint;
  123. __tm_zone : Pchar;
  124. end;
  125. procedure TIBConnection.CheckError(ProcName : string; Status : PISC_STATUS);
  126. var
  127. buf : array [0..1023] of char;
  128. Msg : string;
  129. E : EIBDatabaseError;
  130. Err : longint;
  131. begin
  132. if ((Status[0] = 1) and (Status[1] <> 0)) then
  133. begin
  134. Err := Status[1];
  135. msg := '';
  136. while isc_interprete(Buf, @Status) > 0 do
  137. Msg := Msg + LineEnding +' -' + StrPas(Buf);
  138. E := EIBDatabaseError.CreateFmt('%s : %s : %s',[self.Name,ProcName,Msg]);
  139. E.GDSErrorCode := Err;
  140. Raise E;
  141. end;
  142. end;
  143. constructor TIBConnection.Create(AOwner : TComponent);
  144. begin
  145. inherited;
  146. FConnOptions := FConnOptions + [sqSupportParams] + [sqEscapeRepeat];
  147. FBLobSegmentSize := 65535; //Shows we're using the maximum segment size
  148. FDialect := -1;
  149. FDBDialect := -1;
  150. end;
  151. function TIBConnection.GetTransactionHandle(trans : TSQLHandle): pointer;
  152. begin
  153. Result := (trans as TIBtrans).TransactionHandle;
  154. end;
  155. function TIBConnection.Commit(trans : TSQLHandle) : boolean;
  156. begin
  157. result := false;
  158. with (trans as TIBTrans) do
  159. if isc_commit_transaction(@Status[0], @TransactionHandle) <> 0 then
  160. CheckError('Commit', Status)
  161. else result := true;
  162. end;
  163. function TIBConnection.RollBack(trans : TSQLHandle) : boolean;
  164. begin
  165. result := false;
  166. if isc_rollback_transaction(@TIBTrans(trans).Status[0], @TIBTrans(trans).TransactionHandle) <> 0 then
  167. CheckError('Rollback', TIBTrans(trans).Status)
  168. else result := true;
  169. end;
  170. function TIBConnection.StartDBTransaction(trans : TSQLHandle;AParams : String) : boolean;
  171. var
  172. DBHandle : pointer;
  173. tr : TIBTrans;
  174. i : integer;
  175. s : string;
  176. begin
  177. result := false;
  178. DBHandle := GetHandle;
  179. tr := trans as TIBtrans;
  180. with tr do
  181. begin
  182. TPB := chr(isc_tpb_version3);
  183. i := 1;
  184. s := ExtractSubStr(AParams,i,stdWordDelims);
  185. while s <> '' do
  186. begin
  187. if s='isc_tpb_write' then TPB := TPB + chr(isc_tpb_write)
  188. else if s='isc_tpb_read' then TPB := TPB + chr(isc_tpb_read)
  189. else if s='isc_tpb_consistency' then TPB := TPB + chr(isc_tpb_consistency)
  190. else if s='isc_tpb_concurrency' then TPB := TPB + chr(isc_tpb_concurrency)
  191. else if s='isc_tpb_read_committed' then TPB := TPB + chr(isc_tpb_read_committed)
  192. else if s='isc_tpb_rec_version' then TPB := TPB + chr(isc_tpb_rec_version)
  193. else if s='isc_tpb_no_rec_version' then TPB := TPB + chr(isc_tpb_no_rec_version)
  194. else if s='isc_tpb_wait' then TPB := TPB + chr(isc_tpb_wait)
  195. else if s='isc_tpb_nowait' then TPB := TPB + chr(isc_tpb_nowait)
  196. else if s='isc_tpb_shared' then TPB := TPB + chr(isc_tpb_shared)
  197. else if s='isc_tpb_protected' then TPB := TPB + chr(isc_tpb_protected)
  198. else if s='isc_tpb_exclusive' then TPB := TPB + chr(isc_tpb_exclusive)
  199. else if s='isc_tpb_lock_read' then TPB := TPB + chr(isc_tpb_lock_read)
  200. else if s='isc_tpb_lock_write' then TPB := TPB + chr(isc_tpb_lock_write)
  201. else if s='isc_tpb_verb_time' then TPB := TPB + chr(isc_tpb_verb_time)
  202. else if s='isc_tpb_commit_time' then TPB := TPB + chr(isc_tpb_commit_time)
  203. else if s='isc_tpb_ignore_limbo' then TPB := TPB + chr(isc_tpb_ignore_limbo)
  204. else if s='isc_tpb_autocommit' then TPB := TPB + chr(isc_tpb_autocommit)
  205. else if s='isc_tpb_restart_requests' then TPB := TPB + chr(isc_tpb_restart_requests)
  206. else if s='isc_tpb_no_auto_undo' then TPB := TPB + chr(isc_tpb_no_auto_undo);
  207. s := ExtractSubStr(AParams,i,stdWordDelims);
  208. end;
  209. TransactionHandle := nil;
  210. if isc_start_transaction(@Status[0], @TransactionHandle, 1,
  211. [@DBHandle, Length(TPB), @TPB[1]]) <> 0 then
  212. CheckError('StartTransaction',Status)
  213. else Result := True;
  214. end;
  215. end;
  216. procedure TIBConnection.CommitRetaining(trans : TSQLHandle);
  217. begin
  218. with trans as TIBtrans do
  219. if isc_commit_retaining(@Status[0], @TransactionHandle) <> 0 then
  220. CheckError('CommitRetaining', Status);
  221. end;
  222. procedure TIBConnection.RollBackRetaining(trans : TSQLHandle);
  223. begin
  224. with trans as TIBtrans do
  225. if isc_rollback_retaining(@Status[0], @TransactionHandle) <> 0 then
  226. CheckError('RollBackRetaining', Status);
  227. end;
  228. procedure TIBConnection.DropDB;
  229. begin
  230. CheckDisConnected;
  231. {$IfDef LinkDynamically}
  232. InitialiseIBase60;
  233. {$EndIf}
  234. ConnectFB;
  235. if isc_drop_database(@FStatus[0], @FSQLDatabaseHandle) <> 0 then
  236. CheckError('DropDB', FStatus);
  237. {$IfDef LinkDynamically}
  238. ReleaseIBase60;
  239. {$EndIf}
  240. end;
  241. procedure TIBConnection.CreateDB;
  242. var ASQLDatabaseHandle,
  243. ASQLTransactionHandle : pointer;
  244. CreateSQL : String;
  245. pagesize : String;
  246. begin
  247. CheckDisConnected;
  248. {$IfDef LinkDynamically}
  249. InitialiseIBase60;
  250. {$EndIf}
  251. ASQLDatabaseHandle := nil;
  252. ASQLTransactionHandle := nil;
  253. CreateSQL := 'CREATE DATABASE ';
  254. if HostName <> '' then CreateSQL := CreateSQL + ''''+ HostName+':'+DatabaseName + ''''
  255. else CreateSQL := CreateSQL + '''' + DatabaseName + '''';
  256. if UserName <> '' then
  257. CreateSQL := CreateSQL + ' USER ''' + Username + '''';
  258. if Password <> '' then
  259. CreateSQL := CreateSQL + ' PASSWORD ''' + Password + '''';
  260. pagesize := params.Values['PAGE_SIZE'];
  261. if pagesize <> '' then
  262. CreateSQL := CreateSQL + ' PAGE_SIZE '+pagesize;
  263. if CharSet <> '' then
  264. CreateSQL := CreateSQL + ' DEFAULT CHARACTER SET ' + CharSet;
  265. if isc_dsql_execute_immediate(@FStatus[0],@ASQLDatabaseHandle,@ASQLTransactionHandle,length(CreateSQL),@CreateSQL[1],Dialect,nil) <> 0 then
  266. CheckError('CreateDB', FStatus);
  267. if isc_detach_database(@FStatus[0], @ASQLDatabaseHandle) <> 0 then
  268. CheckError('CreateDB', FStatus);
  269. {$IfDef LinkDynamically}
  270. ReleaseIBase60;
  271. {$EndIf}
  272. end;
  273. procedure TIBConnection.DoInternalConnect;
  274. begin
  275. {$IfDef LinkDynamically}
  276. InitialiseIBase60;
  277. {$EndIf}
  278. inherited dointernalconnect;
  279. ConnectFB;
  280. end;
  281. procedure TIBConnection.DoInternalDisconnect;
  282. begin
  283. FDialect := -1;
  284. FDBDialect := -1;
  285. if not Connected then
  286. begin
  287. FSQLDatabaseHandle := nil;
  288. Exit;
  289. end;
  290. if isc_detach_database(@FStatus[0], @FSQLDatabaseHandle) <> 0 then
  291. CheckError('Close', FStatus);
  292. {$IfDef LinkDynamically}
  293. ReleaseIBase60;
  294. {$EndIf}
  295. end;
  296. function TIBConnection.GetDBDialect: integer;
  297. var
  298. x : integer;
  299. Len : integer;
  300. Buffer : array [0..1] of byte;
  301. ResBuf : array [0..39] of byte;
  302. begin
  303. result := -1;
  304. if Connected then
  305. begin
  306. Buffer[0] := isc_info_db_sql_dialect;
  307. Buffer[1] := isc_info_end;
  308. if isc_database_info(@FStatus[0], @FSQLDatabaseHandle, Length(Buffer),
  309. pchar(@Buffer[0]), SizeOf(ResBuf), pchar(@ResBuf[0])) <> 0 then
  310. CheckError('SetDBDialect', FStatus);
  311. x := 0;
  312. while x < 40 do
  313. case ResBuf[x] of
  314. isc_info_db_sql_dialect :
  315. begin
  316. Inc(x);
  317. Len := isc_vax_integer(pchar(@ResBuf[x]), 2);
  318. Inc(x, 2);
  319. Result := isc_vax_integer(pchar(@ResBuf[x]), Len);
  320. Inc(x, Len);
  321. end;
  322. isc_info_end : Break;
  323. else
  324. inc(x);
  325. end;
  326. end;
  327. end;
  328. procedure TIBConnection.ConnectFB;
  329. var
  330. ADatabaseName: String;
  331. DPB: string;
  332. begin
  333. DPB := chr(isc_dpb_version1);
  334. if (UserName <> '') then
  335. begin
  336. DPB := DPB + chr(isc_dpb_user_name) + chr(Length(UserName)) + UserName;
  337. if (Password <> '') then
  338. DPB := DPB + chr(isc_dpb_password) + chr(Length(Password)) + Password;
  339. end;
  340. if (Role <> '') then
  341. DPB := DPB + chr(isc_dpb_sql_role_name) + chr(Length(Role)) + Role;
  342. if Length(CharSet) > 0 then
  343. DPB := DPB + Chr(isc_dpb_lc_ctype) + Chr(Length(CharSet)) + CharSet;
  344. FSQLDatabaseHandle := nil;
  345. if HostName <> '' then ADatabaseName := HostName+':'+DatabaseName
  346. else ADatabaseName := DatabaseName;
  347. if isc_attach_database(@FStatus[0], Length(ADatabaseName), @ADatabaseName[1],
  348. @FSQLDatabaseHandle,
  349. Length(DPB), @DPB[1]) <> 0 then
  350. CheckError('DoInternalConnect', FStatus);
  351. end;
  352. function TIBConnection.GetDialect: integer;
  353. begin
  354. if FDialect = -1 then
  355. begin
  356. if FDBDialect = -1 then
  357. Result := DEFDIALECT
  358. else
  359. Result := FDBDialect;
  360. end else
  361. Result := FDialect;
  362. end;
  363. procedure TIBConnection.AllocSQLDA(var aSQLDA : PXSQLDA;Count : integer);
  364. begin
  365. FreeSQLDABuffer(aSQLDA);
  366. if count > -1 then
  367. begin
  368. reAllocMem(aSQLDA, XSQLDA_Length(Count));
  369. { Zero out the memory block to avoid problems with exceptions within the
  370. constructor of this class. }
  371. FillChar(aSQLDA^, XSQLDA_Length(Count), 0);
  372. aSQLDA^.Version := sqlda_version1;
  373. aSQLDA^.SQLN := Count;
  374. end
  375. else
  376. reAllocMem(aSQLDA,0);
  377. end;
  378. procedure TIBConnection.TranslateFldType(SQLType, SQLSubType, SQLLen, SQLScale : integer;
  379. var TrType : TFieldType; var TrLen : word);
  380. begin
  381. TrLen := 0;
  382. if SQLScale < 0 then
  383. begin
  384. TrLen := abs(SQLScale);
  385. if (TrLen <= MaxBCDScale) then //Note: NUMERIC(18,3) or (17,2) must be mapped to ftFmtBCD, but we do not know Precision
  386. TrType := ftBCD
  387. else
  388. TrType := ftFMTBcd;
  389. end
  390. else case (SQLType and not 1) of
  391. SQL_VARYING :
  392. begin
  393. TrType := ftString;
  394. TrLen := SQLLen;
  395. end;
  396. SQL_TEXT :
  397. begin
  398. TrType := ftFixedChar;
  399. TrLen := SQLLen;
  400. end;
  401. SQL_TYPE_DATE :
  402. TrType := ftDate;
  403. SQL_TYPE_TIME :
  404. TrType := ftTime;
  405. SQL_TIMESTAMP :
  406. TrType := ftDateTime;
  407. SQL_ARRAY :
  408. begin
  409. TrType := ftArray;
  410. TrLen := SQLLen;
  411. end;
  412. SQL_BLOB :
  413. begin
  414. if SQLSubType = 1 then
  415. TrType := ftMemo
  416. else
  417. TrType := ftBlob;
  418. TrLen := SQLLen;
  419. end;
  420. SQL_SHORT :
  421. TrType := ftSmallint;
  422. SQL_LONG :
  423. TrType := ftInteger;
  424. SQL_INT64 :
  425. TrType := ftLargeInt;
  426. SQL_DOUBLE :
  427. TrType := ftFloat;
  428. SQL_FLOAT :
  429. TrType := ftFloat;
  430. else
  431. TrType := ftUnknown;
  432. end;
  433. end;
  434. Function TIBConnection.AllocateCursorHandle : TSQLCursor;
  435. var curs : TIBCursor;
  436. begin
  437. curs := TIBCursor.create;
  438. curs.sqlda := nil;
  439. curs.statement := nil;
  440. curs.FPrepared := False;
  441. AllocSQLDA(curs.SQLDA,0);
  442. result := curs;
  443. end;
  444. procedure TIBConnection.DeAllocateCursorHandle(var cursor : TSQLCursor);
  445. begin
  446. if assigned(cursor) then with cursor as TIBCursor do
  447. begin
  448. AllocSQLDA(SQLDA,-1);
  449. AllocSQLDA(in_SQLDA,-1);
  450. end;
  451. FreeAndNil(cursor);
  452. end;
  453. Function TIBConnection.AllocateTransactionHandle : TSQLHandle;
  454. begin
  455. result := TIBTrans.create;
  456. end;
  457. procedure TIBConnection.PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams);
  458. var dh : pointer;
  459. tr : pointer;
  460. x : Smallint;
  461. info_request : string;
  462. resbuf : array[0..7] of byte;
  463. blockSize : integer;
  464. IBStatementType: integer;
  465. begin
  466. with cursor as TIBcursor do
  467. begin
  468. dh := GetHandle;
  469. if isc_dsql_allocate_statement(@Status[0], @dh, @Statement) <> 0 then
  470. CheckError('PrepareStatement', Status);
  471. tr := aTransaction.Handle;
  472. if assigned(AParams) and (AParams.count > 0) then
  473. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psInterbase,paramBinding);
  474. if isc_dsql_prepare(@Status[0], @tr, @Statement, 0, @Buf[1], Dialect, nil) <> 0 then
  475. CheckError('PrepareStatement', Status);
  476. if assigned(AParams) and (AParams.count > 0) then
  477. begin
  478. AllocSQLDA(in_SQLDA,Length(ParamBinding));
  479. if isc_dsql_describe_bind(@Status[0], @Statement, 1, in_SQLDA) <> 0 then
  480. CheckError('PrepareStatement', Status);
  481. if in_SQLDA^.SQLD > in_SQLDA^.SQLN then
  482. DatabaseError(SParameterCountIncorrect,self);
  483. {$R-}
  484. for x := 0 to in_SQLDA^.SQLD - 1 do with in_SQLDA^.SQLVar[x] do
  485. begin
  486. if ((SQLType and not 1) = SQL_VARYING) then
  487. SQLData := AllocMem(in_SQLDA^.SQLVar[x].SQLLen+2)
  488. else
  489. SQLData := AllocMem(in_SQLDA^.SQLVar[x].SQLLen);
  490. // Always force the creation of slqind for parameters. It could be
  491. // that a database-trigger takes care of inserting null-values, so
  492. // it should always be possible to pass null-parameters. If that fails,
  493. // the database-server will generate the appropiate error.
  494. sqltype := sqltype or 1;
  495. new(sqlind);
  496. end;
  497. {$R+}
  498. end
  499. else
  500. AllocSQLDA(in_SQLDA,0);
  501. // Get the statement type from firebird/interbase
  502. info_request := chr(isc_info_sql_stmt_type);
  503. if isc_dsql_sql_info(@Status[0],@Statement,Length(info_request), @info_request[1],sizeof(resbuf),@resbuf) <> 0 then
  504. CheckError('PrepareStatement', Status);
  505. assert(resbuf[0]=isc_info_sql_stmt_type);
  506. BlockSize:=isc_vax_integer(@resbuf[1],2);
  507. IBStatementType:=isc_vax_integer(@resbuf[3],blockSize);
  508. assert(resbuf[3+blockSize]=isc_info_end);
  509. // If the statementtype is isc_info_sql_stmt_exec_procedure then
  510. // override the statement type derrived by parsing the query.
  511. // This to recognize statements like 'insert into .. returning' correctly
  512. if IBStatementType = isc_info_sql_stmt_exec_procedure then
  513. FStatementType := stExecProcedure;
  514. if FStatementType in [stSelect,stExecProcedure] then
  515. begin
  516. if isc_dsql_describe(@Status[0], @Statement, 1, SQLDA) <> 0 then
  517. CheckError('PrepareSelect', Status);
  518. if SQLDA^.SQLD > SQLDA^.SQLN then
  519. begin
  520. AllocSQLDA(SQLDA,SQLDA^.SQLD);
  521. if isc_dsql_describe(@Status[0], @Statement, 1, SQLDA) <> 0 then
  522. CheckError('PrepareSelect', Status);
  523. end;
  524. {$R-}
  525. for x := 0 to SQLDA^.SQLD - 1 do with SQLDA^.SQLVar[x] do
  526. begin
  527. if ((SQLType and not 1) = SQL_VARYING) then
  528. SQLData := AllocMem(SQLDA^.SQLVar[x].SQLLen+2)
  529. else
  530. SQLData := AllocMem(SQLDA^.SQLVar[x].SQLLen);
  531. if (SQLType and 1) = 1 then New(SQLInd);
  532. end;
  533. {$R+}
  534. end;
  535. FPrepared := True;
  536. end;
  537. end;
  538. procedure TIBConnection.UnPrepareStatement(cursor : TSQLCursor);
  539. begin
  540. with cursor as TIBcursor do
  541. if assigned(Statement) Then
  542. begin
  543. if isc_dsql_free_statement(@Status[0], @Statement, DSQL_Drop) <> 0 then
  544. CheckError('FreeStatement', Status);
  545. Statement := nil;
  546. FPrepared := False;
  547. end;
  548. end;
  549. procedure TIBConnection.FreeSQLDABuffer(var aSQLDA : PXSQLDA);
  550. var x : Smallint;
  551. begin
  552. {$R-}
  553. if assigned(aSQLDA) then
  554. for x := 0 to aSQLDA^.SQLN - 1 do
  555. begin
  556. reAllocMem(aSQLDA^.SQLVar[x].SQLData,0);
  557. if assigned(aSQLDA^.SQLVar[x].sqlind) then
  558. begin
  559. Dispose(aSQLDA^.SQLVar[x].sqlind);
  560. aSQLDA^.SQLVar[x].sqlind := nil;
  561. end
  562. end;
  563. {$R+}
  564. end;
  565. function TIBConnection.IsDialectStored: boolean;
  566. begin
  567. result := (FDialect<>-1);
  568. end;
  569. procedure TIBConnection.DoConnect;
  570. const NoQuotes: TQuoteChars = (' ',' ');
  571. begin
  572. inherited DoConnect;
  573. FDBDialect := GetDBDialect;
  574. if Dialect < 3 then
  575. FieldNameQuoteChars := NoQuotes
  576. else
  577. FieldNameQuoteChars := DoubleQuotes;
  578. end;
  579. procedure TIBConnection.FreeFldBuffers(cursor : TSQLCursor);
  580. begin
  581. with cursor as TIBCursor do
  582. begin
  583. FreeSQLDABuffer(SQLDA);
  584. FreeSQLDABuffer(in_SQLDA);
  585. SetLength(FieldBinding,0);
  586. end;
  587. end;
  588. procedure TIBConnection.Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams);
  589. var tr : pointer;
  590. out_SQLDA : PXSQLDA;
  591. begin
  592. tr := aTransaction.Handle;
  593. if Assigned(APArams) and (AParams.count > 0) then SetParameters(cursor, atransaction, AParams);
  594. with cursor as TIBCursor do
  595. begin
  596. if FStatementType = stExecProcedure then
  597. out_SQLDA := SQLDA
  598. else
  599. out_SQLDA := nil;
  600. if isc_dsql_execute2(@Status[0], @tr, @Statement, 1, in_SQLDA, out_SQLDA) <> 0 then
  601. CheckError('Execute', Status);
  602. end;
  603. end;
  604. procedure TIBConnection.AddFieldDefs(cursor: TSQLCursor;FieldDefs : TfieldDefs);
  605. var
  606. x : integer;
  607. TransLen : word;
  608. TransType : TFieldType;
  609. FD : TFieldDef;
  610. begin
  611. {$R-}
  612. with cursor as TIBCursor do
  613. begin
  614. setlength(FieldBinding,SQLDA^.SQLD);
  615. for x := 0 to SQLDA^.SQLD - 1 do
  616. begin
  617. TranslateFldType(SQLDA^.SQLVar[x].SQLType, SQLDA^.SQLVar[x].sqlsubtype, SQLDA^.SQLVar[x].SQLLen, SQLDA^.SQLVar[x].SQLScale,
  618. TransType, TransLen);
  619. FD := TFieldDef.Create(FieldDefs, FieldDefs.MakeNameUnique(SQLDA^.SQLVar[x].AliasName), TransType,
  620. TransLen, (SQLDA^.SQLVar[x].sqltype and 1)=0, (x + 1));
  621. if TransType in [ftBCD, ftFmtBCD] then
  622. case (SQLDA^.SQLVar[x].sqltype and not 1) of
  623. SQL_SHORT : FD.precision := 4;
  624. SQL_LONG : FD.precision := 9;
  625. SQL_DOUBLE,
  626. SQL_INT64 : FD.precision := 18;
  627. else FD.precision := SQLDA^.SQLVar[x].SQLLen;
  628. end;
  629. // FD.DisplayName := SQLDA^.SQLVar[x].AliasName;
  630. FieldBinding[FD.FieldNo-1] := x;
  631. end;
  632. end;
  633. {$R+}
  634. end;
  635. function TIBConnection.GetHandle: pointer;
  636. begin
  637. Result := FSQLDatabaseHandle;
  638. end;
  639. function TIBConnection.Fetch(cursor : TSQLCursor) : boolean;
  640. var
  641. retcode : integer;
  642. begin
  643. with cursor as TIBCursor do
  644. begin
  645. if FStatementType = stExecProcedure then
  646. //it is not recommended fetch from non-select statement, i.e. statement which have no cursor
  647. //starting from Firebird 2.5 it leads to error 'Invalid cursor reference'
  648. if SQLDA^.SQLD = 0 then
  649. retcode := 100 //no more rows to retrieve
  650. else
  651. begin
  652. retcode := 0;
  653. SQLDA^.SQLD := 0; //hack: mark after first fetch
  654. end
  655. else
  656. retcode := isc_dsql_fetch(@Status[0], @Statement, 1, SQLDA);
  657. if (retcode <> 0) and (retcode <> 100) then
  658. CheckError('Fetch', Status);
  659. end;
  660. Result := (retcode = 0);
  661. end;
  662. function IntPower10(e: integer): double;
  663. const PreComputedPower10: array[0..9] of integer = (1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000);
  664. var n: integer;
  665. begin
  666. n := abs(e); //exponent can't be greater than 18
  667. if n <= 9 then
  668. Result := PreComputedPower10[n]
  669. else
  670. Result := PreComputedPower10[9] * PreComputedPower10[n-9];
  671. if e < 0 then
  672. Result := 1 / Result;
  673. end;
  674. procedure TIBConnection.SetParameters(cursor : TSQLCursor; aTransation : TSQLTransaction; AParams : TParams);
  675. var ParNr,SQLVarNr : integer;
  676. s : string;
  677. i : integer;
  678. si : smallint;
  679. li : LargeInt;
  680. currbuff : pchar;
  681. w : word;
  682. TransactionHandle : pointer;
  683. blobId : ISC_QUAD;
  684. blobHandle : Isc_blob_Handle;
  685. BlobSize,
  686. BlobBytesWritten : longint;
  687. procedure SetBlobParam;
  688. begin
  689. {$R-}
  690. with cursor as TIBCursor do
  691. begin
  692. TransactionHandle := aTransation.Handle;
  693. blobhandle := FB_API_NULLHANDLE;
  694. if isc_create_blob(@FStatus[0], @FSQLDatabaseHandle, @TransactionHandle, @blobHandle, @blobId) <> 0 then
  695. CheckError('TIBConnection.CreateBlobStream', FStatus);
  696. s := AParams[ParNr].AsString;
  697. BlobSize := length(s);
  698. BlobBytesWritten := 0;
  699. i := 0;
  700. // Write in segments of MAXBLOBSEGMENTSIZE, as that is the fastest.
  701. // We ignore BlobSegmentSize property.
  702. while BlobBytesWritten < (BlobSize-MAXBLOBSEGMENTSIZE) do
  703. begin
  704. isc_put_segment(@FStatus[0], @blobHandle, MAXBLOBSEGMENTSIZE, @s[(i*MAXBLOBSEGMENTSIZE)+1]);
  705. inc(BlobBytesWritten,MAXBLOBSEGMENTSIZE);
  706. inc(i);
  707. end;
  708. if BlobBytesWritten <> BlobSize then
  709. isc_put_segment(@FStatus[0], @blobHandle, BlobSize-BlobBytesWritten, @s[(i*MAXBLOBSEGMENTSIZE)+1]);
  710. if isc_close_blob(@FStatus[0], @blobHandle) <> 0 then
  711. CheckError('TIBConnection.CreateBlobStream isc_close_blob', FStatus);
  712. Move(blobId, in_sqlda^.SQLvar[SQLVarNr].SQLData^, in_SQLDA^.SQLVar[SQLVarNr].SQLLen);
  713. end;
  714. {$R+}
  715. end;
  716. var
  717. // This should be a pointer, because the ORIGINAL variables must
  718. // be modified.
  719. VSQLVar: ^XSQLVAR;
  720. begin
  721. {$R-}
  722. with cursor as TIBCursor do for SQLVarNr := 0 to High(ParamBinding){AParams.count-1} do
  723. begin
  724. ParNr := ParamBinding[SQLVarNr];
  725. VSQLVar := @in_sqlda^.SQLvar[SQLVarNr];
  726. if AParams[ParNr].IsNull then
  727. VSQLVar^.SQLInd^ := -1
  728. else
  729. begin
  730. VSQLVar^.SQLInd^ := 0;
  731. case (VSQLVar^.sqltype and not 1) of
  732. SQL_LONG :
  733. begin
  734. if VSQLVar^.sqlscale = 0 then
  735. i := AParams[ParNr].AsInteger
  736. else
  737. i := Round(AParams[ParNr].AsCurrency * IntPower10(-VSQLVar^.sqlscale));
  738. Move(i, VSQLVar^.SQLData^, VSQLVar^.SQLLen);
  739. end;
  740. SQL_SHORT :
  741. begin
  742. if VSQLVar^.sqlscale = 0 then
  743. si := AParams[ParNr].AsSmallint
  744. else
  745. si := Round(AParams[ParNr].AsCurrency * IntPower10(-VSQLVar^.sqlscale));
  746. i := si;
  747. Move(i, VSQLVar^.SQLData^, VSQLVar^.SQLLen);
  748. end;
  749. SQL_BLOB :
  750. SetBlobParam;
  751. SQL_VARYING, SQL_TEXT :
  752. begin
  753. s := AParams[ParNr].AsString;
  754. w := length(s); // a word is enough, since the max-length of a string in interbase is 32k
  755. if ((VSQLVar^.SQLType and not 1) = SQL_VARYING) then
  756. begin
  757. VSQLVar^.SQLLen := w;
  758. ReAllocMem(VSQLVar^.SQLData, VSQLVar^.SQLLen+2);
  759. CurrBuff := VSQLVar^.SQLData;
  760. move(w,CurrBuff^,sizeof(w));
  761. inc(CurrBuff,2);
  762. end
  763. else
  764. begin
  765. // The buffer-length is always VSQLVar^.sqllen, nothing more, nothing less
  766. // so fill the complete buffer with valid data. Adding #0 will lead
  767. // to problems, because the #0 will be seen as a part of the (binary) string
  768. CurrBuff := VSQLVar^.SQLData;
  769. w := VSQLVar^.sqllen;
  770. s := PadRight(s,w);
  771. end;
  772. Move(s[1], CurrBuff^, w);
  773. end;
  774. SQL_TYPE_DATE, SQL_TYPE_TIME, SQL_TIMESTAMP :
  775. SetDateTime(VSQLVar^.SQLData, AParams[ParNr].AsDateTime, VSQLVar^.SQLType);
  776. SQL_INT64:
  777. begin
  778. if VSQLVar^.sqlscale = 0 then
  779. li := AParams[ParNr].AsLargeInt
  780. else if AParams[ParNr].DataType = ftFMTBcd then
  781. li := AParams[ParNr].AsFMTBCD * IntPower10(-VSQLVar^.sqlscale)
  782. else
  783. li := Round(AParams[ParNr].AsCurrency * IntPower10(-VSQLVar^.sqlscale));
  784. Move(li, VSQLVar^.SQLData^, VSQLVar^.SQLLen);
  785. end;
  786. SQL_DOUBLE, SQL_FLOAT:
  787. SetFloat(VSQLVar^.SQLData, AParams[ParNr].AsFloat, VSQLVar^.SQLLen);
  788. else
  789. DatabaseErrorFmt(SUnsupportedParameter,[Fieldtypenames[AParams[ParNr].DataType]],self);
  790. end {case}
  791. end;
  792. end;
  793. {$R+}
  794. end;
  795. function TIBConnection.LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  796. var
  797. x : integer;
  798. VarcharLen : word;
  799. CurrBuff : pchar;
  800. c : currency;
  801. AFmtBcd : tBCD;
  802. function BcdDivPower10(Dividend: largeint; e: integer): TBCD;
  803. var d: double;
  804. begin
  805. d := Dividend / IntPower10(e);
  806. Result := StrToBCD( FloatToStr(d) );
  807. end;
  808. begin
  809. CreateBlob := False;
  810. with cursor as TIBCursor do
  811. begin
  812. {$R-}
  813. x := FieldBinding[FieldDef.FieldNo-1];
  814. // Joost, 5 jan 2006: I disabled the following, since it's useful for
  815. // debugging, but it also slows things down. In principle things can only go
  816. // wrong when FieldDefs is changed while the dataset is opened. A user just
  817. // shoudn't do that. ;) (The same is done in PQConnection)
  818. // if SQLDA^.SQLVar[x].AliasName <> FieldDef.Name then
  819. // DatabaseErrorFmt(SFieldNotFound,[FieldDef.Name],self);
  820. if assigned(SQLDA^.SQLVar[x].SQLInd) and (SQLDA^.SQLVar[x].SQLInd^ = -1) then
  821. result := false
  822. else
  823. begin
  824. with SQLDA^.SQLVar[x] do
  825. if ((SQLType and not 1) = SQL_VARYING) then
  826. begin
  827. Move(SQLData^, VarcharLen, 2);
  828. CurrBuff := SQLData + 2;
  829. end
  830. else
  831. begin
  832. CurrBuff := SQLData;
  833. VarCharLen := FieldDef.Size;
  834. end;
  835. Result := true;
  836. case FieldDef.DataType of
  837. ftBCD :
  838. begin
  839. case SQLDA^.SQLVar[x].SQLLen of
  840. 2 : c := PSmallint(CurrBuff)^ / IntPower10(-SQLDA^.SQLVar[x].SQLScale);
  841. 4 : c := PLongint(CurrBuff)^ / IntPower10(-SQLDA^.SQLVar[x].SQLScale);
  842. 8 : if Dialect < 3 then
  843. c := PDouble(CurrBuff)^
  844. else
  845. c := PLargeint(CurrBuff)^ / IntPower10(-SQLDA^.SQLVar[x].SQLScale);
  846. else
  847. Result := False; // Just to be sure, in principle this will never happen
  848. end; {case}
  849. Move(c, buffer^ , sizeof(c));
  850. end;
  851. ftFMTBcd :
  852. begin
  853. case SQLDA^.SQLVar[x].SQLLen of
  854. 2 : AFmtBcd := BcdDivPower10(PSmallint(CurrBuff)^, -SQLDA^.SQLVar[x].SQLScale);
  855. 4 : AFmtBcd := BcdDivPower10(PLongint(CurrBuff)^, -SQLDA^.SQLVar[x].SQLScale);
  856. 8 : if Dialect < 3 then
  857. AFmtBcd := PDouble(CurrBuff)^
  858. else
  859. AFmtBcd := BcdDivPower10(PLargeint(CurrBuff)^, -SQLDA^.SQLVar[x].SQLScale);
  860. else
  861. Result := False; // Just to be sure, in principle this will never happen
  862. end; {case}
  863. Move(AFmtBcd, buffer^ , sizeof(AFmtBcd));
  864. end;
  865. ftInteger :
  866. begin
  867. FillByte(buffer^,sizeof(Longint),0);
  868. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  869. end;
  870. ftLargeint :
  871. begin
  872. FillByte(buffer^,sizeof(LargeInt),0);
  873. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  874. end;
  875. ftSmallint :
  876. begin
  877. FillByte(buffer^,sizeof(Smallint),0);
  878. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  879. end;
  880. ftDate, ftTime, ftDateTime:
  881. GetDateTime(CurrBuff, Buffer, SQLDA^.SQLVar[x].SQLType);
  882. ftString, ftFixedChar :
  883. begin
  884. Move(CurrBuff^, Buffer^, VarCharLen);
  885. PChar(Buffer + VarCharLen)^ := #0;
  886. end;
  887. ftFloat :
  888. GetFloat(CurrBuff, Buffer, SQLDA^.SQLVar[x].SQLLen);
  889. ftBlob,
  890. ftMemo :
  891. begin // load the BlobIb in field's buffer
  892. FillByte(buffer^,sizeof(TBufBlobField),0);
  893. Move(CurrBuff^, Buffer^, SQLDA^.SQLVar[x].SQLLen);
  894. end;
  895. else
  896. begin
  897. result := false;
  898. databaseerrorfmt(SUnsupportedFieldType, [Fieldtypenames[FieldDef.DataType], Self]);
  899. end
  900. end; { case }
  901. end; { if/else }
  902. {$R+}
  903. end; { with cursor }
  904. end;
  905. {$DEFINE SUPPORT_MSECS}
  906. {$IFDEF SUPPORT_MSECS}
  907. const
  908. IBDateOffset = 15018; //an offset from 17 Nov 1858.
  909. IBSecsCount = SecsPerDay * 10000; //count of 1/10000 seconds since midnight.
  910. {$ENDIF}
  911. procedure TIBConnection.GetDateTime(CurrBuff, Buffer : pointer; AType : integer);
  912. var
  913. {$IFNDEF SUPPORT_MSECS}
  914. CTime : TTm; // C struct time
  915. STime : TSystemTime; // System time
  916. {$ENDIF}
  917. PTime : TDateTime; // Pascal time
  918. begin
  919. case (AType and not 1) of
  920. SQL_TYPE_DATE :
  921. {$IFNDEF SUPPORT_MSECS}
  922. isc_decode_sql_date(PISC_DATE(CurrBuff), @CTime);
  923. {$ELSE}
  924. PTime := PISC_DATE(CurrBuff)^ - IBDateOffset;
  925. {$ENDIF}
  926. SQL_TYPE_TIME :
  927. {$IFNDEF SUPPORT_MSECS}
  928. isc_decode_sql_time(PISC_TIME(CurrBuff), @CTime);
  929. {$ELSE}
  930. PTime := PISC_TIME(CurrBuff)^ / IBSecsCount;
  931. {$ENDIF}
  932. SQL_TIMESTAMP :
  933. begin
  934. {$IFNDEF SUPPORT_MSECS}
  935. isc_decode_timestamp(PISC_TIMESTAMP(CurrBuff), @CTime);
  936. {$ELSE}
  937. PTime := ComposeDateTime(
  938. PISC_TIMESTAMP(CurrBuff)^.timestamp_date - IBDateOffset,
  939. PISC_TIMESTAMP(CurrBuff)^.timestamp_time / IBSecsCount
  940. );
  941. {$ENDIF}
  942. end
  943. else
  944. Raise EIBDatabaseError.CreateFmt('Invalid parameter type for date Decode : %d',[(AType and not 1)]);
  945. end;
  946. {$IFNDEF SUPPORT_MSECS}
  947. STime.Year := CTime.tm_year + 1900;
  948. STime.Month := CTime.tm_mon + 1;
  949. STime.Day := CTime.tm_mday;
  950. STime.Hour := CTime.tm_hour;
  951. STime.Minute := CTime.tm_min;
  952. STime.Second := CTime.tm_sec;
  953. STime.Millisecond := 0;
  954. PTime := SystemTimeToDateTime(STime);
  955. {$ENDIF}
  956. Move(PTime, Buffer^, SizeOf(PTime));
  957. end;
  958. procedure TIBConnection.SetDateTime(CurrBuff: pointer; PTime : TDateTime; AType : integer);
  959. {$IFNDEF SUPPORT_MSECS}
  960. var
  961. CTime : TTm; // C struct time
  962. STime : TSystemTime; // System time
  963. {$ENDIF}
  964. begin
  965. {$IFNDEF SUPPORT_MSECS}
  966. DateTimeToSystemTime(PTime,STime);
  967. CTime.tm_year := STime.Year - 1900;
  968. CTime.tm_mon := STime.Month -1;
  969. CTime.tm_mday := STime.Day;
  970. CTime.tm_hour := STime.Hour;
  971. CTime.tm_min := STime.Minute;
  972. CTime.tm_sec := STime.Second;
  973. {$ENDIF}
  974. case (AType and not 1) of
  975. SQL_TYPE_DATE :
  976. {$IFNDEF SUPPORT_MSECS}
  977. isc_encode_sql_date(@CTime, PISC_DATE(CurrBuff));
  978. {$ELSE}
  979. PISC_DATE(CurrBuff)^ := Trunc(PTime) + IBDateOffset;
  980. {$ENDIF}
  981. SQL_TYPE_TIME :
  982. {$IFNDEF SUPPORT_MSECS}
  983. isc_encode_sql_time(@CTime, PISC_TIME(CurrBuff));
  984. {$ELSE}
  985. PISC_TIME(CurrBuff)^ := Trunc(abs(Frac(PTime)) * IBSecsCount);
  986. {$ENDIF}
  987. SQL_TIMESTAMP :
  988. begin
  989. {$IFNDEF SUPPORT_MSECS}
  990. isc_encode_timestamp(@CTime, PISC_TIMESTAMP(CurrBuff));
  991. {$ELSE}
  992. PISC_TIMESTAMP(CurrBuff)^.timestamp_date := Trunc(PTime) + IBDateOffset;
  993. PISC_TIMESTAMP(CurrBuff)^.timestamp_time := Trunc(abs(Frac(PTime)) * IBSecsCount);
  994. {$ENDIF}
  995. end
  996. else
  997. Raise EIBDatabaseError.CreateFmt('Invalid parameter type for date encode : %d',[(AType and not 1)]);
  998. end;
  999. end;
  1000. function TIBConnection.GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string;
  1001. var s : string;
  1002. begin
  1003. case SchemaType of
  1004. stTables : s := 'select '+
  1005. 'rdb$relation_id as recno, '+
  1006. '''' + DatabaseName + ''' as catalog_name, '+
  1007. ''''' as schema_name, '+
  1008. 'rdb$relation_name as table_name, '+
  1009. '0 as table_type '+
  1010. 'from '+
  1011. 'rdb$relations '+
  1012. 'where '+
  1013. '(rdb$system_flag = 0 or rdb$system_flag is null) ' + // and rdb$view_blr is null
  1014. 'order by rdb$relation_name';
  1015. stSysTables : s := 'select '+
  1016. 'rdb$relation_id as recno, '+
  1017. '''' + DatabaseName + ''' as catalog_name, '+
  1018. ''''' as schema_name, '+
  1019. 'rdb$relation_name as table_name, '+
  1020. '0 as table_type '+
  1021. 'from '+
  1022. 'rdb$relations '+
  1023. 'where '+
  1024. '(rdb$system_flag > 0) ' + // and rdb$view_blr is null
  1025. 'order by rdb$relation_name';
  1026. stProcedures : s := 'select '+
  1027. 'rdb$procedure_id as recno, '+
  1028. '''' + DatabaseName + ''' as catalog_name, '+
  1029. ''''' as schema_name, '+
  1030. 'rdb$procedure_name as proc_name, '+
  1031. '0 as proc_type, '+
  1032. 'rdb$procedure_inputs as in_params, '+
  1033. 'rdb$procedure_outputs as out_params '+
  1034. 'from '+
  1035. 'rdb$procedures '+
  1036. 'WHERE '+
  1037. '(rdb$system_flag = 0 or rdb$system_flag is null)';
  1038. stColumns : s := 'select '+
  1039. 'rdb$field_id as recno, '+
  1040. '''' + DatabaseName + ''' as catalog_name, '+
  1041. ''''' as schema_name, '+
  1042. 'rdb$relation_name as table_name, '+
  1043. 'rdb$field_name as column_name, '+
  1044. 'rdb$field_position as column_position, '+
  1045. '0 as column_type, '+
  1046. '0 as column_datatype, '+
  1047. ''''' as column_typename, '+
  1048. '0 as column_subtype, '+
  1049. '0 as column_precision, '+
  1050. '0 as column_scale, '+
  1051. '0 as column_length, '+
  1052. '0 as column_nullable '+
  1053. 'from '+
  1054. 'rdb$relation_fields '+
  1055. 'WHERE '+
  1056. '(rdb$system_flag = 0 or rdb$system_flag is null) and (rdb$relation_name = ''' + Uppercase(SchemaObjectName) + ''') ' +
  1057. 'order by rdb$field_name';
  1058. else
  1059. DatabaseError(SMetadataUnavailable)
  1060. end; {case}
  1061. result := s;
  1062. end;
  1063. procedure TIBConnection.UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string);
  1064. var qry : TSQLQuery;
  1065. begin
  1066. if not assigned(Transaction) then
  1067. DatabaseError(SErrConnTransactionnSet);
  1068. qry := tsqlquery.Create(nil);
  1069. qry.transaction := Transaction;
  1070. qry.database := Self;
  1071. with qry do
  1072. begin
  1073. ReadOnly := True;
  1074. sql.clear;
  1075. sql.add('select '+
  1076. 'ind.rdb$index_name, '+
  1077. 'ind.rdb$relation_name, '+
  1078. 'ind.rdb$unique_flag, '+
  1079. 'ind_seg.rdb$field_name, '+
  1080. 'rel_con.rdb$constraint_type, '+
  1081. 'ind.rdb$index_type '+
  1082. 'from '+
  1083. 'rdb$index_segments ind_seg, '+
  1084. 'rdb$indices ind '+
  1085. 'left outer join '+
  1086. 'rdb$relation_constraints rel_con '+
  1087. 'on '+
  1088. 'rel_con.rdb$index_name = ind.rdb$index_name '+
  1089. 'where '+
  1090. '(ind_seg.rdb$index_name = ind.rdb$index_name) and '+
  1091. '(ind.rdb$relation_name=''' + UpperCase(TableName) +''') '+
  1092. 'order by '+
  1093. 'ind.rdb$index_name;');
  1094. open;
  1095. end;
  1096. while not qry.eof do with IndexDefs.AddIndexDef do
  1097. begin
  1098. Name := trim(qry.fields[0].asstring);
  1099. Fields := trim(qry.Fields[3].asstring);
  1100. If qry.fields[4].asstring = 'PRIMARY KEY' then options := options + [ixPrimary];
  1101. If qry.fields[2].asinteger = 1 then options := options + [ixUnique];
  1102. If qry.fields[5].asInteger = 1 then options:=options+[ixDescending];
  1103. qry.next;
  1104. while (name = trim(qry.fields[0].asstring)) and (not qry.eof) do
  1105. begin
  1106. Fields := Fields + ';' + trim(qry.Fields[3].asstring);
  1107. qry.next;
  1108. end;
  1109. end;
  1110. qry.close;
  1111. qry.free;
  1112. end;
  1113. procedure TIBConnection.SetFloat(CurrBuff: pointer; Dbl: Double; Size: integer);
  1114. var
  1115. Ext : extended;
  1116. Sin : single;
  1117. begin
  1118. case Size of
  1119. 4 :
  1120. begin
  1121. Sin := Dbl;
  1122. Move(Sin, CurrBuff^, 4);
  1123. end;
  1124. 8 :
  1125. begin
  1126. Move(Dbl, CurrBuff^, 8);
  1127. end;
  1128. 10:
  1129. begin
  1130. Ext := Dbl;
  1131. Move(Ext, CurrBuff^, 10);
  1132. end;
  1133. else
  1134. Raise EIBDatabaseError.CreateFmt('Invalid float size for float encode : %d',[Size]);
  1135. end;
  1136. end;
  1137. procedure TIBConnection.GetFloat(CurrBuff, Buffer : pointer; Size : byte);
  1138. var
  1139. Ext : extended;
  1140. Dbl : double;
  1141. Sin : single;
  1142. begin
  1143. case Size of
  1144. 4 :
  1145. begin
  1146. Move(CurrBuff^, Sin, 4);
  1147. Dbl := Sin;
  1148. end;
  1149. 8 :
  1150. begin
  1151. Move(CurrBuff^, Dbl, 8);
  1152. end;
  1153. 10:
  1154. begin
  1155. Move(CurrBuff^, Ext, 10);
  1156. Dbl := double(Ext);
  1157. end;
  1158. else
  1159. Raise EIBDatabaseError.CreateFmt('Invalid float size for float Decode : %d',[Size]);
  1160. end;
  1161. Move(Dbl, Buffer^, 8);
  1162. end;
  1163. function TIBConnection.GetBlobSize(blobHandle: TIsc_Blob_Handle): LongInt;
  1164. var
  1165. iscInfoBlobTotalLength : byte;
  1166. blobInfo : array[0..50] of byte;
  1167. begin
  1168. iscInfoBlobTotalLength:=isc_info_blob_total_length;
  1169. if isc_blob_info(@Fstatus[0], @blobHandle, sizeof(iscInfoBlobTotalLength), pchar(@iscInfoBlobTotalLength), sizeof(blobInfo) - 2, pchar(@blobInfo[0])) <> 0 then
  1170. CheckError('isc_blob_info', FStatus);
  1171. if blobInfo[0] = iscInfoBlobTotalLength then
  1172. begin
  1173. result := isc_vax_integer(pchar(@blobInfo[3]), isc_vax_integer(pchar(@blobInfo[1]), 2));
  1174. end
  1175. else
  1176. CheckError('isc_blob_info', FStatus);
  1177. end;
  1178. procedure TIBConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction : TSQLTransaction);
  1179. const
  1180. isc_segstr_eof = 335544367; // It's not defined in ibase60 but in ibase40. Would it be better to define in ibase60?
  1181. var
  1182. blobHandle : Isc_blob_Handle;
  1183. blobSegment : pointer;
  1184. blobSegLen : word;
  1185. blobSize: LongInt;
  1186. TransactionHandle : pointer;
  1187. blobId : PISC_QUAD;
  1188. ptr : Pointer;
  1189. begin
  1190. blobId := PISC_QUAD(@(ABlobBuf^.ConnBlobBuffer));
  1191. TransactionHandle := Atransaction.Handle;
  1192. blobHandle := FB_API_NULLHANDLE;
  1193. if isc_open_blob(@FStatus[0], @FSQLDatabaseHandle, @TransactionHandle, @blobHandle, blobId) <> 0 then
  1194. CheckError('TIBConnection.CreateBlobStream', FStatus);
  1195. blobSize := GetBlobSize(blobHandle);
  1196. //For performance, read as much as we can, regardless of any segment size set in database.
  1197. blobSegment := AllocMem(MAXBLOBSEGMENTSIZE);
  1198. with ABlobBuf^.BlobBuffer^ do
  1199. begin
  1200. Size := 0;
  1201. // Test for Size is a workaround for Win64 Firebird embedded crashing in isc_get_segment when entire blob is read.
  1202. while (Size < blobSize) and (isc_get_segment(@FStatus[0], @blobHandle, @blobSegLen, MAXBLOBSEGMENTSIZE, blobSegment) = 0) do
  1203. begin
  1204. ReAllocMem(Buffer,Size+blobSegLen);
  1205. ptr := Buffer+Size;
  1206. move(blobSegment^,ptr^,blobSegLen);
  1207. inc(Size,blobSegLen);
  1208. end;
  1209. freemem(blobSegment);
  1210. // Throwing the proper error on failure is more important than closing the blob:
  1211. // Test for Size is another workaround.
  1212. if (Size = blobSize) or (FStatus[1] = isc_segstr_eof) then
  1213. begin
  1214. if isc_close_blob(@FStatus[0], @blobHandle) <> 0 then
  1215. CheckError('TIBConnection.CreateBlobStream isc_close_blob', FStatus);
  1216. end
  1217. else
  1218. CheckError('TIBConnection.CreateBlobStream isc_get_segment', FStatus);
  1219. end;
  1220. end;
  1221. function TIBConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  1222. var info_request : string;
  1223. resbuf : array[0..63] of byte;
  1224. i : integer;
  1225. BlockSize,
  1226. subBlockSize : integer;
  1227. SelectedRows,
  1228. InsertedRows : integer;
  1229. begin
  1230. SelectedRows:=-1;
  1231. InsertedRows:=-1;
  1232. if assigned(cursor) then with cursor as TIBCursor do
  1233. if assigned(statement) then
  1234. begin
  1235. info_request := chr(isc_info_sql_records);
  1236. if isc_dsql_sql_info(@Status[0],@Statement,Length(info_request), @info_request[1],sizeof(resbuf),@resbuf) <> 0 then
  1237. CheckError('RowsAffected', Status);
  1238. i := 0;
  1239. while not (byte(resbuf[i]) in [isc_info_end,isc_info_truncated]) do
  1240. begin
  1241. BlockSize:=isc_vax_integer(@resbuf[i+1],2);
  1242. if resbuf[i]=isc_info_sql_records then
  1243. begin
  1244. inc(i,3);
  1245. BlockSize:=BlockSize+i;
  1246. while (resbuf[i] <> isc_info_end) and (i < BlockSize) do
  1247. begin
  1248. subBlockSize:=isc_vax_integer(@resbuf[i+1],2);
  1249. if resbuf[i] = isc_info_req_select_count then
  1250. SelectedRows := isc_vax_integer(@resbuf[i+3],subBlockSize)
  1251. else if resbuf[i] = isc_info_req_insert_count then
  1252. InsertedRows := isc_vax_integer(@resbuf[i+3],subBlockSize);
  1253. inc(i,subBlockSize+3);
  1254. end;
  1255. end
  1256. else
  1257. inc(i,BlockSize+3);
  1258. end;
  1259. end;
  1260. if SelectedRows>0 then result:=SelectedRows
  1261. else Result:=InsertedRows;
  1262. end;
  1263. { TIBConnectionDef }
  1264. class function TIBConnectionDef.TypeName: String;
  1265. begin
  1266. Result:='Firebird';
  1267. end;
  1268. class function TIBConnectionDef.ConnectionClass: TSQLConnectionClass;
  1269. begin
  1270. Result:=TIBConnection;
  1271. end;
  1272. class function TIBConnectionDef.Description: String;
  1273. begin
  1274. Result:='Connect to Firebird/Interbase directly via the client library';
  1275. end;
  1276. class function TIBConnectionDef.DefaultLibraryName: String;
  1277. begin
  1278. If UseEmbeddedFirebird then
  1279. Result:=fbembedlib
  1280. else
  1281. Result:=fbclib
  1282. end;
  1283. class function TIBConnectionDef.LoadFunction: TLibraryLoadFunction;
  1284. begin
  1285. Result:=@InitialiseIBase60;
  1286. end;
  1287. class function TIBConnectionDef.UnLoadFunction: TLibraryUnLoadFunction;
  1288. begin
  1289. Result:=@ReleaseIBase60
  1290. end;
  1291. initialization
  1292. RegisterConnection(TIBConnectionDef);
  1293. finalization
  1294. UnRegisterConnection(TIBConnectionDef);
  1295. end.