ibconnection.pp 46 KB

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