odbcconn.pas 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. (******************************************************************************
  2. * *
  3. * (c) 2005 Hexis BV *
  4. * *
  5. * File: odbcconn.pas *
  6. * Author: Bram Kuijvenhoven ([email protected]) *
  7. * Description: ODBC SQLDB unit *
  8. * License: (modified) LGPL *
  9. * *
  10. ******************************************************************************)
  11. unit odbcconn;
  12. {$mode objfpc}{$H+}
  13. interface
  14. uses
  15. Classes, SysUtils, sqldb, db, odbcsqldyn
  16. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}, BufDataset{$ENDIF}
  17. ;
  18. type
  19. // forward declarations
  20. TODBCConnection = class;
  21. { TODBCCursor }
  22. TODBCCursor = class(TSQLCursor)
  23. protected
  24. FSTMTHandle:SQLHSTMT; // ODBC Statement Handle
  25. FQuery:string; // last prepared query, with :ParamName converted to ?
  26. FParamIndex:TParamBinding; // maps the i-th parameter in the query to the TParams passed to PrepareStatement
  27. FParamBuf:array of pointer; // buffers that can be used to bind the i-th parameter in the query
  28. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  29. FBlobStreams:TList; // list of Blob TMemoryStreams stored in field buffers (we need this currently as we can't hook into the freeing of TBufDataset buffers)
  30. {$ENDIF}
  31. public
  32. constructor Create(Connection:TODBCConnection);
  33. destructor Destroy; override;
  34. end;
  35. { TODBCHandle } // this name is a bit confusing, but follows the standards for naming classes in sqldb
  36. TODBCHandle = class(TSQLHandle)
  37. protected
  38. end;
  39. { TODBCEnvironment }
  40. TODBCEnvironment = class
  41. protected
  42. FENVHandle:SQLHENV; // ODBC Environment Handle
  43. public
  44. constructor Create;
  45. destructor Destroy; override;
  46. end;
  47. { TODBCConnection }
  48. TODBCConnection = class(TSQLConnection)
  49. private
  50. FDriver: string;
  51. FEnvironment:TODBCEnvironment;
  52. FDBCHandle:SQLHDBC; // ODBC Connection Handle
  53. FFileDSN: string;
  54. procedure SetParameters(ODBCCursor:TODBCCursor; AParams:TParams);
  55. procedure FreeParamBuffers(ODBCCursor:TODBCCursor);
  56. protected
  57. // Overrides from TSQLConnection
  58. function GetHandle:pointer; override;
  59. // - Connect/disconnect
  60. procedure DoInternalConnect; override;
  61. procedure DoInternalDisconnect; override;
  62. // - Handle (de)allocation
  63. function AllocateCursorHandle:TSQLCursor; override;
  64. procedure DeAllocateCursorHandle(var cursor:TSQLCursor); override;
  65. function AllocateTransactionHandle:TSQLHandle; override;
  66. // - Statement handling
  67. procedure PrepareStatement(cursor:TSQLCursor; ATransaction:TSQLTransaction; buf:string; AParams:TParams); override;
  68. procedure UnPrepareStatement(cursor:TSQLCursor); override;
  69. // - Transaction handling
  70. function GetTransactionHandle(trans:TSQLHandle):pointer; override;
  71. function StartDBTransaction(trans:TSQLHandle; AParams:string):boolean; override;
  72. function Commit(trans:TSQLHandle):boolean; override;
  73. function Rollback(trans:TSQLHandle):boolean; override;
  74. procedure CommitRetaining(trans:TSQLHandle); override;
  75. procedure RollbackRetaining(trans:TSQLHandle); override;
  76. // - Statement execution
  77. procedure Execute(cursor:TSQLCursor; ATransaction:TSQLTransaction; AParams:TParams); override;
  78. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  79. // - Result retrieving
  80. procedure AddFieldDefs(cursor:TSQLCursor; FieldDefs:TFieldDefs); override;
  81. function Fetch(cursor:TSQLCursor):boolean; override;
  82. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  83. function LoadField(cursor:TSQLCursor; FieldDef:TFieldDef; buffer:pointer; out CreateBlob : boolean):boolean; override;
  84. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction : TSQLTransaction); override;
  85. {$ELSE}
  86. function LoadField(cursor:TSQLCursor; FieldDef:TFieldDef; buffer:pointer):boolean; override;
  87. function CreateBlobStream(Field:TField; Mode:TBlobStreamMode):TStream; override;
  88. {$ENDIF}
  89. procedure FreeFldBuffers(cursor:TSQLCursor); override;
  90. // - UpdateIndexDefs
  91. procedure UpdateIndexDefs(IndexDefs:TIndexDefs; TableName:string); override;
  92. // - Schema info
  93. function GetSchemaInfoSQL(SchemaType:TSchemaType; SchemaObjectName, SchemaObjectPattern:string):string; override;
  94. // Internal utility functions
  95. function CreateConnectionString:string;
  96. public
  97. constructor Create(AOwner : TComponent); override;
  98. property Environment:TODBCEnvironment read FEnvironment;
  99. published
  100. property Driver:string read FDriver write FDriver; // will be passed as DRIVER connection parameter
  101. property FileDSN:string read FFileDSN write FFileDSN; // will be passed as FILEDSN parameter
  102. // Redeclare properties from TSQLConnection
  103. property Password; // will be passed as PWD connection parameter
  104. property Transaction;
  105. property UserName; // will be passed as UID connection parameter
  106. property CharSet;
  107. property HostName; // ignored
  108. // Redeclare properties from TDatabase
  109. property Connected;
  110. property Role;
  111. property DatabaseName; // will be passed as DSN connection parameter
  112. property KeepConnection;
  113. property LoginPrompt; // if true, ODBC drivers might prompt for more details that are not in the connection string
  114. property Params; // will be added to connection string
  115. property OnLogin;
  116. end;
  117. EODBCException = class(EDatabaseError)
  118. // currently empty; perhaps we can add fields here later that describe the error instead of one simple message string
  119. end;
  120. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  121. { TODBCConnectionDef }
  122. TODBCConnectionDef = Class(TConnectionDef)
  123. Class Function TypeName : String; override;
  124. Class Function ConnectionClass : TSQLConnectionClass; override;
  125. Class Function Description : String; override;
  126. end;
  127. {$ENDIF}
  128. implementation
  129. uses
  130. Math, DBConst, ctypes;
  131. const
  132. DefaultEnvironment:TODBCEnvironment = nil;
  133. ODBCLoadCount:integer = 0; // ODBC is loaded when > 0; modified by TODBCEnvironment.Create/Destroy
  134. { Generic ODBC helper functions }
  135. function ODBCSucces(const Res:SQLRETURN):boolean;
  136. begin
  137. Result:=(Res=SQL_SUCCESS) or (Res=SQL_SUCCESS_WITH_INFO);
  138. end;
  139. function ODBCResultToStr(Res:SQLRETURN):string;
  140. begin
  141. case Res of
  142. SQL_SUCCESS: Result:='SQL_SUCCESS';
  143. SQL_SUCCESS_WITH_INFO:Result:='SQL_SUCCESS_WITH_INFO';
  144. SQL_ERROR: Result:='SQL_ERROR';
  145. SQL_INVALID_HANDLE: Result:='SQL_INVALID_HANDLE';
  146. SQL_NO_DATA: Result:='SQL_NO_DATA';
  147. SQL_NEED_DATA: Result:='SQL_NEED_DATA';
  148. SQL_STILL_EXECUTING: Result:='SQL_STILL_EXECUTING';
  149. else
  150. Result:='';
  151. end;
  152. end;
  153. procedure ODBCCheckResult(LastReturnCode:SQLRETURN; HandleType:SQLSMALLINT; AHandle: SQLHANDLE; ErrorMsg: string; const FmtArgs:array of const);
  154. // check return value from SQLGetDiagField/Rec function itself
  155. procedure CheckSQLGetDiagResult(const Res:SQLRETURN);
  156. begin
  157. case Res of
  158. SQL_INVALID_HANDLE:
  159. raise EODBCException.Create('Invalid handle passed to SQLGetDiagRec/Field');
  160. SQL_ERROR:
  161. raise EODBCException.Create('An invalid parameter was passed to SQLGetDiagRec/Field');
  162. SQL_NO_DATA:
  163. raise EODBCException.Create('A too large RecNumber was passed to SQLGetDiagRec/Field');
  164. end;
  165. end;
  166. var
  167. NativeError:SQLINTEGER;
  168. TextLength:SQLSMALLINT;
  169. Res:SQLRETURN;
  170. SqlState,MessageText,TotalMessage:string;
  171. RecNumber:SQLSMALLINT;
  172. begin
  173. // check result
  174. if ODBCSucces(LastReturnCode) then
  175. Exit; // no error; all is ok
  176. //WriteLn('LastResultCode: ',ODBCResultToStr(LastReturnCode));
  177. try
  178. // build TotalMessage for exception to throw
  179. TotalMessage:=Format(ErrorMsg,FmtArgs)+Format(' ODBC error details: LastReturnCode: %s;',[ODBCResultToStr(LastReturnCode)]);
  180. // retrieve status records
  181. SetLength(SqlState,5); // SqlState buffer
  182. SetLength(MessageText,1);
  183. RecNumber:=1;
  184. repeat
  185. // dummy call to get correct TextLength
  186. //WriteLn('Getting error record ',RecNumber);
  187. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(MessageText[1]),0,TextLength);
  188. if Res=SQL_NO_DATA then
  189. Break; // no more status records
  190. CheckSQLGetDiagResult(Res);
  191. if TextLength>0 then // if TextLength=0 we don't need another call; also our string buffer would not point to a #0, but be a nil pointer
  192. begin
  193. // allocate large enough buffer
  194. SetLength(MessageText,TextLength); // note: ansistrings of Length>0 are always terminated by a #0 character, so this is safe
  195. // actual call
  196. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(MessageText[1]),Length(MessageText)+1,TextLength);
  197. CheckSQLGetDiagResult(Res);
  198. end;
  199. // add to TotalMessage
  200. TotalMessage:=TotalMessage+Format(' Record %d: SqlState: %s; NativeError: %d; Message: %s;',[RecNumber,SqlState,NativeError,MessageText]);
  201. // incement counter
  202. Inc(RecNumber);
  203. until false;
  204. except
  205. on E:EODBCException do begin
  206. TotalMessage:=TotalMessage+Format('Could not get error message: %s',[E.Message]);
  207. end
  208. end;
  209. // raise error
  210. raise EODBCException.Create(TotalMessage);
  211. end;
  212. procedure ODBCCheckResult(LastReturnCode:SQLRETURN; HandleType:SQLSMALLINT; AHandle: SQLHANDLE; ErrorMsg: string);
  213. begin
  214. ODBCCheckResult(LastReturnCode, HandleType, AHandle, ErrorMsg, []);
  215. end;
  216. { TODBCConnection }
  217. // Creates a connection string using the current value of the fields
  218. function TODBCConnection.CreateConnectionString: string;
  219. // encloses a param value with braces if necessary, i.e. when any of the characters []{}(),;?*=!@ is in the value
  220. function EscapeParamValue(const s:string):string;
  221. var
  222. NeedEscape:boolean;
  223. i:integer;
  224. begin
  225. NeedEscape:=false;
  226. for i:=1 to Length(s) do
  227. if s[i] in ['[',']','{','}','(',')',',','*','=','!','@'] then
  228. begin
  229. NeedEscape:=true;
  230. Break;
  231. end;
  232. if NeedEscape then
  233. Result:='{'+s+'}'
  234. else
  235. Result:=s;
  236. end;
  237. var
  238. i: Integer;
  239. Param: string;
  240. EqualSignPos:integer;
  241. begin
  242. Result:='';
  243. if DatabaseName<>'' then Result:=Result + 'DSN='+EscapeParamValue(DatabaseName)+';';
  244. if Driver <>'' then Result:=Result + 'DRIVER='+EscapeParamValue(Driver)+';';
  245. if UserName <>'' then Result:=Result + 'UID='+EscapeParamValue(UserName)+';PWD='+EscapeParamValue(Password)+';';
  246. if FileDSN <>'' then Result:=Result + 'FILEDSN='+EscapeParamValue(FileDSN)+'';
  247. for i:=0 to Params.Count-1 do
  248. begin
  249. Param:=Params[i];
  250. EqualSignPos:=Pos('=',Param);
  251. if EqualSignPos=0 then
  252. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; can''t find a ''='' in ''%s''',[i, Param])
  253. else if EqualSignPos=1 then
  254. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; no identifier before the ''='' in ''%s''',[i, Param])
  255. else
  256. Result:=Result + EscapeParamValue(Copy(Param,1,EqualSignPos-1))+'='+EscapeParamValue(Copy(Param,EqualSignPos+1,MaxInt))+';';
  257. end;
  258. end;
  259. constructor TODBCConnection.Create(AOwner: TComponent);
  260. begin
  261. inherited Create(AOwner);
  262. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  263. FConnOptions := FConnOptions + [sqEscapeRepeat] + [sqEscapeSlash];
  264. {$ENDIF}
  265. end;
  266. procedure TODBCConnection.SetParameters(ODBCCursor: TODBCCursor; AParams: TParams);
  267. var
  268. ParamIndex: integer;
  269. PVal, Buf, PStrLenOrInd: pointer;
  270. I, Size: integer;
  271. IntVal: clong;
  272. LargeVal: clonglong;
  273. StrVal: string;
  274. FloatVal: cdouble;
  275. DateVal: SQL_DATE_STRUCT;
  276. TimeStampVal: SQL_TIMESTAMP_STRUCT;
  277. BoolVal: byte;
  278. ColumnSize, BufferLength, StrLenOrInd: SQLINTEGER;
  279. CType, SqlType, DecimalDigits:SQLSMALLINT;
  280. begin
  281. // Note: it is assumed that AParams is the same as the one passed to PrepareStatement, in the sense that
  282. // the parameters have the same order and names
  283. if Length(ODBCCursor.FParamIndex)>0 then
  284. if not Assigned(AParams) then
  285. raise EODBCException.CreateFmt('The query has parameter markers in it, but no actual parameters were passed',[]);
  286. SetLength(ODBCCursor.FParamBuf, Length(ODBCCursor.FParamIndex));
  287. for i:=0 to High(ODBCCursor.FParamIndex) do
  288. begin
  289. ParamIndex:=ODBCCursor.FParamIndex[i];
  290. if (ParamIndex<0) or (ParamIndex>=AParams.Count) then
  291. raise EODBCException.CreateFmt('Parameter %d in query does not have a matching parameter set',[i]);
  292. DecimalDigits:=0;
  293. BufferLength:=0;
  294. StrLenOrInd:=0;
  295. case AParams[ParamIndex].DataType of
  296. ftInteger, ftSmallInt, ftWord, ftAutoInc:
  297. begin
  298. IntVal:=AParams[ParamIndex].AsInteger;
  299. PVal:=@IntVal;
  300. Size:=SizeOf(IntVal);
  301. CType:=SQL_C_LONG;
  302. SqlType:=SQL_INTEGER;
  303. ColumnSize:=10;
  304. end;
  305. ftLargeInt:
  306. begin
  307. LargeVal:=AParams[ParamIndex].AsLargeInt;
  308. PVal:=@LargeVal;
  309. Size:=SizeOf(LargeVal);
  310. CType:=SQL_C_SBIGINT;
  311. SqlType:=SQL_BIGINT;
  312. ColumnSize:=19;
  313. end;
  314. ftString, ftBlob, ftMemo:
  315. begin
  316. StrVal:=AParams[ParamIndex].AsString;
  317. StrLenOrInd:=Length(StrVal);
  318. if StrVal='' then //HY104
  319. begin
  320. StrVal:=#0;
  321. StrLenOrInd:=SQL_NTS;
  322. end;
  323. PVal:=@StrVal[1];
  324. Size:=Length(StrVal);
  325. ColumnSize:=Size;
  326. BufferLength:=Size;
  327. if AParams[ParamIndex].DataType = ftString then
  328. begin
  329. CType:=SQL_C_CHAR;
  330. SqlType:=SQL_LONGVARCHAR;
  331. end
  332. else // ftBlob, ftMemo
  333. begin
  334. CType:=SQL_C_BINARY;
  335. SqlType:=SQL_BINARY;
  336. end;
  337. end;
  338. ftFloat:
  339. begin
  340. FloatVal:=AParams[ParamIndex].AsFloat;
  341. PVal:=@FloatVal;
  342. Size:=SizeOf(FloatVal);
  343. CType:=SQL_C_DOUBLE;
  344. SqlType:=SQL_DOUBLE;
  345. ColumnSize:=15;
  346. end;
  347. ftDate:
  348. begin
  349. DateVal:=DateTimeToDateStruct(AParams[ParamIndex].AsDate);
  350. PVal:=@DateVal;
  351. Size:=SizeOf(DateVal);
  352. CType:=SQL_C_TYPE_DATE;
  353. SqlType:=SQL_TYPE_DATE;
  354. ColumnSize:=Size;
  355. end;
  356. ftDateTime:
  357. begin
  358. DateTime2TimeStampStruct(TimeStampVal, AParams[ParamIndex].AsDateTime);
  359. PVal:=@TimeStampVal;
  360. Size:=SizeOf(TimeStampVal);
  361. CType:=SQL_C_TYPE_TIMESTAMP;
  362. SqlType:=SQL_TYPE_TIMESTAMP;
  363. ColumnSize:=Size;
  364. end;
  365. ftBoolean:
  366. begin
  367. BoolVal:=ord(AParams[ParamIndex].AsBoolean);
  368. PVal:=@BoolVal;
  369. Size:=SizeOf(BoolVal);
  370. CType:=SQL_C_BIT;
  371. SqlType:=SQL_BIT;
  372. ColumnSize:=Size;
  373. end
  374. else
  375. raise EDataBaseError.CreateFmt('Parameter %d is of type %s, which not supported yet',[ParamIndex, Fieldtypenames[AParams[ParamIndex].DataType]]);
  376. end;
  377. if AParams[ParamIndex].IsNull then
  378. StrLenOrInd:=SQL_NULL_DATA;
  379. Buf:=GetMem(Size+SizeOf(SQLINTEGER));
  380. Move(PVal^, Buf^, Size);
  381. if StrLenOrInd<>0 then
  382. begin
  383. PStrLenOrInd:=Buf + Size;
  384. Move(StrLenOrInd, PStrLenOrInd^, SizeOf(SQLINTEGER));
  385. end
  386. else
  387. PStrLenOrInd:=nil;
  388. ODBCCursor.FParamBuf[i]:=Buf;
  389. ODBCCheckResult(
  390. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  391. i+1, // ParameterNumber
  392. SQL_PARAM_INPUT, // InputOutputType
  393. CType, // ValueType
  394. SqlType, // ParameterType
  395. ColumnSize, // ColumnSize
  396. DecimalDigits, // DecimalDigits
  397. Buf, // ParameterValuePtr
  398. BufferLength, // BufferLength
  399. PStrLenOrInd), // StrLen_or_IndPtr
  400. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not bind parameter %d.', [i]
  401. );
  402. end;
  403. end;
  404. procedure TODBCConnection.FreeParamBuffers(ODBCCursor: TODBCCursor);
  405. var
  406. i:integer;
  407. begin
  408. for i:=0 to High(ODBCCursor.FParamBuf) do
  409. FreeMem(ODBCCursor.FParamBuf[i]);
  410. SetLength(ODBCCursor.FParamBuf,0);
  411. end;
  412. function TODBCConnection.GetHandle: pointer;
  413. begin
  414. // I'm not sure whether this is correct; perhaps we should return nil
  415. // note that FDBHandle is a LongInt, because ODBC handles are integers, not pointers
  416. // I wonder how this will work on 64 bit platforms then (FK)
  417. Result:=pointer(PtrInt(FDBCHandle));
  418. end;
  419. procedure TODBCConnection.DoInternalConnect;
  420. const
  421. BufferLength = 1024; // should be at least 1024 according to the ODBC specification
  422. var
  423. ConnectionString:string;
  424. OutConnectionString:string;
  425. ActualLength:SQLSMALLINT;
  426. begin
  427. // Do not call the inherited method as it checks for a non-empty DatabaseName, and we don't even use DatabaseName!
  428. // inherited DoInternalConnect;
  429. // make sure we have an environment
  430. if not Assigned(FEnvironment) then
  431. begin
  432. if not Assigned(DefaultEnvironment) then
  433. DefaultEnvironment:=TODBCEnvironment.Create;
  434. FEnvironment:=DefaultEnvironment;
  435. end;
  436. // allocate connection handle
  437. ODBCCheckResult(
  438. SQLAllocHandle(SQL_HANDLE_DBC,Environment.FENVHandle,FDBCHandle),
  439. SQL_HANDLE_ENV,Environment.FENVHandle,'Could not allocate ODBC Connection handle.'
  440. );
  441. try
  442. // connect
  443. ConnectionString:=CreateConnectionString;
  444. SetLength(OutConnectionString,BufferLength-1); // allocate completed connection string buffer (using the ansistring #0 trick)
  445. ODBCCheckResult(
  446. SQLDriverConnect(FDBCHandle, // the ODBC connection handle
  447. nil, // no parent window (would be required for prompts)
  448. PChar(ConnectionString), // the connection string
  449. Length(ConnectionString), // connection string length
  450. @(OutConnectionString[1]),// buffer for storing the completed connection string
  451. BufferLength, // length of the buffer
  452. ActualLength, // the actual length of the completed connection string
  453. SQL_DRIVER_NOPROMPT), // don't prompt for password etc.
  454. SQL_HANDLE_DBC,FDBCHandle,'Could not connect with connection string "%s".',[ConnectionString]
  455. );
  456. except
  457. on E:Exception do begin
  458. // free connection handle
  459. ODBCCheckResult(
  460. SQLFreeHandle(SQL_HANDLE_DBC,FDBCHandle),
  461. SQL_HANDLE_DBC,FDBCHandle,'Could not free ODBC Connection handle.'
  462. );
  463. raise; // re-raise exception
  464. end;
  465. end;
  466. // commented out as the OutConnectionString is not used further at the moment
  467. // if ActualLength<BufferLength-1 then
  468. // SetLength(OutConnectionString,ActualLength); // fix completed connection string length
  469. // set connection attributes (none yet)
  470. end;
  471. procedure TODBCConnection.DoInternalDisconnect;
  472. var
  473. Res:SQLRETURN;
  474. begin
  475. inherited DoInternalDisconnect;
  476. // disconnect
  477. ODBCCheckResult(
  478. SQLDisconnect(FDBCHandle),
  479. SQL_HANDLE_DBC,FDBCHandle,'Could not disconnect.'
  480. );
  481. // deallocate connection handle
  482. Res:=SQLFreeHandle(SQL_HANDLE_DBC, FDBCHandle);
  483. if Res=SQL_ERROR then
  484. ODBCCheckResult(Res,SQL_HANDLE_DBC,FDBCHandle,'Could not free ODBC Connection handle.');
  485. end;
  486. function TODBCConnection.AllocateCursorHandle: TSQLCursor;
  487. begin
  488. Result:=TODBCCursor.Create(self);
  489. end;
  490. procedure TODBCConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  491. begin
  492. FreeAndNil(cursor); // the destructor of TODBCCursor frees the ODBC Statement handle
  493. end;
  494. function TODBCConnection.AllocateTransactionHandle: TSQLHandle;
  495. begin
  496. Result:=nil; // not yet supported; will move connection handles to transaction handles later
  497. end;
  498. procedure TODBCConnection.PrepareStatement(cursor: TSQLCursor; ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  499. var
  500. ODBCCursor:TODBCCursor;
  501. begin
  502. ODBCCursor:=cursor as TODBCCursor;
  503. // allocate statement handle
  504. ODBCCheckResult(
  505. SQLAllocHandle(SQL_HANDLE_STMT, FDBCHandle, ODBCCursor.FSTMTHandle),
  506. SQL_HANDLE_DBC, FDBCHandle, 'Could not allocate ODBC Statement handle.'
  507. );
  508. ODBCCursor.FPrepared:=True;
  509. // Parameter handling
  510. // Note: We can only pass ? parameters to ODBC, so we should convert named parameters like :MyID
  511. // ODBCCursor.FParamIndex will map th i-th ? token in the (modified) query to an index for AParams
  512. // Parse the SQL and build FParamIndex
  513. if assigned(AParams) and (AParams.count > 0) then
  514. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  515. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psInterbase,ODBCCursor.FParamIndex);
  516. {$ELSE}
  517. buf := AParams.ParseSQL(buf,false,psInterbase,ODBCCursor.FParamIndex);
  518. {$ENDIF}
  519. // prepare statement
  520. ODBCCursor.FQuery:=Buf;
  521. if ODBCCursor.FSchemaType=stNoSchema then
  522. begin
  523. ODBCCheckResult(
  524. SQLPrepare(ODBCCursor.FSTMTHandle, PChar(buf), Length(buf)),
  525. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not prepare statement.'
  526. );
  527. end
  528. else
  529. ODBCCursor.FStatementType:=stSelect;
  530. end;
  531. procedure TODBCConnection.UnPrepareStatement(cursor: TSQLCursor);
  532. var Res:SQLRETURN;
  533. begin
  534. with TODBCCursor(cursor) do
  535. begin
  536. if FSTMTHandle<>SQL_NULL_HSTMT then
  537. begin
  538. // deallocate statement handle
  539. Res:=SQLFreeHandle(SQL_HANDLE_STMT, FSTMTHandle);
  540. if Res=SQL_ERROR then
  541. ODBCCheckResult(Res,SQL_HANDLE_STMT, FSTMTHandle, 'Could not free ODBC Statement handle.');
  542. FSTMTHandle:=SQL_NULL_HSTMT;
  543. FPrepared := False;
  544. end;
  545. end;
  546. end;
  547. function TODBCConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  548. begin
  549. // Tranactions not implemented yet
  550. end;
  551. function TODBCConnection.StartDBTransaction(trans: TSQLHandle; AParams:string): boolean;
  552. begin
  553. // Tranactions not implemented yet
  554. end;
  555. function TODBCConnection.Commit(trans: TSQLHandle): boolean;
  556. begin
  557. // Tranactions not implemented yet
  558. end;
  559. function TODBCConnection.Rollback(trans: TSQLHandle): boolean;
  560. begin
  561. // Tranactions not implemented yet
  562. end;
  563. procedure TODBCConnection.CommitRetaining(trans: TSQLHandle);
  564. begin
  565. // Tranactions not implemented yet
  566. end;
  567. procedure TODBCConnection.RollbackRetaining(trans: TSQLHandle);
  568. begin
  569. // Tranactions not implemented yet
  570. end;
  571. procedure TODBCConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  572. var
  573. ODBCCursor:TODBCCursor;
  574. Res:SQLRETURN;
  575. begin
  576. ODBCCursor:=cursor as TODBCCursor;
  577. // set parameters
  578. if Assigned(APArams) and (AParams.count > 0) then SetParameters(ODBCCursor, AParams);
  579. // execute the statement
  580. case ODBCCursor.FSchemaType of
  581. stNoSchema : Res:=SQLExecute(ODBCCursor.FSTMTHandle); //SQL_NO_DATA returns searched update or delete statement that does not affect any rows
  582. stTables : Res:=SQLTables (ODBCCursor.FSTMTHandle, nil, 0, nil, 0, nil, 0, nil, 0 );
  583. stColumns : Res:=SQLColumns(ODBCCursor.FSTMTHandle, nil, 0, nil, 0, @ODBCCursor.FQuery[1], length(ODBCCursor.FQuery), nil, 0 );
  584. stProcedures: Res:=SQLProcedures(ODBCCursor.FSTMTHandle, nil, 0, nil, 0, nil, 0 );
  585. else Res:=SQL_NO_DATA;
  586. end; {case}
  587. if (Res<>SQL_NO_DATA) then ODBCCheckResult( Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not execute statement.' );
  588. // free parameter buffers
  589. FreeParamBuffers(ODBCCursor);
  590. end;
  591. function TODBCConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  592. var
  593. RowCount: SQLINTEGER;
  594. begin
  595. if assigned(cursor) then
  596. if ODBCSucces( SQLRowCount((cursor as TODBCCursor).FSTMTHandle, RowCount) ) then
  597. Result:=RowCount
  598. else
  599. Result:=-1
  600. else
  601. Result:=-1;
  602. end;
  603. function TODBCConnection.Fetch(cursor: TSQLCursor): boolean;
  604. var
  605. ODBCCursor:TODBCCursor;
  606. Res:SQLRETURN;
  607. begin
  608. ODBCCursor:=cursor as TODBCCursor;
  609. // fetch new row
  610. Res:=SQLFetch(ODBCCursor.FSTMTHandle);
  611. if Res<>SQL_NO_DATA then
  612. ODBCCheckResult(Res,SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not fetch new row from result set.');
  613. // result is true iff a new row was available
  614. Result:=Res<>SQL_NO_DATA;
  615. end;
  616. const
  617. DEFAULT_BLOB_BUFFER_SIZE = 1024;
  618. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  619. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer; out CreateBlob : boolean): boolean;
  620. {$ELSE}
  621. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer):boolean;
  622. {$ENDIF}
  623. var
  624. ODBCCursor:TODBCCursor;
  625. StrLenOrInd:SQLINTEGER;
  626. ODBCDateStruct:SQL_DATE_STRUCT;
  627. ODBCTimeStruct:SQL_TIME_STRUCT;
  628. ODBCTimeStampStruct:SQL_TIMESTAMP_STRUCT;
  629. DateTime:TDateTime;
  630. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  631. BlobBuffer:pointer;
  632. BlobBufferSize,BytesRead:SQLINTEGER;
  633. BlobMemoryStream:TMemoryStream;
  634. {$ENDIF}
  635. Res:SQLRETURN;
  636. begin
  637. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  638. CreateBlob := False;
  639. {$ENDIF}
  640. ODBCCursor:=cursor as TODBCCursor;
  641. // load the field using SQLGetData
  642. // Note: optionally we can implement the use of SQLBindCol later for even more speed
  643. // TODO: finish this
  644. case FieldDef.DataType of
  645. ftWideString,ftFixedWideChar: // mapped to TWideStringField
  646. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_WCHAR, buffer, FieldDef.Size, @StrLenOrInd);
  647. ftGuid, ftFixedChar,ftString: // are mapped to a TStringField (including TGuidField)
  648. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_CHAR, buffer, FieldDef.Size, @StrLenOrInd);
  649. ftSmallint: // mapped to TSmallintField
  650. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SSHORT, buffer, SizeOf(Smallint), @StrLenOrInd);
  651. ftInteger,ftWord,ftAutoInc: // mapped to TLongintField
  652. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SLONG, buffer, SizeOf(Longint), @StrLenOrInd);
  653. ftLargeint: // mapped to TLargeintField
  654. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SBIGINT, buffer, SizeOf(Largeint), @StrLenOrInd);
  655. ftFloat: // mapped to TFloatField
  656. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_DOUBLE, buffer, SizeOf(Double), @StrLenOrInd);
  657. ftTime: // mapped to TTimeField
  658. begin
  659. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIME, @ODBCTimeStruct, SizeOf(SQL_TIME_STRUCT), @StrLenOrInd);
  660. if StrLenOrInd<>SQL_NULL_DATA then
  661. begin
  662. DateTime:=TimeStructToDateTime(@ODBCTimeStruct);
  663. Move(DateTime, buffer^, SizeOf(TDateTime));
  664. end;
  665. end;
  666. ftDate: // mapped to TDateField
  667. begin
  668. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_DATE, @ODBCDateStruct, SizeOf(SQL_DATE_STRUCT), @StrLenOrInd);
  669. if StrLenOrInd<>SQL_NULL_DATA then
  670. begin
  671. DateTime:=DateStructToDateTime(@ODBCDateStruct);
  672. Move(DateTime, buffer^, SizeOf(TDateTime));
  673. end;
  674. end;
  675. ftDateTime: // mapped to TDateTimeField
  676. begin
  677. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIMESTAMP, @ODBCTimeStampStruct, SizeOf(SQL_TIMESTAMP_STRUCT), @StrLenOrInd);
  678. if StrLenOrInd<>SQL_NULL_DATA then
  679. begin
  680. DateTime:=TimeStampStructToDateTime(@ODBCTimeStampStruct);
  681. Move(DateTime, buffer^, SizeOf(TDateTime));
  682. end;
  683. end;
  684. ftBoolean: // mapped to TBooleanField
  685. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BIT, buffer, SizeOf(Wordbool), @StrLenOrInd);
  686. ftBytes: // mapped to TBytesField
  687. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  688. ftVarBytes: // mapped to TVarBytesField
  689. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  690. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  691. ftWideMemo,
  692. {$ENDIF}
  693. ftBlob, ftMemo: // BLOBs
  694. begin
  695. //Writeln('BLOB');
  696. // Try to discover BLOB data length
  697. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, 0, @StrLenOrInd);
  698. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  699. // Read the data if not NULL
  700. if StrLenOrInd<>SQL_NULL_DATA then
  701. begin
  702. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  703. CreateBlob:=true; // defer actual loading of blob data to LoadBlobIntoBuffer method
  704. //WriteLn('Deferring loading of blob of length ',StrLenOrInd);
  705. {$ELSE}
  706. // Determine size of buffer to use
  707. if StrLenOrInd<>SQL_NO_TOTAL then
  708. BlobBufferSize:=StrLenOrInd
  709. else
  710. BlobBufferSize:=DEFAULT_BLOB_BUFFER_SIZE;
  711. try
  712. // init BlobBuffer and BlobMemoryStream to nil pointers
  713. BlobBuffer:=nil;
  714. BlobMemoryStream:=nil;
  715. if BlobBufferSize>0 then // Note: zero-length BLOB is represented as nil pointer in the field buffer to save memory usage
  716. begin
  717. // Allocate the buffer and memorystream
  718. BlobBuffer:=GetMem(BlobBufferSize);
  719. BlobMemoryStream:=TMemoryStream.Create;
  720. // Retrieve data in parts (or effectively in one part if StrLenOrInd<>SQL_NO_TOTAL above)
  721. repeat
  722. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, BlobBuffer, BlobBufferSize, @StrLenOrInd);
  723. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  724. // Append data in buffer to memorystream
  725. if (StrLenOrInd=SQL_NO_TOTAL) or (StrLenOrInd>BlobBufferSize) then
  726. BytesRead:=BlobBufferSize
  727. else
  728. BytesRead:=StrLenOrInd;
  729. BlobMemoryStream.Write(BlobBuffer^, BytesRead);
  730. until Res=SQL_SUCCESS;
  731. end;
  732. // Store memorystream pointer in Field buffer and in the cursor's FBlobStreams list
  733. TObject(buffer^):=BlobMemoryStream;
  734. if BlobMemoryStream<>nil then
  735. ODBCCursor.FBlobStreams.Add(BlobMemoryStream);
  736. // Set BlobMemoryStream to nil, so it won't get freed in the finally block below
  737. BlobMemoryStream:=nil;
  738. finally
  739. BlobMemoryStream.Free;
  740. if BlobBuffer<>nil then
  741. Freemem(BlobBuffer,BlobBufferSize);
  742. end;
  743. {$ENDIF}
  744. end;
  745. end;
  746. // TODO: Loading of other field types
  747. else
  748. raise EODBCException.CreateFmt('Tried to load field of unsupported field type %s',[Fieldtypenames[FieldDef.DataType]]);
  749. end;
  750. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  751. Result:=StrLenOrInd<>SQL_NULL_DATA; // Result indicates whether the value is non-null
  752. //writeln(Format('Field.Size: %d; StrLenOrInd: %d',[FieldDef.Size, StrLenOrInd]));
  753. end;
  754. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  755. procedure TODBCConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef; ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  756. var
  757. ODBCCursor: TODBCCursor;
  758. Res: SQLRETURN;
  759. StrLenOrInd:SQLINTEGER;
  760. BlobBuffer:pointer;
  761. BlobBufferSize,BytesRead:SQLINTEGER;
  762. BlobMemoryStream:TMemoryStream;
  763. begin
  764. ODBCCursor:=cursor as TODBCCursor;
  765. // Try to discover BLOB data length
  766. // NB MS ODBC requires that TargetValuePtr is not nil, so we supply it with a valid pointer, even though BufferLength is 0
  767. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, @BlobBuffer, 0, @StrLenOrInd);
  768. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  769. // Read the data if not NULL
  770. if StrLenOrInd<>SQL_NULL_DATA then
  771. begin
  772. // Determine size of buffer to use
  773. if StrLenOrInd<>SQL_NO_TOTAL then begin
  774. // Size is known on beforehand
  775. // set size & alloc buffer
  776. //WriteLn('Loading blob of length ',StrLenOrInd);
  777. BlobBufferSize:=StrLenOrInd;
  778. ABlobBuf^.BlobBuffer^.Size:=BlobBufferSize;
  779. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize);
  780. // get blob data
  781. if BlobBufferSize>0 then begin
  782. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize, @StrLenOrInd);
  783. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not load blob data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  784. end;
  785. end else begin
  786. // Size is not known on beforehand; read data in chuncks; write to a TMemoryStream (which implements O(n) writing)
  787. BlobBufferSize:=DEFAULT_BLOB_BUFFER_SIZE;
  788. // init BlobBuffer and BlobMemoryStream to nil pointers
  789. BlobBuffer:=nil; // the buffer that will hold the chuncks of data; not to be confused with ABlobBuf^.BlobBuffer
  790. BlobMemoryStream:=nil;
  791. try
  792. // Allocate the buffer and memorystream
  793. BlobBuffer:=GetMem(BlobBufferSize);
  794. BlobMemoryStream:=TMemoryStream.Create;
  795. // Retrieve data in parts
  796. repeat
  797. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, BlobBuffer, BlobBufferSize, @StrLenOrInd);
  798. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not load (partial) blob data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  799. // Append data in buffer to memorystream
  800. if (StrLenOrInd=SQL_NO_TOTAL) or (StrLenOrInd>BlobBufferSize) then
  801. BytesRead:=BlobBufferSize
  802. else
  803. BytesRead:=StrLenOrInd;
  804. BlobMemoryStream.Write(BlobBuffer^, BytesRead);
  805. until Res=SQL_SUCCESS;
  806. // Copy memory stream data to ABlobBuf^.BlobBuffer
  807. BlobBufferSize:=BlobMemoryStream.Size; // actual blob size
  808. // alloc ABlobBuf^.BlobBuffer
  809. ABlobBuf^.BlobBuffer^.Size:=BlobBufferSize;
  810. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize);
  811. // read memory stream data into ABlobBuf^.BlobBuffer
  812. BlobMemoryStream.Position:=0;
  813. BlobMemoryStream.Read(ABlobBuf^.BlobBuffer^.Buffer^, BlobBufferSize);
  814. finally
  815. // free buffer and memory stream
  816. BlobMemoryStream.Free;
  817. if BlobBuffer<>nil then
  818. Freemem(BlobBuffer,BlobBufferSize);
  819. end;
  820. end;
  821. end;
  822. end;
  823. {$ELSE}
  824. function TODBCConnection.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
  825. var
  826. ODBCCursor: TODBCCursor;
  827. BlobMemoryStream, BlobMemoryStreamCopy: TMemoryStream;
  828. begin
  829. if (Mode=bmRead) and not Field.IsNull then
  830. begin
  831. Field.GetData(@BlobMemoryStream);
  832. BlobMemoryStreamCopy:=TMemoryStream.Create;
  833. if BlobMemoryStream<>nil then
  834. BlobMemoryStreamCopy.LoadFromStream(BlobMemoryStream);
  835. Result:=BlobMemoryStreamCopy;
  836. end
  837. else
  838. Result:=nil;
  839. end;
  840. {$ENDIF}
  841. procedure TODBCConnection.FreeFldBuffers(cursor: TSQLCursor);
  842. var
  843. ODBCCursor:TODBCCursor;
  844. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  845. i: integer;
  846. {$ENDIF}
  847. begin
  848. ODBCCursor:=cursor as TODBCCursor;
  849. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  850. // Free TMemoryStreams in cursor.FBlobStreams and clear it
  851. for i:=0 to ODBCCursor.FBlobStreams.Count-1 do
  852. TObject(ODBCCursor.FBlobStreams[i]).Free;
  853. ODBCCursor.FBlobStreams.Clear;
  854. {$ENDIF}
  855. ODBCCheckResult(
  856. SQLFreeStmt(ODBCCursor.FSTMTHandle, SQL_CLOSE),
  857. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not close ODBC statement cursor.'
  858. );
  859. end;
  860. procedure TODBCConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TFieldDefs);
  861. const
  862. ColNameDefaultLength = 40; // should be > 0, because an ansistring of length 0 is a nil pointer instead of a pointer to a #0
  863. TypeNameDefaultLength = 80; // idem
  864. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  865. BLOB_BUF_SIZE = 0;
  866. {$ELSE}
  867. BLOB_BUF_SIZE = sizeof(pointer);
  868. {$ENDIF}
  869. var
  870. ODBCCursor:TODBCCursor;
  871. ColumnCount:SQLSMALLINT;
  872. i:integer;
  873. ColNameLength,TypeNameLength,DataType,DecimalDigits,Nullable:SQLSMALLINT;
  874. ColumnSize:SQLUINTEGER;
  875. ColName,TypeName:string;
  876. FieldType:TFieldType;
  877. FieldSize:word;
  878. AutoIncAttr: SQLINTEGER;
  879. begin
  880. ODBCCursor:=cursor as TODBCCursor;
  881. // get number of columns in result set
  882. ODBCCheckResult(
  883. SQLNumResultCols(ODBCCursor.FSTMTHandle, ColumnCount),
  884. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not determine number of columns in result set.'
  885. );
  886. AutoIncAttr:=SQL_FALSE;
  887. for i:=1 to ColumnCount do
  888. begin
  889. SetLength(ColName,ColNameDefaultLength); // also garantuees uniqueness
  890. // call with default column name buffer
  891. ODBCCheckResult(
  892. SQLDescribeCol(ODBCCursor.FSTMTHandle, // statement handle
  893. i, // column number, is 1-based (Note: column 0 is the bookmark column in ODBC)
  894. @(ColName[1]), // default buffer
  895. ColNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  896. ColNameLength, // actual column name length
  897. DataType, // the SQL datatype for the column
  898. ColumnSize, // column size
  899. DecimalDigits, // number of decimal digits
  900. Nullable), // SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
  901. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get column properties for column %d.',[i]
  902. );
  903. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  904. SetLength(ColName,ColNameLength);
  905. // check whether entire column name was returned
  906. if ColNameLength>ColNameDefaultLength then
  907. begin
  908. // request column name with buffer that is long enough
  909. ODBCCheckResult(
  910. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  911. i, // column number
  912. SQL_DESC_NAME, // the column name or alias
  913. @(ColName[1]), // buffer
  914. ColNameLength+1, // buffer size
  915. @ColNameLength, // actual length
  916. nil), // no numerical output
  917. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get column name for column %d.',[i]
  918. );
  919. end;
  920. // convert type
  921. // NOTE: I made some guesses here after I found only limited information about TFieldType; please report any problems
  922. case DataType of
  923. SQL_CHAR: begin FieldType:=ftFixedChar; FieldSize:=ColumnSize+1; end;
  924. SQL_VARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end;
  925. SQL_LONGVARCHAR: begin FieldType:=ftMemo; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  926. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  927. SQL_WCHAR: begin FieldType:=ftFixedWideChar; FieldSize:=(ColumnSize+1)*sizeof(Widechar); end;
  928. SQL_WVARCHAR: begin FieldType:=ftWideString; FieldSize:=(ColumnSize+1)*sizeof(Widechar); end;
  929. SQL_WLONGVARCHAR: begin FieldType:=ftWideMemo; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  930. {$ENDIF}
  931. SQL_DECIMAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  932. SQL_NUMERIC: begin FieldType:=ftFloat; FieldSize:=0; end;
  933. SQL_SMALLINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  934. SQL_INTEGER: begin FieldType:=ftInteger; FieldSize:=0; end;
  935. SQL_REAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  936. SQL_FLOAT: begin FieldType:=ftFloat; FieldSize:=0; end;
  937. SQL_DOUBLE: begin FieldType:=ftFloat; FieldSize:=0; end;
  938. SQL_BIT: begin FieldType:=ftBoolean; FieldSize:=0; end;
  939. SQL_TINYINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  940. SQL_BIGINT: begin FieldType:=ftLargeint; FieldSize:=0; end;
  941. SQL_BINARY: begin FieldType:=ftBytes; FieldSize:=ColumnSize; end;
  942. SQL_VARBINARY: begin FieldType:=ftVarBytes; FieldSize:=ColumnSize; end;
  943. SQL_LONGVARBINARY: begin FieldType:=ftBlob; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  944. SQL_TYPE_DATE: begin FieldType:=ftDate; FieldSize:=0; end;
  945. SQL_TYPE_TIME: begin FieldType:=ftTime; FieldSize:=0; end;
  946. SQL_TYPE_TIMESTAMP:begin FieldType:=ftDateTime; FieldSize:=0; end;
  947. { SQL_TYPE_UTCDATETIME:FieldType:=ftUnknown;}
  948. { SQL_TYPE_UTCTIME: FieldType:=ftUnknown;}
  949. { SQL_INTERVAL_MONTH: FieldType:=ftUnknown;}
  950. { SQL_INTERVAL_YEAR: FieldType:=ftUnknown;}
  951. { SQL_INTERVAL_YEAR_TO_MONTH: FieldType:=ftUnknown;}
  952. { SQL_INTERVAL_DAY: FieldType:=ftUnknown;}
  953. { SQL_INTERVAL_HOUR: FieldType:=ftUnknown;}
  954. { SQL_INTERVAL_MINUTE: FieldType:=ftUnknown;}
  955. { SQL_INTERVAL_SECOND: FieldType:=ftUnknown;}
  956. { SQL_INTERVAL_DAY_TO_HOUR: FieldType:=ftUnknown;}
  957. { SQL_INTERVAL_DAY_TO_MINUTE: FieldType:=ftUnknown;}
  958. { SQL_INTERVAL_DAY_TO_SECOND: FieldType:=ftUnknown;}
  959. { SQL_INTERVAL_HOUR_TO_MINUTE: FieldType:=ftUnknown;}
  960. { SQL_INTERVAL_HOUR_TO_SECOND: FieldType:=ftUnknown;}
  961. { SQL_INTERVAL_MINUTE_TO_SECOND:FieldType:=ftUnknown;}
  962. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  963. SQL_GUID: begin FieldType:=ftGuid; FieldSize:=ColumnSize+1; end;
  964. {$ENDIF}
  965. else
  966. begin FieldType:=ftUnknown; FieldSize:=ColumnSize; end
  967. end;
  968. if (FieldType in [ftString,ftFixedChar]) and // field types mapped to TStringField
  969. (FieldSize >= dsMaxStringSize) then
  970. begin
  971. FieldSize:=dsMaxStringSize-1;
  972. end
  973. else
  974. if (FieldType in [ftInteger]) and (AutoIncAttr=SQL_FALSE) then //if the column is an autoincrementing column
  975. //any exact numeric type with scale 0 can have identity attr.
  976. //only one column per table can have identity attr.
  977. begin
  978. ODBCCheckResult(
  979. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  980. i, // column number
  981. SQL_DESC_AUTO_UNIQUE_VALUE, // FieldIdentifier
  982. nil, // buffer
  983. 0, // buffer size
  984. nil, // actual length
  985. @AutoIncAttr), // NumericAttribute
  986. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get autoincrement attribute for column %d.',[i]
  987. );
  988. if AutoIncAttr=SQL_TRUE then
  989. FieldType:=ftAutoInc;
  990. end;
  991. if FieldType=ftUnknown then // if unknown field type encountered, try finding more specific information about the ODBC SQL DataType
  992. begin
  993. SetLength(TypeName,TypeNameDefaultLength); // also garantuees uniqueness
  994. ODBCCheckResult(
  995. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  996. i, // column number
  997. SQL_DESC_TYPE_NAME, // FieldIdentifier indicating the datasource dependent data type name (useful for diagnostics)
  998. @(TypeName[1]), // default buffer
  999. TypeNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  1000. @TypeNameLength, // actual type name length
  1001. nil // no need for a pointer to return a numeric attribute at
  1002. ),
  1003. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get datasource dependent type name for column %s.',[ColName]
  1004. );
  1005. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  1006. SetLength(TypeName,TypeNameLength);
  1007. // check whether entire column name was returned
  1008. if TypeNameLength>TypeNameDefaultLength then
  1009. begin
  1010. // request column name with buffer that is long enough
  1011. ODBCCheckResult(
  1012. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  1013. i, // column number
  1014. SQL_DESC_TYPE_NAME, // FieldIdentifier indicating the datasource dependent data type name (useful for diagnostics)
  1015. @(TypeName[1]), // buffer
  1016. TypeNameLength+1, // buffer size
  1017. @TypeNameLength, // actual length
  1018. nil), // no need for a pointer to return a numeric attribute at
  1019. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get datasource dependent type name for column %s.',[ColName]
  1020. );
  1021. end;
  1022. DatabaseErrorFmt('Column %s has an unknown or unsupported column type. Datasource dependent type name: %s. ODBC SQL data type code: %d.', [ColName, TypeName, DataType]);
  1023. end;
  1024. // add FieldDef
  1025. TFieldDef.Create(FieldDefs, ColName, FieldType, FieldSize, False, i);
  1026. end;
  1027. end;
  1028. procedure TODBCConnection.UpdateIndexDefs(IndexDefs: TIndexDefs; TableName: string);
  1029. var
  1030. StmtHandle:SQLHSTMT;
  1031. Res:SQLRETURN;
  1032. IndexDef: TIndexDef;
  1033. KeyName: String;
  1034. // variables for binding
  1035. NonUnique :SQLSMALLINT; NonUniqueIndOrLen :SQLINTEGER;
  1036. IndexName :string; IndexNameIndOrLen :SQLINTEGER;
  1037. _Type :SQLSMALLINT; _TypeIndOrLen :SQLINTEGER;
  1038. OrdinalPos:SQLSMALLINT; OrdinalPosIndOrLen:SQLINTEGER;
  1039. ColName :string; ColNameIndOrLen :SQLINTEGER;
  1040. AscOrDesc :SQLCHAR; AscOrDescIndOrLen :SQLINTEGER;
  1041. PKName :string; PKNameIndOrLen :SQLINTEGER;
  1042. const
  1043. DEFAULT_NAME_LEN = 255;
  1044. begin
  1045. // allocate statement handle
  1046. StmtHandle := SQL_NULL_HANDLE;
  1047. ODBCCheckResult(
  1048. SQLAllocHandle(SQL_HANDLE_STMT, FDBCHandle, StmtHandle),
  1049. SQL_HANDLE_DBC, FDBCHandle, 'Could not allocate ODBC Statement handle.'
  1050. );
  1051. try
  1052. // Disabled: only works if we can specify a SchemaName and, if supported by the data source, a CatalogName
  1053. // otherwise SQLPrimaryKeys returns error HY0009 (Invalid use of null pointer)
  1054. // set the SQL_ATTR_METADATA_ID so parameters to Catalog functions are considered as identifiers (e.g. case-insensitive)
  1055. //ODBCCheckResult(
  1056. // SQLSetStmtAttr(StmtHandle, SQL_ATTR_METADATA_ID, SQLPOINTER(SQL_TRUE), SQL_IS_UINTEGER),
  1057. // SQL_HANDLE_STMT, StmtHandle, 'Could not set SQL_ATTR_METADATA_ID statement attribute to SQL_TRUE.'
  1058. //);
  1059. // alloc result column buffers
  1060. SetLength(ColName, DEFAULT_NAME_LEN);
  1061. SetLength(PKName, DEFAULT_NAME_LEN);
  1062. SetLength(IndexName,DEFAULT_NAME_LEN);
  1063. // Fetch primary key info using SQLPrimaryKeys
  1064. ODBCCheckResult(
  1065. SQLPrimaryKeys(
  1066. StmtHandle,
  1067. nil, 0, // any catalog
  1068. nil, 0, // any schema
  1069. PChar(TableName), Length(TableName)
  1070. ),
  1071. SQL_HANDLE_STMT, StmtHandle, 'Could not retrieve primary key metadata for table %s using SQLPrimaryKeys.', [TableName]
  1072. );
  1073. // init key name & fields; we will set the IndexDefs.Option ixPrimary below when there is a match by IndexName=KeyName
  1074. KeyName:='';
  1075. try
  1076. // bind result columns; the column numbers are documented in the reference for SQLStatistics
  1077. ODBCCheckResult(SQLBindCol(StmtHandle, 4, SQL_C_CHAR , @ColName[1], Length(ColName)+1, @ColNameIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind primary key metadata column COLUMN_NAME.');
  1078. ODBCCheckResult(SQLBindCol(StmtHandle, 5, SQL_C_SSHORT, @OrdinalPos, 0, @OrdinalPosIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind primary key metadata column KEY_SEQ.');
  1079. ODBCCheckResult(SQLBindCol(StmtHandle, 6, SQL_C_CHAR , @PKName [1], Length(PKName )+1, @PKNameIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind primary key metadata column PK_NAME.');
  1080. // fetch result
  1081. repeat
  1082. // go to next row; loads data in bound columns
  1083. Res:=SQLFetch(StmtHandle);
  1084. // if no more row, break
  1085. if Res=SQL_NO_DATA then
  1086. Break;
  1087. // handle data
  1088. if ODBCSucces(Res) then begin
  1089. if OrdinalPos=1 then begin
  1090. // create new IndexDef if OrdinalPos=1
  1091. IndexDef:=IndexDefs.AddIndexDef;
  1092. IndexDef.Name:=PChar(@PKName[1]);
  1093. IndexDef.Fields:=PChar(@ColName[1]);
  1094. IndexDef.Options:=IndexDef.Options+[ixUnique]+[ixPrimary]; // Primary key is always unique
  1095. KeyName:=IndexDef.Name;
  1096. end else begin
  1097. assert(Assigned(IndexDef));
  1098. IndexDef.Fields:=IndexDef.Fields+';'+PChar(@ColName[1]); // NB ; is the separator to be used for IndexDef.Fields
  1099. end;
  1100. end else begin
  1101. ODBCCheckResult(Res, SQL_HANDLE_STMT, StmtHandle, 'Could not fetch primary key metadata row.');
  1102. end;
  1103. until false;
  1104. finally
  1105. // unbind columns & close cursor
  1106. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_UNBIND), SQL_HANDLE_STMT, StmtHandle, 'Could not unbind columns.');
  1107. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_CLOSE), SQL_HANDLE_STMT, StmtHandle, 'Could not close cursor.');
  1108. end;
  1109. //WriteLn('KeyName: ',KeyName,'; KeyFields: ',KeyFields);
  1110. // use SQLStatistics to get index information
  1111. ODBCCheckResult(
  1112. SQLStatistics(
  1113. StmtHandle,
  1114. nil, 0, // catalog unkown; request for all catalogs
  1115. nil, 0, // schema unkown; request for all schemas
  1116. PChar(TableName), Length(TableName), // request information for TableName
  1117. SQL_INDEX_ALL,
  1118. SQL_QUICK
  1119. ),
  1120. SQL_HANDLE_STMT, StmtHandle, 'Could not retrieve index metadata for table %s using SQLStatistics.', [TableName]
  1121. );
  1122. try
  1123. // bind result columns; the column numbers are documented in the reference for SQLStatistics
  1124. ODBCCheckResult(SQLBindCol(StmtHandle, 4, SQL_C_SSHORT, @NonUnique , 0, @NonUniqueIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column NON_UNIQUE.');
  1125. ODBCCheckResult(SQLBindCol(StmtHandle, 6, SQL_C_CHAR , @IndexName[1], Length(IndexName)+1, @IndexNameIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column INDEX_NAME.');
  1126. ODBCCheckResult(SQLBindCol(StmtHandle, 7, SQL_C_SSHORT, @_Type , 0, @_TypeIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column TYPE.');
  1127. ODBCCheckResult(SQLBindCol(StmtHandle, 8, SQL_C_SSHORT, @OrdinalPos, 0, @OrdinalPosIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column ORDINAL_POSITION.');
  1128. ODBCCheckResult(SQLBindCol(StmtHandle, 9, SQL_C_CHAR , @ColName [1], Length(ColName )+1, @ColNameIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column COLUMN_NAME.');
  1129. ODBCCheckResult(SQLBindCol(StmtHandle, 10, SQL_C_CHAR , @AscOrDesc , 1, @AscOrDescIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column ASC_OR_DESC.');
  1130. // clear index defs
  1131. IndexDef:=nil;
  1132. // fetch result
  1133. repeat
  1134. // go to next row; loads data in bound columns
  1135. Res:=SQLFetch(StmtHandle);
  1136. // if no more row, break
  1137. if Res=SQL_NO_DATA then
  1138. Break;
  1139. // handle data
  1140. if ODBCSucces(Res) then begin
  1141. // note: SQLStatistics not only returns index info, but also statistics; we skip the latter
  1142. if _Type<>SQL_TABLE_STAT then begin
  1143. if PChar(@IndexName[1])=KeyName then begin
  1144. // The indexdef is already made as the primary key
  1145. // Only if the index is descending is not known yet.
  1146. if (AscOrDescIndOrLen<>SQL_NULL_DATA) and (AscOrDesc='D') then begin
  1147. IndexDef:=IndexDefs.Find(KeyName);
  1148. IndexDef.Options:=IndexDef.Options+[ixDescending];
  1149. end;
  1150. end else if (OrdinalPos=1) or not Assigned(IndexDef) then begin
  1151. // create new IndexDef iff OrdinalPos=1 or not Assigned(IndexDef) (the latter should not occur though)
  1152. IndexDef:=IndexDefs.AddIndexDef;
  1153. IndexDef.Name:=PChar(@IndexName[1]); // treat ansistring as zero terminated string
  1154. IndexDef.Fields:=PChar(@ColName[1]);
  1155. if NonUnique=SQL_FALSE then
  1156. IndexDef.Options:=IndexDef.Options+[ixUnique];
  1157. if (AscOrDescIndOrLen<>SQL_NULL_DATA) and (AscOrDesc='D') then
  1158. IndexDef.Options:=IndexDef.Options+[ixDescending];
  1159. // TODO: figure out how we can tell whether COLUMN_NAME is an expression or not
  1160. // if it is an expression, we should include ixExpression in Options and set Expression to ColName
  1161. end else // NB we re-use the last IndexDef
  1162. IndexDef.Fields:=IndexDef.Fields+';'+PChar(@ColName[1]); // NB ; is the separator to be used for IndexDef.Fields
  1163. end;
  1164. end else begin
  1165. ODBCCheckResult(Res, SQL_HANDLE_STMT, StmtHandle, 'Could not fetch index metadata row.');
  1166. end;
  1167. until false;
  1168. finally
  1169. // unbind columns & close cursor
  1170. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_UNBIND), SQL_HANDLE_STMT, StmtHandle, 'Could not unbind columns.');
  1171. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_CLOSE), SQL_HANDLE_STMT, StmtHandle, 'Could not close cursor.');
  1172. end;
  1173. finally
  1174. if StmtHandle<>SQL_NULL_HANDLE then begin
  1175. // Free the statement handle
  1176. Res:=SQLFreeHandle(SQL_HANDLE_STMT, StmtHandle);
  1177. if Res=SQL_ERROR then
  1178. ODBCCheckResult(Res, SQL_HANDLE_STMT, STMTHandle, 'Could not free ODBC Statement handle.');
  1179. end;
  1180. end;
  1181. end;
  1182. function TODBCConnection.GetSchemaInfoSQL(SchemaType: TSchemaType; SchemaObjectName, SchemaObjectPattern: string): string;
  1183. begin
  1184. if SchemaObjectName<>'' then
  1185. Result := SchemaObjectName
  1186. else
  1187. Result := ' ';
  1188. if not (SchemaType in [stNoSchema, stTables, stColumns, stProcedures]) then
  1189. DatabaseError(SMetadataUnavailable);
  1190. end;
  1191. { TODBCEnvironment }
  1192. constructor TODBCEnvironment.Create;
  1193. begin
  1194. // make sure odbc is loaded
  1195. if ODBCLoadCount=0 then InitialiseOdbc;
  1196. Inc(ODBCLoadCount);
  1197. // allocate environment handle
  1198. if SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, FENVHandle)=SQL_Error then
  1199. raise EODBCException.Create('Could not allocate ODBC Environment handle'); // we can't retrieve any more information, because we don't have a handle for the SQLGetDiag* functions
  1200. // set odbc version
  1201. ODBCCheckResult(
  1202. SQLSetEnvAttr(FENVHandle, SQL_ATTR_ODBC_VERSION, SQLPOINTER(SQL_OV_ODBC3), 0),
  1203. SQL_HANDLE_ENV, FENVHandle,'Could not set ODBC version to 3.'
  1204. );
  1205. end;
  1206. destructor TODBCEnvironment.Destroy;
  1207. var
  1208. Res:SQLRETURN;
  1209. begin
  1210. // free environment handle
  1211. if assigned(FENVHandle) then
  1212. begin
  1213. Res:=SQLFreeHandle(SQL_HANDLE_ENV, FENVHandle);
  1214. if Res=SQL_ERROR then
  1215. ODBCCheckResult(Res,SQL_HANDLE_ENV, FENVHandle, 'Could not free ODBC Environment handle.');
  1216. end;
  1217. // free odbc if not used by any TODBCEnvironment object anymore
  1218. if ODBCLoadCount>0 then
  1219. begin
  1220. Dec(ODBCLoadCount);
  1221. if ODBCLoadCount=0 then ReleaseOdbc;
  1222. end;
  1223. end;
  1224. { TODBCCursor }
  1225. constructor TODBCCursor.Create(Connection:TODBCConnection);
  1226. begin
  1227. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  1228. // allocate FBlobStreams
  1229. FBlobStreams:=TList.Create;
  1230. {$ENDIF}
  1231. end;
  1232. destructor TODBCCursor.Destroy;
  1233. var
  1234. Res:SQLRETURN;
  1235. begin
  1236. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  1237. FBlobStreams.Free;
  1238. {$ENDIF}
  1239. inherited Destroy;
  1240. end;
  1241. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  1242. class function TODBCConnectionDef.TypeName: String;
  1243. begin
  1244. Result:='ODBC';
  1245. end;
  1246. class function TODBCConnectionDef.ConnectionClass: TSQLConnectionClass;
  1247. begin
  1248. Result:=TODBCConnection;
  1249. end;
  1250. class function TODBCConnectionDef.Description: String;
  1251. begin
  1252. Result:='Connect to any database via an ODBC driver';
  1253. end;
  1254. initialization
  1255. RegisterConnection(TODBCConnectionDef);
  1256. {$ENDIF}
  1257. finalization
  1258. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  1259. UnRegisterConnection(TODBCConnectionDef);
  1260. {$ENDIF}
  1261. if Assigned(DefaultEnvironment) then
  1262. DefaultEnvironment.Free;
  1263. end.