ibconnection.pp 52 KB

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