2
0

odbcconn.pas 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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. ColumnSize, BufferLength, StrLenOrInd: SQLINTEGER;
  278. CType, SqlType, DecimalDigits:SQLSMALLINT;
  279. begin
  280. // Note: it is assumed that AParams is the same as the one passed to PrepareStatement, in the sense that
  281. // the parameters have the same order and names
  282. if Length(ODBCCursor.FParamIndex)>0 then
  283. if not Assigned(AParams) then
  284. raise EODBCException.CreateFmt('The query has parameter markers in it, but no actual parameters were passed',[]);
  285. SetLength(ODBCCursor.FParamBuf, Length(ODBCCursor.FParamIndex));
  286. for i:=0 to High(ODBCCursor.FParamIndex) do
  287. begin
  288. ParamIndex:=ODBCCursor.FParamIndex[i];
  289. if (ParamIndex<0) or (ParamIndex>=AParams.Count) then
  290. raise EODBCException.CreateFmt('Parameter %d in query does not have a matching parameter set',[i]);
  291. DecimalDigits:=0;
  292. BufferLength:=0;
  293. StrLenOrInd:=0;
  294. case AParams[ParamIndex].DataType of
  295. ftInteger, ftSmallInt:
  296. begin
  297. IntVal:=AParams[ParamIndex].AsInteger;
  298. PVal:=@IntVal;
  299. Size:=SizeOf(IntVal);
  300. CType:=SQL_C_LONG;
  301. SqlType:=SQL_INTEGER;
  302. ColumnSize:=10;
  303. end;
  304. ftLargeInt:
  305. begin
  306. LargeVal:=AParams[ParamIndex].AsLargeInt;
  307. PVal:=@LargeVal;
  308. Size:=SizeOf(LargeVal);
  309. CType:=SQL_C_SBIGINT;
  310. SqlType:=SQL_BIGINT;
  311. ColumnSize:=19;
  312. end;
  313. ftString, ftBlob, ftMemo:
  314. begin
  315. StrVal:=AParams[ParamIndex].AsString;
  316. StrLenOrInd:=Length(StrVal);
  317. if StrVal='' then //HY104
  318. begin
  319. StrVal:=#0;
  320. StrLenOrInd:=SQL_NTS;
  321. end;
  322. PVal:=@StrVal[1];
  323. Size:=Length(StrVal);
  324. ColumnSize:=Size;
  325. BufferLength:=Size;
  326. if AParams[ParamIndex].DataType = ftString then
  327. begin
  328. CType:=SQL_C_CHAR;
  329. SqlType:=SQL_LONGVARCHAR;
  330. end
  331. else // ftBlob, ftMemo
  332. begin
  333. CType:=SQL_C_BINARY;
  334. SqlType:=SQL_BINARY;
  335. end;
  336. end;
  337. ftFloat:
  338. begin
  339. FloatVal:=AParams[ParamIndex].AsFloat;
  340. PVal:=@FloatVal;
  341. Size:=SizeOf(FloatVal);
  342. CType:=SQL_C_DOUBLE;
  343. SqlType:=SQL_DOUBLE;
  344. ColumnSize:=15;
  345. end;
  346. ftDate:
  347. begin
  348. DateVal:=DateTimeToDateStruct(AParams[ParamIndex].AsDate);
  349. PVal:=@DateVal;
  350. Size:=SizeOf(DateVal);
  351. CType:=SQL_C_TYPE_DATE;
  352. SqlType:=SQL_TYPE_DATE;
  353. ColumnSize:=Size;
  354. end;
  355. ftDateTime:
  356. begin
  357. DateTime2TimeStampStruct(TimeStampVal, AParams[ParamIndex].AsDateTime);
  358. PVal:=@TimeStampVal;
  359. Size:=SizeOf(TimeStampVal);
  360. CType:=SQL_C_TYPE_TIMESTAMP;
  361. SqlType:=SQL_TYPE_TIMESTAMP;
  362. ColumnSize:=Size;
  363. end;
  364. else
  365. raise EDataBaseError.CreateFmt('Parameter %d is of type %s, which not supported yet',[ParamIndex, Fieldtypenames[AParams[ParamIndex].DataType]]);
  366. end;
  367. if AParams[ParamIndex].IsNull then
  368. StrLenOrInd:=SQL_NULL_DATA;
  369. Buf:=GetMem(Size+SizeOf(SQLINTEGER));
  370. Move(PVal^, Buf^, Size);
  371. if StrLenOrInd<>0 then
  372. begin
  373. PStrLenOrInd:=Buf + Size;
  374. Move(StrLenOrInd, PStrLenOrInd^, SizeOf(SQLINTEGER));
  375. end
  376. else
  377. PStrLenOrInd:=nil;
  378. ODBCCursor.FParamBuf[i]:=Buf;
  379. ODBCCheckResult(
  380. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  381. i+1, // ParameterNumber
  382. SQL_PARAM_INPUT, // InputOutputType
  383. CType, // ValueType
  384. SqlType, // ParameterType
  385. ColumnSize, // ColumnSize
  386. DecimalDigits, // DecimalDigits
  387. Buf, // ParameterValuePtr
  388. BufferLength, // BufferLength
  389. PStrLenOrInd), // StrLen_or_IndPtr
  390. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not bind parameter %d.', [i]
  391. );
  392. end;
  393. end;
  394. procedure TODBCConnection.FreeParamBuffers(ODBCCursor: TODBCCursor);
  395. var
  396. i:integer;
  397. begin
  398. for i:=0 to High(ODBCCursor.FParamBuf) do
  399. FreeMem(ODBCCursor.FParamBuf[i]);
  400. SetLength(ODBCCursor.FParamBuf,0);
  401. end;
  402. function TODBCConnection.GetHandle: pointer;
  403. begin
  404. // I'm not sure whether this is correct; perhaps we should return nil
  405. // note that FDBHandle is a LongInt, because ODBC handles are integers, not pointers
  406. // I wonder how this will work on 64 bit platforms then (FK)
  407. Result:=pointer(PtrInt(FDBCHandle));
  408. end;
  409. procedure TODBCConnection.DoInternalConnect;
  410. const
  411. BufferLength = 1024; // should be at least 1024 according to the ODBC specification
  412. var
  413. ConnectionString:string;
  414. OutConnectionString:string;
  415. ActualLength:SQLSMALLINT;
  416. begin
  417. // Do not call the inherited method as it checks for a non-empty DatabaseName, and we don't even use DatabaseName!
  418. // inherited DoInternalConnect;
  419. // make sure we have an environment
  420. if not Assigned(FEnvironment) then
  421. begin
  422. if not Assigned(DefaultEnvironment) then
  423. DefaultEnvironment:=TODBCEnvironment.Create;
  424. FEnvironment:=DefaultEnvironment;
  425. end;
  426. // allocate connection handle
  427. ODBCCheckResult(
  428. SQLAllocHandle(SQL_HANDLE_DBC,Environment.FENVHandle,FDBCHandle),
  429. SQL_HANDLE_ENV,Environment.FENVHandle,'Could not allocate ODBC Connection handle.'
  430. );
  431. try
  432. // connect
  433. ConnectionString:=CreateConnectionString;
  434. SetLength(OutConnectionString,BufferLength-1); // allocate completed connection string buffer (using the ansistring #0 trick)
  435. ODBCCheckResult(
  436. SQLDriverConnect(FDBCHandle, // the ODBC connection handle
  437. nil, // no parent window (would be required for prompts)
  438. PChar(ConnectionString), // the connection string
  439. Length(ConnectionString), // connection string length
  440. @(OutConnectionString[1]),// buffer for storing the completed connection string
  441. BufferLength, // length of the buffer
  442. ActualLength, // the actual length of the completed connection string
  443. SQL_DRIVER_NOPROMPT), // don't prompt for password etc.
  444. SQL_HANDLE_DBC,FDBCHandle,'Could not connect with connection string "%s".',[ConnectionString]
  445. );
  446. except
  447. on E:Exception do begin
  448. // free connection handle
  449. ODBCCheckResult(
  450. SQLFreeHandle(SQL_HANDLE_DBC,FDBCHandle),
  451. SQL_HANDLE_DBC,FDBCHandle,'Could not free ODBC Connection handle.'
  452. );
  453. raise; // re-raise exception
  454. end;
  455. end;
  456. // commented out as the OutConnectionString is not used further at the moment
  457. // if ActualLength<BufferLength-1 then
  458. // SetLength(OutConnectionString,ActualLength); // fix completed connection string length
  459. // set connection attributes (none yet)
  460. end;
  461. procedure TODBCConnection.DoInternalDisconnect;
  462. var
  463. Res:SQLRETURN;
  464. begin
  465. inherited DoInternalDisconnect;
  466. // disconnect
  467. ODBCCheckResult(
  468. SQLDisconnect(FDBCHandle),
  469. SQL_HANDLE_DBC,FDBCHandle,'Could not disconnect.'
  470. );
  471. // deallocate connection handle
  472. Res:=SQLFreeHandle(SQL_HANDLE_DBC, FDBCHandle);
  473. if Res=SQL_ERROR then
  474. ODBCCheckResult(Res,SQL_HANDLE_DBC,FDBCHandle,'Could not free ODBC Connection handle.');
  475. end;
  476. function TODBCConnection.AllocateCursorHandle: TSQLCursor;
  477. begin
  478. Result:=TODBCCursor.Create(self);
  479. end;
  480. procedure TODBCConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  481. begin
  482. FreeAndNil(cursor); // the destructor of TODBCCursor frees the ODBC Statement handle
  483. end;
  484. function TODBCConnection.AllocateTransactionHandle: TSQLHandle;
  485. begin
  486. Result:=nil; // not yet supported; will move connection handles to transaction handles later
  487. end;
  488. procedure TODBCConnection.PrepareStatement(cursor: TSQLCursor; ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  489. var
  490. ODBCCursor:TODBCCursor;
  491. begin
  492. ODBCCursor:=cursor as TODBCCursor;
  493. // allocate statement handle
  494. ODBCCheckResult(
  495. SQLAllocHandle(SQL_HANDLE_STMT, FDBCHandle, ODBCCursor.FSTMTHandle),
  496. SQL_HANDLE_DBC, FDBCHandle, 'Could not allocate ODBC Statement handle.'
  497. );
  498. ODBCCursor.FPrepared:=True;
  499. // Parameter handling
  500. // Note: We can only pass ? parameters to ODBC, so we should convert named parameters like :MyID
  501. // ODBCCursor.FParamIndex will map th i-th ? token in the (modified) query to an index for AParams
  502. // Parse the SQL and build FParamIndex
  503. if assigned(AParams) and (AParams.count > 0) then
  504. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  505. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psInterbase,ODBCCursor.FParamIndex);
  506. {$ELSE}
  507. buf := AParams.ParseSQL(buf,false,psInterbase,ODBCCursor.FParamIndex);
  508. {$ENDIF}
  509. // prepare statement
  510. ODBCCursor.FQuery:=Buf;
  511. if ODBCCursor.FSchemaType=stNoSchema then
  512. begin
  513. ODBCCheckResult(
  514. SQLPrepare(ODBCCursor.FSTMTHandle, PChar(buf), Length(buf)),
  515. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not prepare statement.'
  516. );
  517. end
  518. else
  519. ODBCCursor.FStatementType:=stSelect;
  520. end;
  521. procedure TODBCConnection.UnPrepareStatement(cursor: TSQLCursor);
  522. var Res:SQLRETURN;
  523. begin
  524. with TODBCCursor(cursor) do
  525. begin
  526. if FSTMTHandle<>SQL_NULL_HSTMT then
  527. begin
  528. // deallocate statement handle
  529. Res:=SQLFreeHandle(SQL_HANDLE_STMT, FSTMTHandle);
  530. if Res=SQL_ERROR then
  531. ODBCCheckResult(Res,SQL_HANDLE_STMT, FSTMTHandle, 'Could not free ODBC Statement handle.');
  532. FSTMTHandle:=SQL_NULL_HSTMT;
  533. FPrepared := False;
  534. end;
  535. end;
  536. end;
  537. function TODBCConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  538. begin
  539. // Tranactions not implemented yet
  540. end;
  541. function TODBCConnection.StartDBTransaction(trans: TSQLHandle; AParams:string): boolean;
  542. begin
  543. // Tranactions not implemented yet
  544. end;
  545. function TODBCConnection.Commit(trans: TSQLHandle): boolean;
  546. begin
  547. // Tranactions not implemented yet
  548. end;
  549. function TODBCConnection.Rollback(trans: TSQLHandle): boolean;
  550. begin
  551. // Tranactions not implemented yet
  552. end;
  553. procedure TODBCConnection.CommitRetaining(trans: TSQLHandle);
  554. begin
  555. // Tranactions not implemented yet
  556. end;
  557. procedure TODBCConnection.RollbackRetaining(trans: TSQLHandle);
  558. begin
  559. // Tranactions not implemented yet
  560. end;
  561. procedure TODBCConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  562. var
  563. ODBCCursor:TODBCCursor;
  564. Res:SQLRETURN;
  565. begin
  566. ODBCCursor:=cursor as TODBCCursor;
  567. // set parameters
  568. if Assigned(APArams) and (AParams.count > 0) then SetParameters(ODBCCursor, AParams);
  569. // execute the statement
  570. case ODBCCursor.FSchemaType of
  571. stNoSchema : Res:=SQLExecute(ODBCCursor.FSTMTHandle); //SQL_NO_DATA returns searched update or delete statement that does not affect any rows
  572. stTables : Res:=SQLTables (ODBCCursor.FSTMTHandle, nil, 0, nil, 0, nil, 0, nil, 0 );
  573. stColumns : Res:=SQLColumns(ODBCCursor.FSTMTHandle, nil, 0, nil, 0, @ODBCCursor.FQuery[1], length(ODBCCursor.FQuery), nil, 0 );
  574. stProcedures: Res:=SQLProcedures(ODBCCursor.FSTMTHandle, nil, 0, nil, 0, nil, 0 );
  575. else Res:=SQL_NO_DATA;
  576. end; {case}
  577. if (Res<>SQL_NO_DATA) then ODBCCheckResult( Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not execute statement.' );
  578. // free parameter buffers
  579. FreeParamBuffers(ODBCCursor);
  580. end;
  581. function TODBCConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  582. var
  583. RowCount: SQLINTEGER;
  584. begin
  585. if assigned(cursor) then
  586. if ODBCSucces( SQLRowCount((cursor as TODBCCursor).FSTMTHandle, RowCount) ) then
  587. Result:=RowCount
  588. else
  589. Result:=-1
  590. else
  591. Result:=-1;
  592. end;
  593. function TODBCConnection.Fetch(cursor: TSQLCursor): boolean;
  594. var
  595. ODBCCursor:TODBCCursor;
  596. Res:SQLRETURN;
  597. begin
  598. ODBCCursor:=cursor as TODBCCursor;
  599. // fetch new row
  600. Res:=SQLFetch(ODBCCursor.FSTMTHandle);
  601. if Res<>SQL_NO_DATA then
  602. ODBCCheckResult(Res,SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not fetch new row from result set.');
  603. // result is true iff a new row was available
  604. Result:=Res<>SQL_NO_DATA;
  605. end;
  606. const
  607. DEFAULT_BLOB_BUFFER_SIZE = 1024;
  608. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  609. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer; out CreateBlob : boolean): boolean;
  610. {$ELSE}
  611. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer):boolean;
  612. {$ENDIF}
  613. var
  614. ODBCCursor:TODBCCursor;
  615. StrLenOrInd:SQLINTEGER;
  616. ODBCDateStruct:SQL_DATE_STRUCT;
  617. ODBCTimeStruct:SQL_TIME_STRUCT;
  618. ODBCTimeStampStruct:SQL_TIMESTAMP_STRUCT;
  619. DateTime:TDateTime;
  620. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  621. BlobBuffer:pointer;
  622. BlobBufferSize,BytesRead:SQLINTEGER;
  623. BlobMemoryStream:TMemoryStream;
  624. {$ENDIF}
  625. Res:SQLRETURN;
  626. begin
  627. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  628. CreateBlob := False;
  629. {$ENDIF}
  630. ODBCCursor:=cursor as TODBCCursor;
  631. // load the field using SQLGetData
  632. // Note: optionally we can implement the use of SQLBindCol later for even more speed
  633. // TODO: finish this
  634. case FieldDef.DataType of
  635. ftWideString,ftFixedWideChar: // mapped to TWideStringField
  636. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_WCHAR, buffer, FieldDef.Size, @StrLenOrInd);
  637. ftGuid, ftFixedChar,ftString: // are mapped to a TStringField (including TGuidField)
  638. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_CHAR, buffer, FieldDef.Size, @StrLenOrInd);
  639. ftSmallint: // mapped to TSmallintField
  640. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SSHORT, buffer, SizeOf(Smallint), @StrLenOrInd);
  641. ftInteger,ftWord: // mapped to TLongintField
  642. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SLONG, buffer, SizeOf(Longint), @StrLenOrInd);
  643. ftLargeint: // mapped to TLargeintField
  644. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SBIGINT, buffer, SizeOf(Largeint), @StrLenOrInd);
  645. ftFloat: // mapped to TFloatField
  646. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_DOUBLE, buffer, SizeOf(Double), @StrLenOrInd);
  647. ftTime: // mapped to TTimeField
  648. begin
  649. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIME, @ODBCTimeStruct, SizeOf(SQL_TIME_STRUCT), @StrLenOrInd);
  650. if StrLenOrInd<>SQL_NULL_DATA then
  651. begin
  652. DateTime:=TimeStructToDateTime(@ODBCTimeStruct);
  653. Move(DateTime, buffer^, SizeOf(TDateTime));
  654. end;
  655. end;
  656. ftDate: // mapped to TDateField
  657. begin
  658. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_DATE, @ODBCDateStruct, SizeOf(SQL_DATE_STRUCT), @StrLenOrInd);
  659. if StrLenOrInd<>SQL_NULL_DATA then
  660. begin
  661. DateTime:=DateStructToDateTime(@ODBCDateStruct);
  662. Move(DateTime, buffer^, SizeOf(TDateTime));
  663. end;
  664. end;
  665. ftDateTime: // mapped to TDateTimeField
  666. begin
  667. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIMESTAMP, @ODBCTimeStampStruct, SizeOf(SQL_TIMESTAMP_STRUCT), @StrLenOrInd);
  668. if StrLenOrInd<>SQL_NULL_DATA then
  669. begin
  670. DateTime:=TimeStampStructToDateTime(@ODBCTimeStampStruct);
  671. Move(DateTime, buffer^, SizeOf(TDateTime));
  672. end;
  673. end;
  674. ftBoolean: // mapped to TBooleanField
  675. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BIT, buffer, SizeOf(Wordbool), @StrLenOrInd);
  676. ftBytes: // mapped to TBytesField
  677. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  678. ftVarBytes: // mapped to TVarBytesField
  679. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  680. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  681. ftWideMemo,
  682. {$ENDIF}
  683. ftBlob, ftMemo: // BLOBs
  684. begin
  685. //Writeln('BLOB');
  686. // Try to discover BLOB data length
  687. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, 0, @StrLenOrInd);
  688. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  689. // Read the data if not NULL
  690. if StrLenOrInd<>SQL_NULL_DATA then
  691. begin
  692. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  693. CreateBlob:=true; // defer actual loading of blob data to LoadBlobIntoBuffer method
  694. //WriteLn('Deferring loading of blob of length ',StrLenOrInd);
  695. {$ELSE}
  696. // Determine size of buffer to use
  697. if StrLenOrInd<>SQL_NO_TOTAL then
  698. BlobBufferSize:=StrLenOrInd
  699. else
  700. BlobBufferSize:=DEFAULT_BLOB_BUFFER_SIZE;
  701. try
  702. // init BlobBuffer and BlobMemoryStream to nil pointers
  703. BlobBuffer:=nil;
  704. BlobMemoryStream:=nil;
  705. if BlobBufferSize>0 then // Note: zero-length BLOB is represented as nil pointer in the field buffer to save memory usage
  706. begin
  707. // Allocate the buffer and memorystream
  708. BlobBuffer:=GetMem(BlobBufferSize);
  709. BlobMemoryStream:=TMemoryStream.Create;
  710. // Retrieve data in parts (or effectively in one part if StrLenOrInd<>SQL_NO_TOTAL above)
  711. repeat
  712. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, BlobBuffer, BlobBufferSize, @StrLenOrInd);
  713. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  714. // Append data in buffer to memorystream
  715. if (StrLenOrInd=SQL_NO_TOTAL) or (StrLenOrInd>BlobBufferSize) then
  716. BytesRead:=BlobBufferSize
  717. else
  718. BytesRead:=StrLenOrInd;
  719. BlobMemoryStream.Write(BlobBuffer^, BytesRead);
  720. until Res=SQL_SUCCESS;
  721. end;
  722. // Store memorystream pointer in Field buffer and in the cursor's FBlobStreams list
  723. TObject(buffer^):=BlobMemoryStream;
  724. if BlobMemoryStream<>nil then
  725. ODBCCursor.FBlobStreams.Add(BlobMemoryStream);
  726. // Set BlobMemoryStream to nil, so it won't get freed in the finally block below
  727. BlobMemoryStream:=nil;
  728. finally
  729. BlobMemoryStream.Free;
  730. if BlobBuffer<>nil then
  731. Freemem(BlobBuffer,BlobBufferSize);
  732. end;
  733. {$ENDIF}
  734. end;
  735. end;
  736. // TODO: Loading of other field types
  737. else
  738. raise EODBCException.CreateFmt('Tried to load field of unsupported field type %s',[Fieldtypenames[FieldDef.DataType]]);
  739. end;
  740. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  741. Result:=StrLenOrInd<>SQL_NULL_DATA; // Result indicates whether the value is non-null
  742. //writeln(Format('Field.Size: %d; StrLenOrInd: %d',[FieldDef.Size, StrLenOrInd]));
  743. end;
  744. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  745. procedure TODBCConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef; ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  746. var
  747. ODBCCursor: TODBCCursor;
  748. Res: SQLRETURN;
  749. StrLenOrInd:SQLINTEGER;
  750. BlobBuffer:pointer;
  751. BlobBufferSize,BytesRead:SQLINTEGER;
  752. BlobMemoryStream:TMemoryStream;
  753. begin
  754. ODBCCursor:=cursor as TODBCCursor;
  755. // Try to discover BLOB data length
  756. // NB MS ODBC requires that TargetValuePtr is not nil, so we supply it with a valid pointer, even though BufferLength is 0
  757. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, @BlobBuffer, 0, @StrLenOrInd);
  758. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  759. // Read the data if not NULL
  760. if StrLenOrInd<>SQL_NULL_DATA then
  761. begin
  762. // Determine size of buffer to use
  763. if StrLenOrInd<>SQL_NO_TOTAL then begin
  764. // Size is known on beforehand
  765. // set size & alloc buffer
  766. //WriteLn('Loading blob of length ',StrLenOrInd);
  767. BlobBufferSize:=StrLenOrInd;
  768. ABlobBuf^.BlobBuffer^.Size:=BlobBufferSize;
  769. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize);
  770. // get blob data
  771. if BlobBufferSize>0 then begin
  772. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize, @StrLenOrInd);
  773. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not load blob data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  774. end;
  775. end else begin
  776. // Size is not known on beforehand; read data in chuncks; write to a TMemoryStream (which implements O(n) writing)
  777. BlobBufferSize:=DEFAULT_BLOB_BUFFER_SIZE;
  778. // init BlobBuffer and BlobMemoryStream to nil pointers
  779. BlobBuffer:=nil; // the buffer that will hold the chuncks of data; not to be confused with ABlobBuf^.BlobBuffer
  780. BlobMemoryStream:=nil;
  781. try
  782. // Allocate the buffer and memorystream
  783. BlobBuffer:=GetMem(BlobBufferSize);
  784. BlobMemoryStream:=TMemoryStream.Create;
  785. // Retrieve data in parts
  786. repeat
  787. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, BlobBuffer, BlobBufferSize, @StrLenOrInd);
  788. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not load (partial) blob data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  789. // Append data in buffer to memorystream
  790. if (StrLenOrInd=SQL_NO_TOTAL) or (StrLenOrInd>BlobBufferSize) then
  791. BytesRead:=BlobBufferSize
  792. else
  793. BytesRead:=StrLenOrInd;
  794. BlobMemoryStream.Write(BlobBuffer^, BytesRead);
  795. until Res=SQL_SUCCESS;
  796. // Copy memory stream data to ABlobBuf^.BlobBuffer
  797. BlobBufferSize:=BlobMemoryStream.Size; // actual blob size
  798. // alloc ABlobBuf^.BlobBuffer
  799. ABlobBuf^.BlobBuffer^.Size:=BlobBufferSize;
  800. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize);
  801. // read memory stream data into ABlobBuf^.BlobBuffer
  802. BlobMemoryStream.Position:=0;
  803. BlobMemoryStream.Read(ABlobBuf^.BlobBuffer^.Buffer^, BlobBufferSize);
  804. finally
  805. // free buffer and memory stream
  806. BlobMemoryStream.Free;
  807. if BlobBuffer<>nil then
  808. Freemem(BlobBuffer,BlobBufferSize);
  809. end;
  810. end;
  811. end;
  812. end;
  813. {$ELSE}
  814. function TODBCConnection.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
  815. var
  816. ODBCCursor: TODBCCursor;
  817. BlobMemoryStream, BlobMemoryStreamCopy: TMemoryStream;
  818. begin
  819. if (Mode=bmRead) and not Field.IsNull then
  820. begin
  821. Field.GetData(@BlobMemoryStream);
  822. BlobMemoryStreamCopy:=TMemoryStream.Create;
  823. if BlobMemoryStream<>nil then
  824. BlobMemoryStreamCopy.LoadFromStream(BlobMemoryStream);
  825. Result:=BlobMemoryStreamCopy;
  826. end
  827. else
  828. Result:=nil;
  829. end;
  830. {$ENDIF}
  831. procedure TODBCConnection.FreeFldBuffers(cursor: TSQLCursor);
  832. var
  833. ODBCCursor:TODBCCursor;
  834. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  835. i: integer;
  836. {$ENDIF}
  837. begin
  838. ODBCCursor:=cursor as TODBCCursor;
  839. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  840. // Free TMemoryStreams in cursor.FBlobStreams and clear it
  841. for i:=0 to ODBCCursor.FBlobStreams.Count-1 do
  842. TObject(ODBCCursor.FBlobStreams[i]).Free;
  843. ODBCCursor.FBlobStreams.Clear;
  844. {$ENDIF}
  845. ODBCCheckResult(
  846. SQLFreeStmt(ODBCCursor.FSTMTHandle, SQL_CLOSE),
  847. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not close ODBC statement cursor.'
  848. );
  849. end;
  850. procedure TODBCConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TFieldDefs);
  851. const
  852. ColNameDefaultLength = 40; // should be > 0, because an ansistring of length 0 is a nil pointer instead of a pointer to a #0
  853. TypeNameDefaultLength = 80; // idem
  854. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  855. BLOB_BUF_SIZE = 0;
  856. {$ELSE}
  857. BLOB_BUF_SIZE = sizeof(pointer);
  858. {$ENDIF}
  859. var
  860. ODBCCursor:TODBCCursor;
  861. ColumnCount:SQLSMALLINT;
  862. i:integer;
  863. ColNameLength,TypeNameLength,DataType,DecimalDigits,Nullable:SQLSMALLINT;
  864. ColumnSize:SQLUINTEGER;
  865. ColName,TypeName:string;
  866. FieldType:TFieldType;
  867. FieldSize:word;
  868. begin
  869. ODBCCursor:=cursor as TODBCCursor;
  870. // get number of columns in result set
  871. ODBCCheckResult(
  872. SQLNumResultCols(ODBCCursor.FSTMTHandle, ColumnCount),
  873. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not determine number of columns in result set.'
  874. );
  875. for i:=1 to ColumnCount do
  876. begin
  877. SetLength(ColName,ColNameDefaultLength); // also garantuees uniqueness
  878. // call with default column name buffer
  879. ODBCCheckResult(
  880. SQLDescribeCol(ODBCCursor.FSTMTHandle, // statement handle
  881. i, // column number, is 1-based (Note: column 0 is the bookmark column in ODBC)
  882. @(ColName[1]), // default buffer
  883. ColNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  884. ColNameLength, // actual column name length
  885. DataType, // the SQL datatype for the column
  886. ColumnSize, // column size
  887. DecimalDigits, // number of decimal digits
  888. Nullable), // SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
  889. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get column properties for column %d.',[i]
  890. );
  891. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  892. SetLength(ColName,ColNameLength);
  893. // check whether entire column name was returned
  894. if ColNameLength>ColNameDefaultLength then
  895. begin
  896. // request column name with buffer that is long enough
  897. ODBCCheckResult(
  898. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  899. i, // column number
  900. SQL_DESC_NAME, // the column name or alias
  901. @(ColName[1]), // buffer
  902. ColNameLength+1, // buffer size
  903. @ColNameLength, // actual length
  904. nil), // no numerical output
  905. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get column name for column %d.',[i]
  906. );
  907. end;
  908. // convert type
  909. // NOTE: I made some guesses here after I found only limited information about TFieldType; please report any problems
  910. case DataType of
  911. SQL_CHAR: begin FieldType:=ftFixedChar; FieldSize:=ColumnSize+1; end;
  912. SQL_VARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end;
  913. SQL_LONGVARCHAR: begin FieldType:=ftMemo; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  914. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  915. SQL_WCHAR: begin FieldType:=ftFixedWideChar; FieldSize:=(ColumnSize+1)*sizeof(Widechar); end;
  916. SQL_WVARCHAR: begin FieldType:=ftWideString; FieldSize:=(ColumnSize+1)*sizeof(Widechar); end;
  917. SQL_WLONGVARCHAR: begin FieldType:=ftWideMemo; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  918. {$ENDIF}
  919. SQL_DECIMAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  920. SQL_NUMERIC: begin FieldType:=ftFloat; FieldSize:=0; end;
  921. SQL_SMALLINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  922. SQL_INTEGER: begin FieldType:=ftInteger; FieldSize:=0; end;
  923. SQL_REAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  924. SQL_FLOAT: begin FieldType:=ftFloat; FieldSize:=0; end;
  925. SQL_DOUBLE: begin FieldType:=ftFloat; FieldSize:=0; end;
  926. SQL_BIT: begin FieldType:=ftBoolean; FieldSize:=0; end;
  927. SQL_TINYINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  928. SQL_BIGINT: begin FieldType:=ftLargeint; FieldSize:=0; end;
  929. SQL_BINARY: begin FieldType:=ftBytes; FieldSize:=ColumnSize; end;
  930. SQL_VARBINARY: begin FieldType:=ftVarBytes; FieldSize:=ColumnSize; end;
  931. SQL_LONGVARBINARY: begin FieldType:=ftBlob; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  932. SQL_TYPE_DATE: begin FieldType:=ftDate; FieldSize:=0; end;
  933. SQL_TYPE_TIME: begin FieldType:=ftTime; FieldSize:=0; end;
  934. SQL_TYPE_TIMESTAMP:begin FieldType:=ftDateTime; FieldSize:=0; end;
  935. { SQL_TYPE_UTCDATETIME:FieldType:=ftUnknown;}
  936. { SQL_TYPE_UTCTIME: FieldType:=ftUnknown;}
  937. { SQL_INTERVAL_MONTH: FieldType:=ftUnknown;}
  938. { SQL_INTERVAL_YEAR: FieldType:=ftUnknown;}
  939. { SQL_INTERVAL_YEAR_TO_MONTH: FieldType:=ftUnknown;}
  940. { SQL_INTERVAL_DAY: FieldType:=ftUnknown;}
  941. { SQL_INTERVAL_HOUR: FieldType:=ftUnknown;}
  942. { SQL_INTERVAL_MINUTE: FieldType:=ftUnknown;}
  943. { SQL_INTERVAL_SECOND: FieldType:=ftUnknown;}
  944. { SQL_INTERVAL_DAY_TO_HOUR: FieldType:=ftUnknown;}
  945. { SQL_INTERVAL_DAY_TO_MINUTE: FieldType:=ftUnknown;}
  946. { SQL_INTERVAL_DAY_TO_SECOND: FieldType:=ftUnknown;}
  947. { SQL_INTERVAL_HOUR_TO_MINUTE: FieldType:=ftUnknown;}
  948. { SQL_INTERVAL_HOUR_TO_SECOND: FieldType:=ftUnknown;}
  949. { SQL_INTERVAL_MINUTE_TO_SECOND:FieldType:=ftUnknown;}
  950. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  951. SQL_GUID: begin FieldType:=ftGuid; FieldSize:=ColumnSize+1; end;
  952. {$ENDIF}
  953. else
  954. begin FieldType:=ftUnknown; FieldSize:=ColumnSize; end
  955. end;
  956. if (FieldType in [ftString,ftFixedChar]) and // field types mapped to TStringField
  957. (FieldSize >= dsMaxStringSize) then
  958. begin
  959. FieldSize:=dsMaxStringSize-1;
  960. end;
  961. if FieldType=ftUnknown then // if unknown field type encountered, try finding more specific information about the ODBC SQL DataType
  962. begin
  963. SetLength(TypeName,TypeNameDefaultLength); // also garantuees uniqueness
  964. ODBCCheckResult(
  965. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  966. i, // column number
  967. SQL_DESC_TYPE_NAME, // FieldIdentifier indicating the datasource dependent data type name (useful for diagnostics)
  968. @(TypeName[1]), // default buffer
  969. TypeNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  970. @TypeNameLength, // actual type name length
  971. nil // no need for a pointer to return a numeric attribute at
  972. ),
  973. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get datasource dependent type name for column %s.',[ColName]
  974. );
  975. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  976. SetLength(TypeName,TypeNameLength);
  977. // check whether entire column name was returned
  978. if TypeNameLength>TypeNameDefaultLength then
  979. begin
  980. // request column name with buffer that is long enough
  981. ODBCCheckResult(
  982. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  983. i, // column number
  984. SQL_DESC_TYPE_NAME, // FieldIdentifier indicating the datasource dependent data type name (useful for diagnostics)
  985. @(TypeName[1]), // buffer
  986. TypeNameLength+1, // buffer size
  987. @TypeNameLength, // actual length
  988. nil), // no need for a pointer to return a numeric attribute at
  989. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get datasource dependent type name for column %s.',[ColName]
  990. );
  991. end;
  992. DatabaseErrorFmt('Column %s has an unknown or unsupported column type. Datasource dependent type name: %s. ODBC SQL data type code: %d.', [ColName, TypeName, DataType]);
  993. end;
  994. // add FieldDef
  995. TFieldDef.Create(FieldDefs, ColName, FieldType, FieldSize, False, i);
  996. end;
  997. end;
  998. procedure TODBCConnection.UpdateIndexDefs(IndexDefs: TIndexDefs; TableName: string);
  999. var
  1000. StmtHandle:SQLHSTMT;
  1001. Res:SQLRETURN;
  1002. IndexDef: TIndexDef;
  1003. KeyName: String;
  1004. // variables for binding
  1005. NonUnique :SQLSMALLINT; NonUniqueIndOrLen :SQLINTEGER;
  1006. IndexName :string; IndexNameIndOrLen :SQLINTEGER;
  1007. _Type :SQLSMALLINT; _TypeIndOrLen :SQLINTEGER;
  1008. OrdinalPos:SQLSMALLINT; OrdinalPosIndOrLen:SQLINTEGER;
  1009. ColName :string; ColNameIndOrLen :SQLINTEGER;
  1010. AscOrDesc :SQLCHAR; AscOrDescIndOrLen :SQLINTEGER;
  1011. PKName :string; PKNameIndOrLen :SQLINTEGER;
  1012. const
  1013. DEFAULT_NAME_LEN = 255;
  1014. begin
  1015. // allocate statement handle
  1016. StmtHandle := SQL_NULL_HANDLE;
  1017. ODBCCheckResult(
  1018. SQLAllocHandle(SQL_HANDLE_STMT, FDBCHandle, StmtHandle),
  1019. SQL_HANDLE_DBC, FDBCHandle, 'Could not allocate ODBC Statement handle.'
  1020. );
  1021. try
  1022. // Disabled: only works if we can specify a SchemaName and, if supported by the data source, a CatalogName
  1023. // otherwise SQLPrimaryKeys returns error HY0009 (Invalid use of null pointer)
  1024. // set the SQL_ATTR_METADATA_ID so parameters to Catalog functions are considered as identifiers (e.g. case-insensitive)
  1025. //ODBCCheckResult(
  1026. // SQLSetStmtAttr(StmtHandle, SQL_ATTR_METADATA_ID, SQLPOINTER(SQL_TRUE), SQL_IS_UINTEGER),
  1027. // SQL_HANDLE_STMT, StmtHandle, 'Could not set SQL_ATTR_METADATA_ID statement attribute to SQL_TRUE.'
  1028. //);
  1029. // alloc result column buffers
  1030. SetLength(ColName, DEFAULT_NAME_LEN);
  1031. SetLength(PKName, DEFAULT_NAME_LEN);
  1032. SetLength(IndexName,DEFAULT_NAME_LEN);
  1033. // Fetch primary key info using SQLPrimaryKeys
  1034. ODBCCheckResult(
  1035. SQLPrimaryKeys(
  1036. StmtHandle,
  1037. nil, 0, // any catalog
  1038. nil, 0, // any schema
  1039. PChar(TableName), Length(TableName)
  1040. ),
  1041. SQL_HANDLE_STMT, StmtHandle, 'Could not retrieve primary key metadata for table %s using SQLPrimaryKeys.', [TableName]
  1042. );
  1043. // init key name & fields; we will set the IndexDefs.Option ixPrimary below when there is a match by IndexName=KeyName
  1044. KeyName:='';
  1045. try
  1046. // bind result columns; the column numbers are documented in the reference for SQLStatistics
  1047. 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.');
  1048. ODBCCheckResult(SQLBindCol(StmtHandle, 5, SQL_C_SSHORT, @OrdinalPos, 0, @OrdinalPosIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind primary key metadata column KEY_SEQ.');
  1049. 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.');
  1050. // fetch result
  1051. repeat
  1052. // go to next row; loads data in bound columns
  1053. Res:=SQLFetch(StmtHandle);
  1054. // if no more row, break
  1055. if Res=SQL_NO_DATA then
  1056. Break;
  1057. // handle data
  1058. if ODBCSucces(Res) then begin
  1059. if OrdinalPos=1 then begin
  1060. // create new IndexDef if OrdinalPos=1
  1061. IndexDef:=IndexDefs.AddIndexDef;
  1062. IndexDef.Name:=PChar(@PKName[1]);
  1063. IndexDef.Fields:=PChar(@ColName[1]);
  1064. IndexDef.Options:=IndexDef.Options+[ixUnique]+[ixPrimary]; // Primary key is always unique
  1065. KeyName:=IndexDef.Name;
  1066. end else begin
  1067. assert(Assigned(IndexDef));
  1068. IndexDef.Fields:=IndexDef.Fields+';'+PChar(@ColName[1]); // NB ; is the separator to be used for IndexDef.Fields
  1069. end;
  1070. end else begin
  1071. ODBCCheckResult(Res, SQL_HANDLE_STMT, StmtHandle, 'Could not fetch primary key metadata row.');
  1072. end;
  1073. until false;
  1074. finally
  1075. // unbind columns & close cursor
  1076. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_UNBIND), SQL_HANDLE_STMT, StmtHandle, 'Could not unbind columns.');
  1077. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_CLOSE), SQL_HANDLE_STMT, StmtHandle, 'Could not close cursor.');
  1078. end;
  1079. //WriteLn('KeyName: ',KeyName,'; KeyFields: ',KeyFields);
  1080. // use SQLStatistics to get index information
  1081. ODBCCheckResult(
  1082. SQLStatistics(
  1083. StmtHandle,
  1084. nil, 0, // catalog unkown; request for all catalogs
  1085. nil, 0, // schema unkown; request for all schemas
  1086. PChar(TableName), Length(TableName), // request information for TableName
  1087. SQL_INDEX_ALL,
  1088. SQL_QUICK
  1089. ),
  1090. SQL_HANDLE_STMT, StmtHandle, 'Could not retrieve index metadata for table %s using SQLStatistics.', [TableName]
  1091. );
  1092. try
  1093. // bind result columns; the column numbers are documented in the reference for SQLStatistics
  1094. ODBCCheckResult(SQLBindCol(StmtHandle, 4, SQL_C_SSHORT, @NonUnique , 0, @NonUniqueIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column NON_UNIQUE.');
  1095. 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.');
  1096. ODBCCheckResult(SQLBindCol(StmtHandle, 7, SQL_C_SSHORT, @_Type , 0, @_TypeIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column TYPE.');
  1097. ODBCCheckResult(SQLBindCol(StmtHandle, 8, SQL_C_SSHORT, @OrdinalPos, 0, @OrdinalPosIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column ORDINAL_POSITION.');
  1098. 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.');
  1099. ODBCCheckResult(SQLBindCol(StmtHandle, 10, SQL_C_CHAR , @AscOrDesc , 1, @AscOrDescIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column ASC_OR_DESC.');
  1100. // clear index defs
  1101. IndexDef:=nil;
  1102. // fetch result
  1103. repeat
  1104. // go to next row; loads data in bound columns
  1105. Res:=SQLFetch(StmtHandle);
  1106. // if no more row, break
  1107. if Res=SQL_NO_DATA then
  1108. Break;
  1109. // handle data
  1110. if ODBCSucces(Res) then begin
  1111. // note: SQLStatistics not only returns index info, but also statistics; we skip the latter
  1112. if _Type<>SQL_TABLE_STAT then begin
  1113. if PChar(@IndexName[1])=KeyName then begin
  1114. // The indexdef is already made as the primary key
  1115. // Only if the index is descending is not known yet.
  1116. if (AscOrDescIndOrLen<>SQL_NULL_DATA) and (AscOrDesc='D') then begin
  1117. IndexDef:=IndexDefs.Find(KeyName);
  1118. IndexDef.Options:=IndexDef.Options+[ixDescending];
  1119. end;
  1120. end else if (OrdinalPos=1) or not Assigned(IndexDef) then begin
  1121. // create new IndexDef iff OrdinalPos=1 or not Assigned(IndexDef) (the latter should not occur though)
  1122. IndexDef:=IndexDefs.AddIndexDef;
  1123. IndexDef.Name:=PChar(@IndexName[1]); // treat ansistring as zero terminated string
  1124. IndexDef.Fields:=PChar(@ColName[1]);
  1125. if NonUnique=SQL_FALSE then
  1126. IndexDef.Options:=IndexDef.Options+[ixUnique];
  1127. if (AscOrDescIndOrLen<>SQL_NULL_DATA) and (AscOrDesc='D') then
  1128. IndexDef.Options:=IndexDef.Options+[ixDescending];
  1129. // TODO: figure out how we can tell whether COLUMN_NAME is an expression or not
  1130. // if it is an expression, we should include ixExpression in Options and set Expression to ColName
  1131. end else // NB we re-use the last IndexDef
  1132. IndexDef.Fields:=IndexDef.Fields+';'+PChar(@ColName[1]); // NB ; is the separator to be used for IndexDef.Fields
  1133. end;
  1134. end else begin
  1135. ODBCCheckResult(Res, SQL_HANDLE_STMT, StmtHandle, 'Could not fetch index metadata row.');
  1136. end;
  1137. until false;
  1138. finally
  1139. // unbind columns & close cursor
  1140. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_UNBIND), SQL_HANDLE_STMT, StmtHandle, 'Could not unbind columns.');
  1141. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_CLOSE), SQL_HANDLE_STMT, StmtHandle, 'Could not close cursor.');
  1142. end;
  1143. finally
  1144. if StmtHandle<>SQL_NULL_HANDLE then begin
  1145. // Free the statement handle
  1146. Res:=SQLFreeHandle(SQL_HANDLE_STMT, StmtHandle);
  1147. if Res=SQL_ERROR then
  1148. ODBCCheckResult(Res, SQL_HANDLE_STMT, STMTHandle, 'Could not free ODBC Statement handle.');
  1149. end;
  1150. end;
  1151. end;
  1152. function TODBCConnection.GetSchemaInfoSQL(SchemaType: TSchemaType; SchemaObjectName, SchemaObjectPattern: string): string;
  1153. begin
  1154. if SchemaObjectName<>'' then
  1155. Result := SchemaObjectName
  1156. else
  1157. Result := ' ';
  1158. if not (SchemaType in [stNoSchema, stTables, stColumns, stProcedures]) then
  1159. DatabaseError(SMetadataUnavailable);
  1160. end;
  1161. { TODBCEnvironment }
  1162. constructor TODBCEnvironment.Create;
  1163. begin
  1164. // make sure odbc is loaded
  1165. if ODBCLoadCount=0 then InitialiseOdbc;
  1166. Inc(ODBCLoadCount);
  1167. // allocate environment handle
  1168. if SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, FENVHandle)=SQL_Error then
  1169. 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
  1170. // set odbc version
  1171. ODBCCheckResult(
  1172. SQLSetEnvAttr(FENVHandle, SQL_ATTR_ODBC_VERSION, SQLPOINTER(SQL_OV_ODBC3), 0),
  1173. SQL_HANDLE_ENV, FENVHandle,'Could not set ODBC version to 3.'
  1174. );
  1175. end;
  1176. destructor TODBCEnvironment.Destroy;
  1177. var
  1178. Res:SQLRETURN;
  1179. begin
  1180. // free environment handle
  1181. if assigned(FENVHandle) then
  1182. begin
  1183. Res:=SQLFreeHandle(SQL_HANDLE_ENV, FENVHandle);
  1184. if Res=SQL_ERROR then
  1185. ODBCCheckResult(Res,SQL_HANDLE_ENV, FENVHandle, 'Could not free ODBC Environment handle.');
  1186. end;
  1187. // free odbc if not used by any TODBCEnvironment object anymore
  1188. if ODBCLoadCount>0 then
  1189. begin
  1190. Dec(ODBCLoadCount);
  1191. if ODBCLoadCount=0 then ReleaseOdbc;
  1192. end;
  1193. end;
  1194. { TODBCCursor }
  1195. constructor TODBCCursor.Create(Connection:TODBCConnection);
  1196. begin
  1197. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  1198. // allocate FBlobStreams
  1199. FBlobStreams:=TList.Create;
  1200. {$ENDIF}
  1201. end;
  1202. destructor TODBCCursor.Destroy;
  1203. var
  1204. Res:SQLRETURN;
  1205. begin
  1206. {$IF NOT((FPC_VERSION>=2) AND (FPC_RELEASE>=1))}
  1207. FBlobStreams.Free;
  1208. {$ENDIF}
  1209. inherited Destroy;
  1210. end;
  1211. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  1212. class function TODBCConnectionDef.TypeName: String;
  1213. begin
  1214. Result:='ODBC';
  1215. end;
  1216. class function TODBCConnectionDef.ConnectionClass: TSQLConnectionClass;
  1217. begin
  1218. Result:=TODBCConnection;
  1219. end;
  1220. class function TODBCConnectionDef.Description: String;
  1221. begin
  1222. Result:='Connect to any database via an ODBC driver';
  1223. end;
  1224. initialization
  1225. RegisterConnection(TODBCConnectionDef);
  1226. {$ENDIF}
  1227. finalization
  1228. {$IF (FPC_VERSION>=2) AND (FPC_RELEASE>=1)}
  1229. UnRegisterConnection(TODBCConnectionDef);
  1230. {$ENDIF}
  1231. if Assigned(DefaultEnvironment) then
  1232. DefaultEnvironment.Free;
  1233. end.