ibconnection.pp 52 KB

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