odbcconn.pas 36 KB

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