odbcconn.pas 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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, odbcsql;
  16. type
  17. // forward declarations
  18. TODBCConnection = class;
  19. { TODBCCursor }
  20. TODBCCursor = class(TSQLCursor)
  21. protected
  22. FSTMTHandle:SQLHSTMT; // ODBC Statement Handle
  23. FQuery:string; // last prepared query, with :ParamName converted to ?
  24. FParamIndex:TParamBinding; // maps the i-th parameter in the query to the TParams passed to PrepareStatement
  25. FParamBuf:array of pointer; // buffers that can be used to bind the i-th parameter in the query
  26. public
  27. constructor Create(Connection:TODBCConnection);
  28. destructor Destroy; override;
  29. end;
  30. { TODBCHandle } // this name is a bit confusing, but follows the standards for naming classes in sqldb
  31. TODBCHandle = class(TSQLHandle)
  32. protected
  33. end;
  34. { TODBCEnvironment }
  35. TODBCEnvironment = class
  36. protected
  37. FENVHandle:SQLHENV; // ODBC Environment Handle
  38. public
  39. constructor Create;
  40. destructor Destroy; override;
  41. end;
  42. { TODBCConnection }
  43. TODBCConnection = class(TSQLConnection)
  44. private
  45. FDriver: string;
  46. FEnvironment:TODBCEnvironment;
  47. FDBCHandle:SQLHDBC; // ODBC Connection Handle
  48. FFileDSN: string;
  49. procedure SetParameters(ODBCCursor:TODBCCursor; AParams:TParams);
  50. procedure FreeParamBuffers(ODBCCursor:TODBCCursor);
  51. protected
  52. // Overrides from TSQLConnection
  53. function GetHandle:pointer; override;
  54. // - Connect/disconnect
  55. procedure DoInternalConnect; override;
  56. procedure DoInternalDisconnect; override;
  57. // - Handle (de)allocation
  58. function AllocateCursorHandle:TSQLCursor; override;
  59. procedure DeAllocateCursorHandle(var cursor:TSQLCursor); override;
  60. function AllocateTransactionHandle:TSQLHandle; override;
  61. // - Statement handling
  62. procedure PrepareStatement(cursor:TSQLCursor; ATransaction:TSQLTransaction; buf:string; AParams:TParams); override;
  63. procedure UnPrepareStatement(cursor:TSQLCursor); override;
  64. // - Transaction handling
  65. function GetTransactionHandle(trans:TSQLHandle):pointer; override;
  66. function StartDBTransaction(trans:TSQLHandle; AParams:string):boolean; override;
  67. function Commit(trans:TSQLHandle):boolean; override;
  68. function Rollback(trans:TSQLHandle):boolean; override;
  69. procedure CommitRetaining(trans:TSQLHandle); override;
  70. procedure RollbackRetaining(trans:TSQLHandle); override;
  71. // - Statement execution
  72. procedure Execute(cursor:TSQLCursor; ATransaction:TSQLTransaction; AParams:TParams); override;
  73. // - Result retrieving
  74. procedure AddFieldDefs(cursor:TSQLCursor; FieldDefs:TFieldDefs); override;
  75. function Fetch(cursor:TSQLCursor):boolean; override;
  76. function LoadField(cursor:TSQLCursor; FieldDef:TFieldDef; buffer:pointer):boolean; override;
  77. function CreateBlobStream(Field:TField; Mode:TBlobStreamMode):TStream; override;
  78. procedure FreeFldBuffers(cursor:TSQLCursor); override;
  79. // - UpdateIndexDefs
  80. procedure UpdateIndexDefs(var IndexDefs:TIndexDefs; TableName:string); override;
  81. // - Schema info
  82. function GetSchemaInfoSQL(SchemaType:TSchemaType; SchemaObjectName, SchemaObjectPattern:string):string; override;
  83. // Internal utility functions
  84. function CreateConnectionString:string;
  85. public
  86. property Environment:TODBCEnvironment read FEnvironment;
  87. published
  88. property Driver:string read FDriver write FDriver; // will be passed as DRIVER connection parameter
  89. property FileDSN:string read FFileDSN write FFileDSN; // will be passed as FILEDSN parameter
  90. // Redeclare properties from TSQLConnection
  91. property Password; // will be passed as PWD connection parameter
  92. property Transaction;
  93. property UserName; // will be passed as UID connection parameter
  94. property CharSet;
  95. property HostName; // ignored
  96. // Redeclare properties from TDatabase
  97. property Connected;
  98. property Role;
  99. property DatabaseName; // will be passed as DSN connection parameter
  100. property KeepConnection;
  101. property LoginPrompt; // if true, ODBC drivers might prompt for more details that are not in the connection string
  102. property Params; // will be added to connection string
  103. property OnLogin;
  104. end;
  105. EODBCException = class(Exception)
  106. // currently empty; perhaps we can add fields here later that describe the error instead of one simple message string
  107. end;
  108. implementation
  109. uses
  110. Math; // for the Min proc
  111. const
  112. DefaultEnvironment:TODBCEnvironment = nil;
  113. ODBCLoadCount:integer = 0; // ODBC is loaded when > 0; modified by TODBCEnvironment.Create/Destroy
  114. { Generic ODBC helper functions }
  115. function ODBCSucces(const Res:SQLRETURN):boolean;
  116. begin
  117. Result:=(Res=SQL_SUCCESS) or (Res=SQL_SUCCESS_WITH_INFO);
  118. end;
  119. function ODBCResultToStr(Res:SQLRETURN):string;
  120. begin
  121. case Res of
  122. SQL_SUCCESS: Result:='SQL_SUCCESS';
  123. SQL_SUCCESS_WITH_INFO:Result:='SQL_SUCCESS_WITH_INFO';
  124. SQL_ERROR: Result:='SQL_ERROR';
  125. SQL_INVALID_HANDLE: Result:='SQL_INVALID_HANDLE';
  126. SQL_NO_DATA: Result:='SQL_NO_DATA';
  127. SQL_NEED_DATA: Result:='SQL_NEED_DATA';
  128. SQL_STILL_EXECUTING: Result:='SQL_STILL_EXECUTING';
  129. else
  130. Result:='';
  131. end;
  132. end;
  133. procedure ODBCCheckResult(LastReturnCode:SQLRETURN; HandleType:SQLSMALLINT; AHandle: SQLHANDLE; ErrorMsg: string);
  134. // check return value from SQLGetDiagField/Rec function itself
  135. procedure CheckSQLGetDiagResult(const Res:SQLRETURN);
  136. begin
  137. case Res of
  138. SQL_INVALID_HANDLE:
  139. raise EODBCException.Create('Invalid handle passed to SQLGetDiagRec/Field');
  140. SQL_ERROR:
  141. raise EODBCException.Create('An invalid parameter was passed to SQLGetDiagRec/Field');
  142. SQL_NO_DATA:
  143. raise EODBCException.Create('A too large RecNumber was passed to SQLGetDiagRec/Field');
  144. end;
  145. end;
  146. var
  147. NativeError:SQLINTEGER;
  148. TextLength:SQLSMALLINT;
  149. Res:SQLRETURN;
  150. SqlState,MessageText,TotalMessage:string;
  151. RecNumber:SQLSMALLINT;
  152. begin
  153. // check result
  154. if ODBCSucces(LastReturnCode) then
  155. Exit; // no error; all is ok
  156. // build TotalMessage for exception to throw
  157. TotalMessage:=Format('%s ODBC error details:',[ErrorMsg]);
  158. // retrieve status records
  159. SetLength(SqlState,5); // SqlState buffer
  160. RecNumber:=1;
  161. repeat
  162. // dummy call to get correct TextLength
  163. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(SqlState[1]),0,TextLength);
  164. if Res=SQL_NO_DATA then
  165. Break; // no more status records
  166. CheckSQLGetDiagResult(Res);
  167. 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
  168. begin
  169. // allocate large enough buffer
  170. SetLength(MessageText,TextLength); // note: ansistrings of Length>0 are always terminated by a #0 character, so this is safe
  171. // actual call
  172. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(MessageText[1]),Length(MessageText)+1,TextLength);
  173. CheckSQLGetDiagResult(Res);
  174. end;
  175. // add to TotalMessage
  176. TotalMessage:=TotalMessage + Format(' Record %d: SqlState: %s; NativeError: %d; Message: %s;',[RecNumber,SqlState,NativeError,MessageText]);
  177. // incement counter
  178. Inc(RecNumber);
  179. until false;
  180. // raise error
  181. raise EODBCException.Create(TotalMessage);
  182. end;
  183. { TODBCConnection }
  184. // Creates a connection string using the current value of the fields
  185. function TODBCConnection.CreateConnectionString: string;
  186. // encloses a param value with braces if necessary, i.e. when any of the characters []{}(),;?*=!@ is in the value
  187. function EscapeParamValue(const s:string):string;
  188. var
  189. NeedEscape:boolean;
  190. i:integer;
  191. begin
  192. NeedEscape:=false;
  193. for i:=1 to Length(s) do
  194. if s[i] in ['[',']','{','}','(',')',',','*','=','!','@'] then
  195. begin
  196. NeedEscape:=true;
  197. Break;
  198. end;
  199. if NeedEscape then
  200. Result:='{'+s+'}'
  201. else
  202. Result:=s;
  203. end;
  204. var
  205. i: Integer;
  206. Param: string;
  207. EqualSignPos:integer;
  208. begin
  209. Result:='';
  210. if DatabaseName<>'' then Result:=Result + 'DSN='+EscapeParamValue(DatabaseName)+';';
  211. if Driver <>'' then Result:=Result + 'DRIVER='+EscapeParamValue(Driver)+';';
  212. if UserName <>'' then Result:=Result + 'UID='+EscapeParamValue(UserName)+';PWD='+EscapeParamValue(Password)+';';
  213. if FileDSN <>'' then Result:=Result + 'FILEDSN='+EscapeParamValue(FileDSN)+'';
  214. for i:=0 to Params.Count-1 do
  215. begin
  216. Param:=Params[i];
  217. EqualSignPos:=Pos('=',Param);
  218. if EqualSignPos=0 then
  219. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; can''t find a ''='' in ''%s''',[i, Param])
  220. else if EqualSignPos=1 then
  221. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; no identifier before the ''='' in ''%s''',[i, Param])
  222. else
  223. Result:=Result + EscapeParamValue(Copy(Param,1,EqualSignPos-1))+'='+EscapeParamValue(Copy(Param,EqualSignPos+1,MaxInt))+';';
  224. end;
  225. end;
  226. procedure TODBCConnection.SetParameters(ODBCCursor: TODBCCursor; AParams: TParams);
  227. var
  228. ParamIndex:integer;
  229. Buf:pointer;
  230. I:integer;
  231. IntVal:longint;
  232. StrVal:string;
  233. StrLen:SQLINTEGER;
  234. begin
  235. // Note: it is assumed that AParams is the same as the one passed to PrepareStatement, in the sense that
  236. // the parameters have the same order and names
  237. if Length(ODBCCursor.FParamIndex)>0 then
  238. if not Assigned(AParams) then
  239. raise EODBCException.CreateFmt('The query has parameter markers in it, but no actual parameters were passed',[]);
  240. SetLength(ODBCCursor.FParamBuf, Length(ODBCCursor.FParamIndex));
  241. for i:=0 to High(ODBCCursor.FParamIndex) do
  242. begin
  243. ParamIndex:=ODBCCursor.FParamIndex[i];
  244. if (ParamIndex<0) or (ParamIndex>=AParams.Count) then
  245. raise EODBCException.CreateFmt('Parameter %d in query does not have a matching parameter set',[i]);
  246. case AParams[ParamIndex].DataType of
  247. ftInteger:
  248. begin
  249. Buf:=GetMem(4);
  250. IntVal:=AParams[ParamIndex].AsInteger;
  251. Move(IntVal,Buf^,4);
  252. ODBCCursor.FParamBuf[i]:=Buf;
  253. ODBCCheckResult(
  254. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  255. i+1, // ParameterNumber
  256. SQL_PARAM_INPUT, // InputOutputType
  257. SQL_C_LONG, // ValueType
  258. SQL_INTEGER, // ParameterType
  259. 10, // ColumnSize
  260. 0, // DecimalDigits
  261. Buf, // ParameterValuePtr
  262. 0, // BufferLength
  263. nil), // StrLen_or_IndPtr
  264. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not bind parameter %d',[i])
  265. );
  266. end;
  267. ftString:
  268. begin
  269. StrVal:=AParams[ParamIndex].AsString;
  270. StrLen:=Length(StrVal);
  271. Buf:=GetMem(SizeOf(SQLINTEGER)+StrLen);
  272. Move(StrLen, buf^, SizeOf(SQLINTEGER));
  273. Move(StrVal[1],(buf+SizeOf(SQLINTEGER))^,StrLen);
  274. ODBCCursor.FParamBuf[i]:=Buf;
  275. ODBCCheckResult(
  276. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  277. i+1, // ParameterNumber
  278. SQL_PARAM_INPUT, // InputOutputType
  279. SQL_C_CHAR, // ValueType
  280. SQL_CHAR, // ParameterType
  281. StrLen, // ColumnSize
  282. 0, // DecimalDigits
  283. buf+SizeOf(SQLINTEGER), // ParameterValuePtr
  284. StrLen, // BufferLength
  285. Buf), // StrLen_or_IndPtr
  286. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not bind parameter %d',[i])
  287. );
  288. end;
  289. else
  290. raise EDataBaseError.CreateFmt('Parameter %d is of type %s, which not supported yet',[ParamIndex, Fieldtypenames[AParams[ParamIndex].DataType]]);
  291. end;
  292. end;
  293. end;
  294. procedure TODBCConnection.FreeParamBuffers(ODBCCursor: TODBCCursor);
  295. var
  296. i:integer;
  297. begin
  298. for i:=0 to High(ODBCCursor.FParamBuf) do
  299. FreeMem(ODBCCursor.FParamBuf[i]);
  300. end;
  301. function TODBCConnection.GetHandle: pointer;
  302. begin
  303. // I'm not sure whether this is correct; perhaps we should return nil
  304. // note that FDBHandle is a LongInt, because ODBC handles are integers, not pointers
  305. // I wonder how this will work on 64 bit platforms then (FK)
  306. Result:=pointer(PtrInt(FDBCHandle));
  307. end;
  308. procedure TODBCConnection.DoInternalConnect;
  309. const
  310. BufferLength = 1024; // should be at least 1024 according to the ODBC specification
  311. var
  312. ConnectionString:string;
  313. OutConnectionString:string;
  314. ActualLength:SQLSMALLINT;
  315. begin
  316. inherited DoInternalConnect;
  317. // make sure we have an environment
  318. if not Assigned(FEnvironment) then
  319. begin
  320. if not Assigned(DefaultEnvironment) then
  321. DefaultEnvironment:=TODBCEnvironment.Create;
  322. FEnvironment:=DefaultEnvironment;
  323. end;
  324. // allocate connection handle
  325. ODBCCheckResult(
  326. SQLAllocHandle(SQL_HANDLE_DBC,Environment.FENVHandle,FDBCHandle),
  327. SQL_HANDLE_ENV,Environment.FENVHandle,'Could not allocate ODBC Connection handle.'
  328. );
  329. // connect
  330. ConnectionString:=CreateConnectionString;
  331. SetLength(OutConnectionString,BufferLength-1); // allocate completed connection string buffer (using the ansistring #0 trick)
  332. ODBCCheckResult(
  333. SQLDriverConnect(FDBCHandle, // the ODBC connection handle
  334. nil, // no parent window (would be required for prompts)
  335. PChar(ConnectionString), // the connection string
  336. Length(ConnectionString), // connection string length
  337. @(OutConnectionString[1]),// buffer for storing the completed connection string
  338. BufferLength, // length of the buffer
  339. ActualLength, // the actual length of the completed connection string
  340. SQL_DRIVER_NOPROMPT), // don't prompt for password etc.
  341. SQL_HANDLE_DBC,FDBCHandle,Format('Could not connect with connection string "%s".',[ConnectionString])
  342. );
  343. // commented out as the OutConenctionString is not used further at the moment
  344. // if ActualLength<BufferLength-1 then
  345. // SetLength(OutConnectionString,ActualLength); // fix completed connection string length
  346. // set connection attributes (none yet)
  347. end;
  348. procedure TODBCConnection.DoInternalDisconnect;
  349. var
  350. Res:SQLRETURN;
  351. begin
  352. inherited DoInternalDisconnect;
  353. // disconnect
  354. ODBCCheckResult(
  355. SQLDisconnect(FDBCHandle),
  356. SQL_HANDLE_DBC,FDBCHandle,'Could not disconnect.'
  357. );
  358. // deallocate connection handle
  359. Res:=SQLFreeHandle(SQL_HANDLE_DBC, FDBCHandle);
  360. if Res=SQL_ERROR then
  361. ODBCCheckResult(Res,SQL_HANDLE_DBC,FDBCHandle,'Could not free connection handle.');
  362. end;
  363. function TODBCConnection.AllocateCursorHandle: TSQLCursor;
  364. begin
  365. Result:=TODBCCursor.Create(self);
  366. end;
  367. procedure TODBCConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  368. begin
  369. // make sure we don't deallocate the cursor if the connection was lost already
  370. if not Connected then
  371. (cursor as TODBCCursor).FSTMTHandle:=SQL_INVALID_HANDLE;
  372. FreeAndNil(cursor); // the destructor of TODBCCursor frees the ODBC Statement handle
  373. end;
  374. function TODBCConnection.AllocateTransactionHandle: TSQLHandle;
  375. begin
  376. Result:=nil; // not yet supported; will move connection handles to transaction handles later
  377. end;
  378. procedure TODBCConnection.PrepareStatement(cursor: TSQLCursor; ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  379. var
  380. ODBCCursor:TODBCCursor;
  381. begin
  382. ODBCCursor:=cursor as TODBCCursor;
  383. // Parameter handling
  384. // Note: We can only pass ? parameters to ODBC, so we should convert named parameters like :MyID
  385. // ODBCCursor.FParamIndex will map th i-th ? token in the (modified) query to an index for AParams
  386. // Parse the SQL and build FParamIndex
  387. if assigned(AParams) and (AParams.count > 0) then
  388. buf := AParams.ParseSQL(buf,false,psInterbase,ODBCCursor.FParamIndex);
  389. // prepare statement
  390. ODBCCheckResult(
  391. SQLPrepare(ODBCCursor.FSTMTHandle, PChar(buf), Length(buf)),
  392. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not prepare statement.'
  393. );
  394. ODBCCursor.FQuery:=Buf;
  395. end;
  396. procedure TODBCConnection.UnPrepareStatement(cursor: TSQLCursor);
  397. begin
  398. // not necessary in ODBC
  399. end;
  400. function TODBCConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  401. begin
  402. // Tranactions not implemented yet
  403. end;
  404. function TODBCConnection.StartDBTransaction(trans: TSQLHandle; AParams:string): boolean;
  405. begin
  406. // Tranactions not implemented yet
  407. end;
  408. function TODBCConnection.Commit(trans: TSQLHandle): boolean;
  409. begin
  410. // Tranactions not implemented yet
  411. end;
  412. function TODBCConnection.Rollback(trans: TSQLHandle): boolean;
  413. begin
  414. // Tranactions not implemented yet
  415. end;
  416. procedure TODBCConnection.CommitRetaining(trans: TSQLHandle);
  417. begin
  418. // Tranactions not implemented yet
  419. end;
  420. procedure TODBCConnection.RollbackRetaining(trans: TSQLHandle);
  421. begin
  422. // Tranactions not implemented yet
  423. end;
  424. procedure TODBCConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  425. var
  426. ODBCCursor:TODBCCursor;
  427. begin
  428. ODBCCursor:=cursor as TODBCCursor;
  429. // set parameters
  430. SetParameters(ODBCCursor, AParams);
  431. // execute the statement
  432. ODBCCheckResult(
  433. SQLExecute(ODBCCursor.FSTMTHandle),
  434. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not execute statement.'
  435. );
  436. // free parameter buffers
  437. FreeParamBuffers(ODBCCursor);
  438. end;
  439. function TODBCConnection.Fetch(cursor: TSQLCursor): boolean;
  440. var
  441. ODBCCursor:TODBCCursor;
  442. Res:SQLRETURN;
  443. begin
  444. ODBCCursor:=cursor as TODBCCursor;
  445. // fetch new row
  446. Res:=SQLFetch(ODBCCursor.FSTMTHandle);
  447. if Res<>SQL_NO_DATA then
  448. ODBCCheckResult(Res,SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not fetch new row from result set');
  449. // result is true iff a new row was available
  450. Result:=Res<>SQL_NO_DATA;
  451. end;
  452. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer): boolean;
  453. var
  454. ODBCCursor:TODBCCursor;
  455. StrLenOrInd:SQLINTEGER;
  456. ODBCDateStruct:SQL_DATE_STRUCT;
  457. ODBCTimeStruct:SQL_TIME_STRUCT;
  458. ODBCTimeStampStruct:SQL_TIMESTAMP_STRUCT;
  459. DateTime:TDateTime;
  460. Res:SQLRETURN;
  461. begin
  462. ODBCCursor:=cursor as TODBCCursor;
  463. // load the field using SQLGetData
  464. // Note: optionally we can implement the use of SQLBindCol later for even more speed
  465. // TODO: finish this
  466. case FieldDef.DataType of
  467. ftFixedChar,ftString: // are both mapped to TStringField
  468. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_CHAR, buffer, FieldDef.Size, @StrLenOrInd);
  469. ftSmallint: // mapped to TSmallintField
  470. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SSHORT, buffer, SizeOf(Smallint), @StrLenOrInd);
  471. ftInteger,ftWord: // mapped to TLongintField
  472. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SLONG, buffer, SizeOf(Longint), @StrLenOrInd);
  473. ftLargeint: // mapped to TLargeintField
  474. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SBIGINT, buffer, SizeOf(Largeint), @StrLenOrInd);
  475. ftFloat: // mapped to TFloatField
  476. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_DOUBLE, buffer, SizeOf(Double), @StrLenOrInd);
  477. ftTime: // mapped to TTimeField
  478. begin
  479. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIME, @ODBCTimeStruct, SizeOf(SQL_TIME_STRUCT), @StrLenOrInd);
  480. DateTime:=TimeStructToDateTime(@ODBCTimeStruct);
  481. Move(DateTime, buffer^, SizeOf(TDateTime));
  482. end;
  483. ftDate: // mapped to TDateField
  484. begin
  485. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_DATE, @ODBCDateStruct, SizeOf(SQL_DATE_STRUCT), @StrLenOrInd);
  486. DateTime:=DateStructToDateTime(@ODBCDateStruct);
  487. Move(DateTime, buffer^, SizeOf(TDateTime));
  488. end;
  489. ftDateTime: // mapped to TDateTimeField
  490. begin
  491. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIMESTAMP, @ODBCTimeStampStruct, SizeOf(SQL_TIMESTAMP_STRUCT), @StrLenOrInd);
  492. DateTime:=TimeStampStructToDateTime(@ODBCTimeStampStruct);
  493. Move(DateTime, buffer^, SizeOf(TDateTime));
  494. end;
  495. ftBoolean: // mapped to TBooleanField
  496. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BIT, buffer, SizeOf(Wordbool), @StrLenOrInd);
  497. ftBytes: // mapped to TBytesField
  498. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  499. ftVarBytes: // mapped to TVarBytesField
  500. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  501. // TODO: Loading of other field types
  502. else
  503. raise EODBCException.CreateFmt('Tried to load field of unsupported field type %s',[Fieldtypenames[FieldDef.DataType]]);
  504. end;
  505. ODBCCheckResult(Res,SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  506. Result:=StrLenOrInd<>SQL_NULL_DATA; // Result indicates whether the value is non-null
  507. // writeln(Format('Field.Size: %d; StrLenOrInd: %d',[FieldDef.Size, StrLenOrInd]));
  508. end;
  509. function TODBCConnection.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
  510. begin
  511. // TODO: implement TODBCConnection.CreateBlobStream
  512. Result:=nil;
  513. end;
  514. procedure TODBCConnection.FreeFldBuffers(cursor: TSQLCursor);
  515. var
  516. ODBCCursor:TODBCCursor;
  517. begin
  518. ODBCCursor:=cursor as TODBCCursor;
  519. ODBCCheckResult(
  520. SQLFreeStmt(ODBCCursor.FSTMTHandle, SQL_CLOSE),
  521. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not close ODBC statement cursor.'
  522. );
  523. end;
  524. procedure TODBCConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TFieldDefs);
  525. const
  526. ColNameDefaultLength = 40; // should be > 0, because an ansistring of length 0 is a nil pointer instead of a pointer to a #0
  527. var
  528. ODBCCursor:TODBCCursor;
  529. ColumnCount:SQLSMALLINT;
  530. i:integer;
  531. ColNameLength,DataType,DecimalDigits,Nullable:SQLSMALLINT;
  532. ColumnSize:SQLUINTEGER;
  533. ColName:string;
  534. FieldType:TFieldType;
  535. FieldSize:word;
  536. begin
  537. ODBCCursor:=cursor as TODBCCursor;
  538. // get number of columns in result set
  539. ODBCCheckResult(
  540. SQLNumResultCols(ODBCCursor.FSTMTHandle, ColumnCount),
  541. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not determine number of columns in result set.'
  542. );
  543. for i:=1 to ColumnCount do
  544. begin
  545. SetLength(ColName,ColNameDefaultLength); // also garantuees uniqueness
  546. // call with default column name buffer
  547. ODBCCheckResult(
  548. SQLDescribeCol(ODBCCursor.FSTMTHandle, // statement handle
  549. i, // column number, is 1-based (Note: column 0 is the bookmark column in ODBC)
  550. @(ColName[1]), // default buffer
  551. ColNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  552. ColNameLength, // actual column name length
  553. DataType, // the SQL datatype for the column
  554. ColumnSize, // column size
  555. DecimalDigits, // number of decimal digits
  556. Nullable), // SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
  557. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get column properties for column %d.',[i])
  558. );
  559. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  560. SetLength(ColName,ColNameLength);
  561. // check whether entire column name was returned
  562. if ColNameLength>ColNameDefaultLength then
  563. begin
  564. // request column name with buffer that is long enough
  565. ODBCCheckResult(
  566. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  567. i, // column number
  568. SQL_DESC_NAME, // the column name or alias
  569. @(ColName[1]), // buffer
  570. ColNameLength+1, // buffer size
  571. @ColNameLength, // actual length
  572. nil), // no numerical output
  573. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get column name for column %d.',[i])
  574. );
  575. end;
  576. // convert type
  577. // NOTE: I made some guesses here after I found only limited information about TFieldType; please report any problems
  578. case DataType of
  579. SQL_CHAR: begin FieldType:=ftFixedChar; FieldSize:=ColumnSize+1; end;
  580. SQL_VARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end;
  581. SQL_LONGVARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end; // no fixed maximum length; make ftMemo when blobs are supported
  582. SQL_WCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end;
  583. SQL_WVARCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end;
  584. SQL_WLONGVARCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end; // no fixed maximum length; make ftMemo when blobs are supported
  585. SQL_DECIMAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  586. SQL_NUMERIC: begin FieldType:=ftFloat; FieldSize:=0; end;
  587. SQL_SMALLINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  588. SQL_INTEGER: begin FieldType:=ftInteger; FieldSize:=0; end;
  589. SQL_REAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  590. SQL_FLOAT: begin FieldType:=ftFloat; FieldSize:=0; end;
  591. SQL_DOUBLE: begin FieldType:=ftFloat; FieldSize:=0; end;
  592. SQL_BIT: begin FieldType:=ftBoolean; FieldSize:=0; end;
  593. SQL_TINYINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  594. SQL_BIGINT: begin FieldType:=ftLargeint; FieldSize:=0; end;
  595. SQL_BINARY: begin FieldType:=ftBytes; FieldSize:=ColumnSize; end;
  596. SQL_VARBINARY: begin FieldType:=ftVarBytes; FieldSize:=ColumnSize; end;
  597. SQL_LONGVARBINARY: begin FieldType:=ftBlob; FieldSize:=ColumnSize; end;
  598. SQL_TYPE_DATE: begin FieldType:=ftDate; FieldSize:=0; end;
  599. SQL_TYPE_TIME: begin FieldType:=ftTime; FieldSize:=0; end;
  600. SQL_TYPE_TIMESTAMP:begin FieldType:=ftTimeStamp; FieldSize:=0; end;
  601. { SQL_TYPE_UTCDATETIME:FieldType:=ftUnknown;}
  602. { SQL_TYPE_UTCTIME: FieldType:=ftUnknown; }
  603. { SQL_INTERVAL_MONTH: FieldType:=ftUnknown;}
  604. { SQL_INTERVAL_YEAR: FieldType:=ftUnknown;}
  605. { SQL_INTERVAL_YEAR_TO_MONTH: FieldType:=ftUnknown;}
  606. { SQL_INTERVAL_DAY: FieldType:=ftUnknown;}
  607. { SQL_INTERVAL_HOUR: FieldType:=ftUnknown;}
  608. { SQL_INTERVAL_MINUTE: FieldType:=ftUnknown;}
  609. { SQL_INTERVAL_SECOND: FieldType:=ftUnknown;}
  610. { SQL_INTERVAL_DAY_TO_HOUR: FieldType:=ftUnknown;}
  611. { SQL_INTERVAL_DAY_TO_MINUTE: FieldType:=ftUnknown;}
  612. { SQL_INTERVAL_DAY_TO_SECOND: FieldType:=ftUnknown;}
  613. { SQL_INTERVAL_HOUR_TO_MINUTE: FieldType:=ftUnknown;}
  614. { SQL_INTERVAL_HOUR_TO_SECOND: FieldType:=ftUnknown;}
  615. { SQL_INTERVAL_MINUTE_TO_SECOND:FieldType:=ftUnknown;}
  616. { SQL_GUID: begin FieldType:=ftGuid; FieldSize:=ColumnSize; end; } // no TGuidField exists yet in the db unit
  617. else
  618. begin FieldType:=ftUnknown; FieldSize:=ColumnSize; end
  619. end;
  620. // add FieldDef
  621. TFieldDef.Create(FieldDefs, ColName, FieldType, FieldSize, False, i);
  622. end;
  623. end;
  624. procedure TODBCConnection.UpdateIndexDefs(var IndexDefs: TIndexDefs; TableName: string);
  625. begin
  626. inherited UpdateIndexDefs(IndexDefs, TableName);
  627. // TODO: implement this
  628. end;
  629. function TODBCConnection.GetSchemaInfoSQL(SchemaType: TSchemaType; SchemaObjectName, SchemaObjectPattern: string): string;
  630. begin
  631. Result:=inherited GetSchemaInfoSQL(SchemaType, SchemaObjectName, SchemaObjectPattern);
  632. // TODO: implement this
  633. end;
  634. { TODBCEnvironment }
  635. constructor TODBCEnvironment.Create;
  636. begin
  637. // make sure odbc is loaded
  638. if ODBCLoadCount=0 then LoadOdbc;
  639. Inc(ODBCLoadCount);
  640. // allocate environment handle
  641. if SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, FENVHandle)=SQL_Error then
  642. 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
  643. // set odbc version
  644. ODBCCheckResult(
  645. SQLSetEnvAttr(FENVHandle, SQL_ATTR_ODBC_VERSION, SQLPOINTER(SQL_OV_ODBC3), 0),
  646. SQL_HANDLE_ENV, FENVHandle,'Could not set ODBC version to 3.'
  647. );
  648. end;
  649. destructor TODBCEnvironment.Destroy;
  650. var
  651. Res:SQLRETURN;
  652. begin
  653. // free environment handle
  654. Res:=SQLFreeHandle(SQL_HANDLE_ENV, FENVHandle);
  655. if Res=SQL_ERROR then
  656. ODBCCheckResult(Res,SQL_HANDLE_ENV, FENVHandle, 'Could not free ODBC Environment handle.');
  657. // free odbc if not used by any TODBCEnvironment object anymore
  658. Dec(ODBCLoadCount);
  659. if ODBCLoadCount=0 then UnLoadOdbc;
  660. end;
  661. { TODBCCursor }
  662. constructor TODBCCursor.Create(Connection:TODBCConnection);
  663. begin
  664. // allocate statement handle
  665. ODBCCheckResult(
  666. SQLAllocHandle(SQL_HANDLE_STMT, Connection.FDBCHandle, FSTMTHandle),
  667. SQL_HANDLE_DBC, Connection.FDBCHandle, 'Could not allocate ODBC Statement handle.'
  668. );
  669. end;
  670. destructor TODBCCursor.Destroy;
  671. var
  672. Res:SQLRETURN;
  673. begin
  674. inherited Destroy;
  675. if FSTMTHandle<>SQL_INVALID_HANDLE then
  676. begin
  677. // deallocate statement handle
  678. Res:=SQLFreeHandle(SQL_HANDLE_STMT, FSTMTHandle);
  679. if Res=SQL_ERROR then
  680. ODBCCheckResult(Res,SQL_HANDLE_STMT, FSTMTHandle, 'Could not free ODBC Statement handle.');
  681. end;
  682. end;
  683. { finalization }
  684. finalization
  685. if Assigned(DefaultEnvironment) then
  686. DefaultEnvironment.Free;
  687. end.