odbcconn.pas 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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):boolean; override;
  78. function CreateBlobStream(Field:TField; Mode:TBlobStreamMode):TStream; override;
  79. procedure FreeFldBuffers(cursor:TSQLCursor); override;
  80. // - UpdateIndexDefs
  81. procedure UpdateIndexDefs(var IndexDefs:TIndexDefs; TableName:string); override;
  82. // - Schema info
  83. function GetSchemaInfoSQL(SchemaType:TSchemaType; SchemaObjectName, SchemaObjectPattern:string):string; override;
  84. // Internal utility functions
  85. function CreateConnectionString:string;
  86. public
  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. procedure TODBCConnection.SetParameters(ODBCCursor: TODBCCursor; AParams: TParams);
  228. var
  229. ParamIndex:integer;
  230. Buf:pointer;
  231. I:integer;
  232. IntVal:longint;
  233. StrVal:string;
  234. StrLen:SQLINTEGER;
  235. begin
  236. // Note: it is assumed that AParams is the same as the one passed to PrepareStatement, in the sense that
  237. // the parameters have the same order and names
  238. if Length(ODBCCursor.FParamIndex)>0 then
  239. if not Assigned(AParams) then
  240. raise EODBCException.CreateFmt('The query has parameter markers in it, but no actual parameters were passed',[]);
  241. SetLength(ODBCCursor.FParamBuf, Length(ODBCCursor.FParamIndex));
  242. for i:=0 to High(ODBCCursor.FParamIndex) do
  243. begin
  244. ParamIndex:=ODBCCursor.FParamIndex[i];
  245. if (ParamIndex<0) or (ParamIndex>=AParams.Count) then
  246. raise EODBCException.CreateFmt('Parameter %d in query does not have a matching parameter set',[i]);
  247. case AParams[ParamIndex].DataType of
  248. ftInteger:
  249. begin
  250. Buf:=GetMem(4);
  251. IntVal:=AParams[ParamIndex].AsInteger;
  252. Move(IntVal,Buf^,4);
  253. ODBCCursor.FParamBuf[i]:=Buf;
  254. ODBCCheckResult(
  255. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  256. i+1, // ParameterNumber
  257. SQL_PARAM_INPUT, // InputOutputType
  258. SQL_C_LONG, // ValueType
  259. SQL_INTEGER, // ParameterType
  260. 10, // ColumnSize
  261. 0, // DecimalDigits
  262. Buf, // ParameterValuePtr
  263. 0, // BufferLength
  264. nil), // StrLen_or_IndPtr
  265. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not bind parameter %d',[i])
  266. );
  267. end;
  268. ftString:
  269. begin
  270. StrVal:=AParams[ParamIndex].AsString;
  271. StrLen:=Length(StrVal);
  272. Buf:=GetMem(SizeOf(SQLINTEGER)+StrLen);
  273. Move(StrLen, buf^, SizeOf(SQLINTEGER));
  274. Move(StrVal[1],(buf+SizeOf(SQLINTEGER))^,StrLen);
  275. ODBCCursor.FParamBuf[i]:=Buf;
  276. ODBCCheckResult(
  277. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  278. i+1, // ParameterNumber
  279. SQL_PARAM_INPUT, // InputOutputType
  280. SQL_C_CHAR, // ValueType
  281. SQL_CHAR, // ParameterType
  282. StrLen, // ColumnSize
  283. 0, // DecimalDigits
  284. buf+SizeOf(SQLINTEGER), // ParameterValuePtr
  285. StrLen, // BufferLength
  286. Buf), // StrLen_or_IndPtr
  287. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not bind parameter %d',[i])
  288. );
  289. end;
  290. else
  291. raise EDataBaseError.CreateFmt('Parameter %d is of type %s, which not supported yet',[ParamIndex, Fieldtypenames[AParams[ParamIndex].DataType]]);
  292. end;
  293. end;
  294. end;
  295. procedure TODBCConnection.FreeParamBuffers(ODBCCursor: TODBCCursor);
  296. var
  297. i:integer;
  298. begin
  299. for i:=0 to High(ODBCCursor.FParamBuf) do
  300. FreeMem(ODBCCursor.FParamBuf[i]);
  301. SetLength(ODBCCursor.FParamBuf,0);
  302. end;
  303. function TODBCConnection.GetHandle: pointer;
  304. begin
  305. // I'm not sure whether this is correct; perhaps we should return nil
  306. // note that FDBHandle is a LongInt, because ODBC handles are integers, not pointers
  307. // I wonder how this will work on 64 bit platforms then (FK)
  308. Result:=pointer(PtrInt(FDBCHandle));
  309. end;
  310. procedure TODBCConnection.DoInternalConnect;
  311. const
  312. BufferLength = 1024; // should be at least 1024 according to the ODBC specification
  313. var
  314. ConnectionString:string;
  315. OutConnectionString:string;
  316. ActualLength:SQLSMALLINT;
  317. begin
  318. // Do not call the inherited method as it checks for a non-empty DatabaseName, and we don't even use DatabaseName!
  319. // inherited DoInternalConnect;
  320. // make sure we have an environment
  321. if not Assigned(FEnvironment) then
  322. begin
  323. if not Assigned(DefaultEnvironment) then
  324. DefaultEnvironment:=TODBCEnvironment.Create;
  325. FEnvironment:=DefaultEnvironment;
  326. end;
  327. // allocate connection handle
  328. ODBCCheckResult(
  329. SQLAllocHandle(SQL_HANDLE_DBC,Environment.FENVHandle,FDBCHandle),
  330. SQL_HANDLE_ENV,Environment.FENVHandle,'Could not allocate ODBC Connection handle.'
  331. );
  332. // connect
  333. ConnectionString:=CreateConnectionString;
  334. SetLength(OutConnectionString,BufferLength-1); // allocate completed connection string buffer (using the ansistring #0 trick)
  335. ODBCCheckResult(
  336. SQLDriverConnect(FDBCHandle, // the ODBC connection handle
  337. nil, // no parent window (would be required for prompts)
  338. PChar(ConnectionString), // the connection string
  339. Length(ConnectionString), // connection string length
  340. @(OutConnectionString[1]),// buffer for storing the completed connection string
  341. BufferLength, // length of the buffer
  342. ActualLength, // the actual length of the completed connection string
  343. SQL_DRIVER_NOPROMPT), // don't prompt for password etc.
  344. SQL_HANDLE_DBC,FDBCHandle,Format('Could not connect with connection string "%s".',[ConnectionString])
  345. );
  346. // commented out as the OutConnectionString is not used further at the moment
  347. // if ActualLength<BufferLength-1 then
  348. // SetLength(OutConnectionString,ActualLength); // fix completed connection string length
  349. // set connection attributes (none yet)
  350. end;
  351. procedure TODBCConnection.DoInternalDisconnect;
  352. var
  353. Res:SQLRETURN;
  354. begin
  355. inherited DoInternalDisconnect;
  356. // disconnect
  357. ODBCCheckResult(
  358. SQLDisconnect(FDBCHandle),
  359. SQL_HANDLE_DBC,FDBCHandle,'Could not disconnect.'
  360. );
  361. // deallocate connection handle
  362. Res:=SQLFreeHandle(SQL_HANDLE_DBC, FDBCHandle);
  363. if Res=SQL_ERROR then
  364. ODBCCheckResult(Res,SQL_HANDLE_DBC,FDBCHandle,'Could not free connection handle.');
  365. end;
  366. function TODBCConnection.AllocateCursorHandle: TSQLCursor;
  367. begin
  368. Result:=TODBCCursor.Create(self);
  369. end;
  370. procedure TODBCConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  371. begin
  372. // make sure we don't deallocate the cursor if the connection was lost already
  373. if not Connected then
  374. (cursor as TODBCCursor).FSTMTHandle:=SQL_INVALID_HANDLE;
  375. FreeAndNil(cursor); // the destructor of TODBCCursor frees the ODBC Statement handle
  376. end;
  377. function TODBCConnection.AllocateTransactionHandle: TSQLHandle;
  378. begin
  379. Result:=nil; // not yet supported; will move connection handles to transaction handles later
  380. end;
  381. procedure TODBCConnection.PrepareStatement(cursor: TSQLCursor; ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  382. var
  383. ODBCCursor:TODBCCursor;
  384. begin
  385. ODBCCursor:=cursor as TODBCCursor;
  386. // Parameter handling
  387. // Note: We can only pass ? parameters to ODBC, so we should convert named parameters like :MyID
  388. // ODBCCursor.FParamIndex will map th i-th ? token in the (modified) query to an index for AParams
  389. // Parse the SQL and build FParamIndex
  390. if assigned(AParams) and (AParams.count > 0) then
  391. buf := AParams.ParseSQL(buf,false,psInterbase,ODBCCursor.FParamIndex);
  392. // prepare statement
  393. ODBCCheckResult(
  394. SQLPrepare(ODBCCursor.FSTMTHandle, PChar(buf), Length(buf)),
  395. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not prepare statement.'
  396. );
  397. ODBCCursor.FQuery:=Buf;
  398. end;
  399. procedure TODBCConnection.UnPrepareStatement(cursor: TSQLCursor);
  400. begin
  401. // not necessary in ODBC
  402. end;
  403. function TODBCConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  404. begin
  405. // Tranactions not implemented yet
  406. end;
  407. function TODBCConnection.StartDBTransaction(trans: TSQLHandle; AParams:string): boolean;
  408. begin
  409. // Tranactions not implemented yet
  410. end;
  411. function TODBCConnection.Commit(trans: TSQLHandle): boolean;
  412. begin
  413. // Tranactions not implemented yet
  414. end;
  415. function TODBCConnection.Rollback(trans: TSQLHandle): boolean;
  416. begin
  417. // Tranactions not implemented yet
  418. end;
  419. procedure TODBCConnection.CommitRetaining(trans: TSQLHandle);
  420. begin
  421. // Tranactions not implemented yet
  422. end;
  423. procedure TODBCConnection.RollbackRetaining(trans: TSQLHandle);
  424. begin
  425. // Tranactions not implemented yet
  426. end;
  427. procedure TODBCConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  428. var
  429. ODBCCursor:TODBCCursor;
  430. begin
  431. ODBCCursor:=cursor as TODBCCursor;
  432. // set parameters
  433. if Assigned(APArams) and (AParams.count > 0) then SetParameters(ODBCCursor, AParams);
  434. // execute the statement
  435. ODBCCheckResult(
  436. SQLExecute(ODBCCursor.FSTMTHandle),
  437. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not execute statement.'
  438. );
  439. // free parameter buffers
  440. FreeParamBuffers(ODBCCursor);
  441. end;
  442. function TODBCConnection.Fetch(cursor: TSQLCursor): boolean;
  443. var
  444. ODBCCursor:TODBCCursor;
  445. Res:SQLRETURN;
  446. begin
  447. ODBCCursor:=cursor as TODBCCursor;
  448. // fetch new row
  449. Res:=SQLFetch(ODBCCursor.FSTMTHandle);
  450. if Res<>SQL_NO_DATA then
  451. ODBCCheckResult(Res,SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not fetch new row from result set');
  452. // result is true iff a new row was available
  453. Result:=Res<>SQL_NO_DATA;
  454. end;
  455. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer): boolean;
  456. const
  457. DEFAULT_BLOB_BUFFER_SIZE = 1024;
  458. var
  459. ODBCCursor:TODBCCursor;
  460. StrLenOrInd:SQLINTEGER;
  461. ODBCDateStruct:SQL_DATE_STRUCT;
  462. ODBCTimeStruct:SQL_TIME_STRUCT;
  463. ODBCTimeStampStruct:SQL_TIMESTAMP_STRUCT;
  464. DateTime:TDateTime;
  465. BlobBuffer:pointer;
  466. BlobBufferSize,BytesRead:SQLINTEGER;
  467. BlobMemoryStream:TMemoryStream;
  468. Res:SQLRETURN;
  469. begin
  470. ODBCCursor:=cursor as TODBCCursor;
  471. // load the field using SQLGetData
  472. // Note: optionally we can implement the use of SQLBindCol later for even more speed
  473. // TODO: finish this
  474. case FieldDef.DataType of
  475. ftFixedChar,ftString: // are both mapped to TStringField
  476. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_CHAR, buffer, FieldDef.Size, @StrLenOrInd);
  477. ftSmallint: // mapped to TSmallintField
  478. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SSHORT, buffer, SizeOf(Smallint), @StrLenOrInd);
  479. ftInteger,ftWord: // mapped to TLongintField
  480. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SLONG, buffer, SizeOf(Longint), @StrLenOrInd);
  481. ftLargeint: // mapped to TLargeintField
  482. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SBIGINT, buffer, SizeOf(Largeint), @StrLenOrInd);
  483. ftFloat: // mapped to TFloatField
  484. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_DOUBLE, buffer, SizeOf(Double), @StrLenOrInd);
  485. ftTime: // mapped to TTimeField
  486. begin
  487. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIME, @ODBCTimeStruct, SizeOf(SQL_TIME_STRUCT), @StrLenOrInd);
  488. if StrLenOrInd<>SQL_NULL_DATA then
  489. begin
  490. DateTime:=TimeStructToDateTime(@ODBCTimeStruct);
  491. Move(DateTime, buffer^, SizeOf(TDateTime));
  492. end;
  493. end;
  494. ftDate: // mapped to TDateField
  495. begin
  496. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_DATE, @ODBCDateStruct, SizeOf(SQL_DATE_STRUCT), @StrLenOrInd);
  497. if StrLenOrInd<>SQL_NULL_DATA then
  498. begin
  499. DateTime:=DateStructToDateTime(@ODBCDateStruct);
  500. Move(DateTime, buffer^, SizeOf(TDateTime));
  501. end;
  502. end;
  503. ftDateTime: // mapped to TDateTimeField
  504. begin
  505. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIMESTAMP, @ODBCTimeStampStruct, SizeOf(SQL_TIMESTAMP_STRUCT), @StrLenOrInd);
  506. if StrLenOrInd<>SQL_NULL_DATA then
  507. begin
  508. DateTime:=TimeStampStructToDateTime(@ODBCTimeStampStruct);
  509. Move(DateTime, buffer^, SizeOf(TDateTime));
  510. end;
  511. end;
  512. ftBoolean: // mapped to TBooleanField
  513. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BIT, buffer, SizeOf(Wordbool), @StrLenOrInd);
  514. ftBytes: // mapped to TBytesField
  515. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  516. ftVarBytes: // mapped to TVarBytesField
  517. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  518. ftBlob, ftMemo: // BLOBs
  519. begin
  520. // Try to discover BLOB data length
  521. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, 0, @StrLenOrInd);
  522. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  523. // Read the data if not NULL
  524. if StrLenOrInd<>SQL_NULL_DATA then
  525. begin
  526. // Determine size of buffer to use
  527. if StrLenOrInd<>SQL_NO_TOTAL then
  528. BlobBufferSize:=StrLenOrInd
  529. else
  530. BlobBufferSize:=DEFAULT_BLOB_BUFFER_SIZE;
  531. try
  532. // init BlobBuffer and BlobMemoryStream to nil pointers
  533. BlobBuffer:=nil;
  534. BlobMemoryStream:=nil;
  535. if BlobBufferSize>0 then // Note: zero-length BLOB is represented as nil pointer in the field buffer to save memory usage
  536. begin
  537. // Allocate the buffer and memorystream
  538. BlobBuffer:=GetMem(BlobBufferSize);
  539. BlobMemoryStream:=TMemoryStream.Create;
  540. // Retrieve data in parts (or effectively in one part if StrLenOrInd<>SQL_NO_TOTAL above)
  541. repeat
  542. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, BlobBuffer, BlobBufferSize, @StrLenOrInd);
  543. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  544. // Append data in buffer to memorystream
  545. if (StrLenOrInd=SQL_NO_TOTAL) or (StrLenOrInd>BlobBufferSize) then
  546. BytesRead:=BlobBufferSize
  547. else
  548. BytesRead:=StrLenOrInd;
  549. BlobMemoryStream.Write(BlobBuffer^, BytesRead);
  550. until Res=SQL_SUCCESS;
  551. end;
  552. // Store memorystream pointer in Field buffer and in the cursor's FBlobStreams list
  553. TObject(buffer^):=BlobMemoryStream;
  554. if BlobMemoryStream<>nil then
  555. ODBCCursor.FBlobStreams.Add(BlobMemoryStream);
  556. // Set BlobMemoryStream to nil, so it won't get freed in the finally block below
  557. BlobMemoryStream:=nil;
  558. finally
  559. BlobMemoryStream.Free;
  560. if BlobBuffer<>nil then
  561. Freemem(BlobBuffer,BlobBufferSize);
  562. end;
  563. end;
  564. end;
  565. // TODO: Loading of other field types
  566. else
  567. raise EODBCException.CreateFmt('Tried to load field of unsupported field type %s',[Fieldtypenames[FieldDef.DataType]]);
  568. end;
  569. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  570. Result:=StrLenOrInd<>SQL_NULL_DATA; // Result indicates whether the value is non-null
  571. // writeln(Format('Field.Size: %d; StrLenOrInd: %d',[FieldDef.Size, StrLenOrInd]));
  572. end;
  573. function TODBCConnection.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
  574. var
  575. ODBCCursor: TODBCCursor;
  576. BlobMemoryStream, BlobMemoryStreamCopy: TMemoryStream;
  577. begin
  578. if (Mode=bmRead) and not Field.IsNull then
  579. begin
  580. Field.GetData(@BlobMemoryStream);
  581. BlobMemoryStreamCopy:=TMemoryStream.Create;
  582. if BlobMemoryStream<>nil then
  583. BlobMemoryStreamCopy.LoadFromStream(BlobMemoryStream);
  584. Result:=BlobMemoryStreamCopy;
  585. end
  586. else
  587. Result:=nil;
  588. end;
  589. procedure TODBCConnection.FreeFldBuffers(cursor: TSQLCursor);
  590. var
  591. ODBCCursor:TODBCCursor;
  592. i: integer;
  593. begin
  594. ODBCCursor:=cursor as TODBCCursor;
  595. // Free TMemoryStreams in cursor.FBlobStreams and clear it
  596. for i:=0 to ODBCCursor.FBlobStreams.Count-1 do
  597. TObject(ODBCCursor.FBlobStreams[i]).Free;
  598. ODBCCursor.FBlobStreams.Clear;
  599. ODBCCheckResult(
  600. SQLFreeStmt(ODBCCursor.FSTMTHandle, SQL_CLOSE),
  601. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not close ODBC statement cursor.'
  602. );
  603. end;
  604. procedure TODBCConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TFieldDefs);
  605. const
  606. ColNameDefaultLength = 40; // should be > 0, because an ansistring of length 0 is a nil pointer instead of a pointer to a #0
  607. TypeNameDefaultLength = 80; // idem
  608. var
  609. ODBCCursor:TODBCCursor;
  610. ColumnCount:SQLSMALLINT;
  611. i:integer;
  612. ColNameLength,TypeNameLength,DataType,DecimalDigits,Nullable:SQLSMALLINT;
  613. ColumnSize:SQLUINTEGER;
  614. ColName,TypeName:string;
  615. FieldType:TFieldType;
  616. FieldSize:word;
  617. begin
  618. ODBCCursor:=cursor as TODBCCursor;
  619. // get number of columns in result set
  620. ODBCCheckResult(
  621. SQLNumResultCols(ODBCCursor.FSTMTHandle, ColumnCount),
  622. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not determine number of columns in result set.'
  623. );
  624. for i:=1 to ColumnCount do
  625. begin
  626. SetLength(ColName,ColNameDefaultLength); // also garantuees uniqueness
  627. // call with default column name buffer
  628. ODBCCheckResult(
  629. SQLDescribeCol(ODBCCursor.FSTMTHandle, // statement handle
  630. i, // column number, is 1-based (Note: column 0 is the bookmark column in ODBC)
  631. @(ColName[1]), // default buffer
  632. ColNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  633. ColNameLength, // actual column name length
  634. DataType, // the SQL datatype for the column
  635. ColumnSize, // column size
  636. DecimalDigits, // number of decimal digits
  637. Nullable), // SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
  638. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get column properties for column %d.',[i])
  639. );
  640. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  641. SetLength(ColName,ColNameLength);
  642. // check whether entire column name was returned
  643. if ColNameLength>ColNameDefaultLength then
  644. begin
  645. // request column name with buffer that is long enough
  646. ODBCCheckResult(
  647. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  648. i, // column number
  649. SQL_DESC_NAME, // the column name or alias
  650. @(ColName[1]), // buffer
  651. ColNameLength+1, // buffer size
  652. @ColNameLength, // actual length
  653. nil), // no numerical output
  654. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get column name for column %d.',[i])
  655. );
  656. end;
  657. // convert type
  658. // NOTE: I made some guesses here after I found only limited information about TFieldType; please report any problems
  659. case DataType of
  660. SQL_CHAR: begin FieldType:=ftFixedChar; FieldSize:=ColumnSize+1; end;
  661. SQL_VARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end;
  662. SQL_LONGVARCHAR: begin FieldType:=ftMemo; FieldSize:=sizeof(pointer); end; // is a blob
  663. SQL_WCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end;
  664. SQL_WVARCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end;
  665. SQL_WLONGVARCHAR: begin FieldType:=ftMemo; FieldSize:=sizeof(pointer); end; // is a blob
  666. SQL_DECIMAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  667. SQL_NUMERIC: begin FieldType:=ftFloat; FieldSize:=0; end;
  668. SQL_SMALLINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  669. SQL_INTEGER: begin FieldType:=ftInteger; FieldSize:=0; end;
  670. SQL_REAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  671. SQL_FLOAT: begin FieldType:=ftFloat; FieldSize:=0; end;
  672. SQL_DOUBLE: begin FieldType:=ftFloat; FieldSize:=0; end;
  673. SQL_BIT: begin FieldType:=ftBoolean; FieldSize:=0; end;
  674. SQL_TINYINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  675. SQL_BIGINT: begin FieldType:=ftLargeint; FieldSize:=0; end;
  676. SQL_BINARY: begin FieldType:=ftBytes; FieldSize:=ColumnSize; end;
  677. SQL_VARBINARY: begin FieldType:=ftVarBytes; FieldSize:=ColumnSize; end;
  678. SQL_LONGVARBINARY: begin FieldType:=ftBlob; FieldSize:=sizeof(pointer); end; // is a blob
  679. SQL_TYPE_DATE: begin FieldType:=ftDate; FieldSize:=0; end;
  680. SQL_TYPE_TIME: begin FieldType:=ftTime; FieldSize:=0; end;
  681. SQL_TYPE_TIMESTAMP:begin FieldType:=ftDateTime; FieldSize:=0; end;
  682. { SQL_TYPE_UTCDATETIME:FieldType:=ftUnknown;}
  683. { SQL_TYPE_UTCTIME: FieldType:=ftUnknown;}
  684. { SQL_INTERVAL_MONTH: FieldType:=ftUnknown;}
  685. { SQL_INTERVAL_YEAR: FieldType:=ftUnknown;}
  686. { SQL_INTERVAL_YEAR_TO_MONTH: FieldType:=ftUnknown;}
  687. { SQL_INTERVAL_DAY: FieldType:=ftUnknown;}
  688. { SQL_INTERVAL_HOUR: FieldType:=ftUnknown;}
  689. { SQL_INTERVAL_MINUTE: FieldType:=ftUnknown;}
  690. { SQL_INTERVAL_SECOND: FieldType:=ftUnknown;}
  691. { SQL_INTERVAL_DAY_TO_HOUR: FieldType:=ftUnknown;}
  692. { SQL_INTERVAL_DAY_TO_MINUTE: FieldType:=ftUnknown;}
  693. { SQL_INTERVAL_DAY_TO_SECOND: FieldType:=ftUnknown;}
  694. { SQL_INTERVAL_HOUR_TO_MINUTE: FieldType:=ftUnknown;}
  695. { SQL_INTERVAL_HOUR_TO_SECOND: FieldType:=ftUnknown;}
  696. { SQL_INTERVAL_MINUTE_TO_SECOND:FieldType:=ftUnknown;}
  697. { SQL_GUID: begin FieldType:=ftGuid; FieldSize:=ColumnSize; end; } // no TGuidField exists yet in the db unit
  698. else
  699. begin FieldType:=ftUnknown; FieldSize:=ColumnSize; end
  700. end;
  701. if (FieldType in [ftString,ftFixedChar]) and // field types mapped to TStringField
  702. (FieldSize >= dsMaxStringSize) then
  703. begin
  704. FieldSize:=dsMaxStringSize-1;
  705. end;
  706. if FieldType=ftUnknown then // if unknown field type encountered, try finding more specific information about the ODBC SQL DataType
  707. begin
  708. SetLength(TypeName,TypeNameDefaultLength); // also garantuees uniqueness
  709. ODBCCheckResult(
  710. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  711. i, // column number
  712. SQL_DESC_TYPE_NAME, // FieldIdentifier indicating the datasource dependent data type name (useful for diagnostics)
  713. @(TypeName[1]), // default buffer
  714. TypeNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  715. @TypeNameLength, // actual type name length
  716. nil // no need for a pointer to return a numeric attribute at
  717. ),
  718. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get datasource dependent type name for column %s.',[ColName])
  719. );
  720. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  721. SetLength(TypeName,TypeNameLength);
  722. // check whether entire column name was returned
  723. if TypeNameLength>TypeNameDefaultLength then
  724. begin
  725. // request column name with buffer that is long enough
  726. ODBCCheckResult(
  727. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  728. i, // column number
  729. SQL_DESC_TYPE_NAME, // FieldIdentifier indicating the datasource dependent data type name (useful for diagnostics)
  730. @(TypeName[1]), // buffer
  731. TypeNameLength+1, // buffer size
  732. @TypeNameLength, // actual length
  733. nil), // no need for a pointer to return a numeric attribute at
  734. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get datasource dependent type name for column %s.',[ColName])
  735. );
  736. end;
  737. DatabaseErrorFmt('Column %s has an unknown or unsupported column type. Datasource dependent type name: %s. ODBC SQL data type code: %d.', [ColName, TypeName, DataType]);
  738. end;
  739. // add FieldDef
  740. TFieldDef.Create(FieldDefs, ColName, FieldType, FieldSize, False, i);
  741. end;
  742. end;
  743. procedure TODBCConnection.UpdateIndexDefs(var IndexDefs: TIndexDefs; TableName: string);
  744. begin
  745. inherited UpdateIndexDefs(IndexDefs, TableName);
  746. // TODO: implement this
  747. end;
  748. function TODBCConnection.GetSchemaInfoSQL(SchemaType: TSchemaType; SchemaObjectName, SchemaObjectPattern: string): string;
  749. begin
  750. Result:=inherited GetSchemaInfoSQL(SchemaType, SchemaObjectName, SchemaObjectPattern);
  751. // TODO: implement this
  752. end;
  753. { TODBCEnvironment }
  754. constructor TODBCEnvironment.Create;
  755. begin
  756. // make sure odbc is loaded
  757. if ODBCLoadCount=0 then InitialiseOdbc;
  758. Inc(ODBCLoadCount);
  759. // allocate environment handle
  760. if SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, FENVHandle)=SQL_Error then
  761. 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
  762. // set odbc version
  763. ODBCCheckResult(
  764. SQLSetEnvAttr(FENVHandle, SQL_ATTR_ODBC_VERSION, SQLPOINTER(SQL_OV_ODBC3), 0),
  765. SQL_HANDLE_ENV, FENVHandle,'Could not set ODBC version to 3.'
  766. );
  767. end;
  768. destructor TODBCEnvironment.Destroy;
  769. var
  770. Res:SQLRETURN;
  771. begin
  772. // free environment handle
  773. Res:=SQLFreeHandle(SQL_HANDLE_ENV, FENVHandle);
  774. if Res=SQL_ERROR then
  775. ODBCCheckResult(Res,SQL_HANDLE_ENV, FENVHandle, 'Could not free ODBC Environment handle.');
  776. // free odbc if not used by any TODBCEnvironment object anymore
  777. Dec(ODBCLoadCount);
  778. if ODBCLoadCount=0 then ReleaseOdbc;
  779. end;
  780. { TODBCCursor }
  781. constructor TODBCCursor.Create(Connection:TODBCConnection);
  782. begin
  783. // allocate statement handle
  784. ODBCCheckResult(
  785. SQLAllocHandle(SQL_HANDLE_STMT, Connection.FDBCHandle, FSTMTHandle),
  786. SQL_HANDLE_DBC, Connection.FDBCHandle, 'Could not allocate ODBC Statement handle.'
  787. );
  788. // allocate FBlobStreams
  789. FBlobStreams:=TList.Create;
  790. end;
  791. destructor TODBCCursor.Destroy;
  792. var
  793. Res:SQLRETURN;
  794. begin
  795. inherited Destroy;
  796. FBlobStreams.Free;
  797. if FSTMTHandle<>SQL_INVALID_HANDLE then
  798. begin
  799. // deallocate statement handle
  800. Res:=SQLFreeHandle(SQL_HANDLE_STMT, FSTMTHandle);
  801. if Res=SQL_ERROR then
  802. ODBCCheckResult(Res,SQL_HANDLE_STMT, FSTMTHandle, 'Could not free ODBC Statement handle.');
  803. end;
  804. end;
  805. { finalization }
  806. finalization
  807. if Assigned(DefaultEnvironment) then
  808. DefaultEnvironment.Free;
  809. end.