ibconnection.pp 45 KB

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