ibconnection.pp 57 KB

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