odbcconn.pas 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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 LoadBlobIntoStream(Field: TField;AStream: TStream;cursor: TSQLCursor;ATransaction : TSQLTransaction); 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. constructor Create(AOwner : TComponent); override;
  88. property Environment:TODBCEnvironment read FEnvironment;
  89. published
  90. property Driver:string read FDriver write FDriver; // will be passed as DRIVER connection parameter
  91. property FileDSN:string read FFileDSN write FFileDSN; // will be passed as FILEDSN parameter
  92. // Redeclare properties from TSQLConnection
  93. property Password; // will be passed as PWD connection parameter
  94. property Transaction;
  95. property UserName; // will be passed as UID connection parameter
  96. property CharSet;
  97. property HostName; // ignored
  98. // Redeclare properties from TDatabase
  99. property Connected;
  100. property Role;
  101. property DatabaseName; // will be passed as DSN connection parameter
  102. property KeepConnection;
  103. property LoginPrompt; // if true, ODBC drivers might prompt for more details that are not in the connection string
  104. property Params; // will be added to connection string
  105. property OnLogin;
  106. end;
  107. EODBCException = class(Exception)
  108. // currently empty; perhaps we can add fields here later that describe the error instead of one simple message string
  109. end;
  110. implementation
  111. uses
  112. Math, DBConst;
  113. const
  114. DefaultEnvironment:TODBCEnvironment = nil;
  115. ODBCLoadCount:integer = 0; // ODBC is loaded when > 0; modified by TODBCEnvironment.Create/Destroy
  116. { Generic ODBC helper functions }
  117. function ODBCSucces(const Res:SQLRETURN):boolean;
  118. begin
  119. Result:=(Res=SQL_SUCCESS) or (Res=SQL_SUCCESS_WITH_INFO);
  120. end;
  121. function ODBCResultToStr(Res:SQLRETURN):string;
  122. begin
  123. case Res of
  124. SQL_SUCCESS: Result:='SQL_SUCCESS';
  125. SQL_SUCCESS_WITH_INFO:Result:='SQL_SUCCESS_WITH_INFO';
  126. SQL_ERROR: Result:='SQL_ERROR';
  127. SQL_INVALID_HANDLE: Result:='SQL_INVALID_HANDLE';
  128. SQL_NO_DATA: Result:='SQL_NO_DATA';
  129. SQL_NEED_DATA: Result:='SQL_NEED_DATA';
  130. SQL_STILL_EXECUTING: Result:='SQL_STILL_EXECUTING';
  131. else
  132. Result:='';
  133. end;
  134. end;
  135. procedure ODBCCheckResult(LastReturnCode:SQLRETURN; HandleType:SQLSMALLINT; AHandle: SQLHANDLE; ErrorMsg: string);
  136. // check return value from SQLGetDiagField/Rec function itself
  137. procedure CheckSQLGetDiagResult(const Res:SQLRETURN);
  138. begin
  139. case Res of
  140. SQL_INVALID_HANDLE:
  141. raise EODBCException.Create('Invalid handle passed to SQLGetDiagRec/Field');
  142. SQL_ERROR:
  143. raise EODBCException.Create('An invalid parameter was passed to SQLGetDiagRec/Field');
  144. SQL_NO_DATA:
  145. raise EODBCException.Create('A too large RecNumber was passed to SQLGetDiagRec/Field');
  146. end;
  147. end;
  148. var
  149. NativeError:SQLINTEGER;
  150. TextLength:SQLSMALLINT;
  151. Res:SQLRETURN;
  152. SqlState,MessageText,TotalMessage:string;
  153. RecNumber:SQLSMALLINT;
  154. begin
  155. // check result
  156. if ODBCSucces(LastReturnCode) then
  157. Exit; // no error; all is ok
  158. // build TotalMessage for exception to throw
  159. TotalMessage:=Format('%s ODBC error details:',[ErrorMsg]);
  160. // retrieve status records
  161. SetLength(SqlState,5); // SqlState buffer
  162. RecNumber:=1;
  163. repeat
  164. // dummy call to get correct TextLength
  165. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(SqlState[1]),0,TextLength);
  166. if Res=SQL_NO_DATA then
  167. Break; // no more status records
  168. CheckSQLGetDiagResult(Res);
  169. 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
  170. begin
  171. // allocate large enough buffer
  172. SetLength(MessageText,TextLength); // note: ansistrings of Length>0 are always terminated by a #0 character, so this is safe
  173. // actual call
  174. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(MessageText[1]),Length(MessageText)+1,TextLength);
  175. CheckSQLGetDiagResult(Res);
  176. end;
  177. // add to TotalMessage
  178. TotalMessage:=TotalMessage + Format(' Record %d: SqlState: %s; NativeError: %d; Message: %s;',[RecNumber,SqlState,NativeError,MessageText]);
  179. // incement counter
  180. Inc(RecNumber);
  181. until false;
  182. // raise error
  183. raise EODBCException.Create(TotalMessage);
  184. end;
  185. { TODBCConnection }
  186. // Creates a connection string using the current value of the fields
  187. function TODBCConnection.CreateConnectionString: string;
  188. // encloses a param value with braces if necessary, i.e. when any of the characters []{}(),;?*=!@ is in the value
  189. function EscapeParamValue(const s:string):string;
  190. var
  191. NeedEscape:boolean;
  192. i:integer;
  193. begin
  194. NeedEscape:=false;
  195. for i:=1 to Length(s) do
  196. if s[i] in ['[',']','{','}','(',')',',','*','=','!','@'] then
  197. begin
  198. NeedEscape:=true;
  199. Break;
  200. end;
  201. if NeedEscape then
  202. Result:='{'+s+'}'
  203. else
  204. Result:=s;
  205. end;
  206. var
  207. i: Integer;
  208. Param: string;
  209. EqualSignPos:integer;
  210. begin
  211. Result:='';
  212. if DatabaseName<>'' then Result:=Result + 'DSN='+EscapeParamValue(DatabaseName)+';';
  213. if Driver <>'' then Result:=Result + 'DRIVER='+EscapeParamValue(Driver)+';';
  214. if UserName <>'' then Result:=Result + 'UID='+EscapeParamValue(UserName)+';PWD='+EscapeParamValue(Password)+';';
  215. if FileDSN <>'' then Result:=Result + 'FILEDSN='+EscapeParamValue(FileDSN)+'';
  216. for i:=0 to Params.Count-1 do
  217. begin
  218. Param:=Params[i];
  219. EqualSignPos:=Pos('=',Param);
  220. if EqualSignPos=0 then
  221. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; can''t find a ''='' in ''%s''',[i, Param])
  222. else if EqualSignPos=1 then
  223. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; no identifier before the ''='' in ''%s''',[i, Param])
  224. else
  225. Result:=Result + EscapeParamValue(Copy(Param,1,EqualSignPos-1))+'='+EscapeParamValue(Copy(Param,EqualSignPos+1,MaxInt))+';';
  226. end;
  227. end;
  228. constructor TODBCConnection.Create(AOwner: TComponent);
  229. begin
  230. inherited Create(AOwner);
  231. FConnOptions := FConnOptions + [sqEscapeRepeat] + [sqEscapeSlash];
  232. end;
  233. procedure TODBCConnection.SetParameters(ODBCCursor: TODBCCursor; AParams: TParams);
  234. var
  235. ParamIndex:integer;
  236. Buf:pointer;
  237. I:integer;
  238. IntVal:longint;
  239. StrVal:string;
  240. StrLen:SQLINTEGER;
  241. begin
  242. // Note: it is assumed that AParams is the same as the one passed to PrepareStatement, in the sense that
  243. // the parameters have the same order and names
  244. if Length(ODBCCursor.FParamIndex)>0 then
  245. if not Assigned(AParams) then
  246. raise EODBCException.CreateFmt('The query has parameter markers in it, but no actual parameters were passed',[]);
  247. SetLength(ODBCCursor.FParamBuf, Length(ODBCCursor.FParamIndex));
  248. for i:=0 to High(ODBCCursor.FParamIndex) do
  249. begin
  250. ParamIndex:=ODBCCursor.FParamIndex[i];
  251. if (ParamIndex<0) or (ParamIndex>=AParams.Count) then
  252. raise EODBCException.CreateFmt('Parameter %d in query does not have a matching parameter set',[i]);
  253. case AParams[ParamIndex].DataType of
  254. ftInteger:
  255. begin
  256. Buf:=GetMem(4);
  257. IntVal:=AParams[ParamIndex].AsInteger;
  258. Move(IntVal,Buf^,4);
  259. ODBCCursor.FParamBuf[i]:=Buf;
  260. ODBCCheckResult(
  261. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  262. i+1, // ParameterNumber
  263. SQL_PARAM_INPUT, // InputOutputType
  264. SQL_C_LONG, // ValueType
  265. SQL_INTEGER, // ParameterType
  266. 10, // ColumnSize
  267. 0, // DecimalDigits
  268. Buf, // ParameterValuePtr
  269. 0, // BufferLength
  270. nil), // StrLen_or_IndPtr
  271. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not bind parameter %d',[i])
  272. );
  273. end;
  274. ftString:
  275. begin
  276. StrVal:=AParams[ParamIndex].AsString;
  277. StrLen:=Length(StrVal);
  278. Buf:=GetMem(SizeOf(SQLINTEGER)+StrLen);
  279. Move(StrLen, buf^, SizeOf(SQLINTEGER));
  280. Move(StrVal[1],(buf+SizeOf(SQLINTEGER))^,StrLen);
  281. ODBCCursor.FParamBuf[i]:=Buf;
  282. ODBCCheckResult(
  283. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  284. i+1, // ParameterNumber
  285. SQL_PARAM_INPUT, // InputOutputType
  286. SQL_C_CHAR, // ValueType
  287. SQL_CHAR, // ParameterType
  288. StrLen, // ColumnSize
  289. 0, // DecimalDigits
  290. buf+SizeOf(SQLINTEGER), // ParameterValuePtr
  291. StrLen, // BufferLength
  292. Buf), // StrLen_or_IndPtr
  293. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not bind parameter %d',[i])
  294. );
  295. end;
  296. else
  297. raise EDataBaseError.CreateFmt('Parameter %d is of type %s, which not supported yet',[ParamIndex, Fieldtypenames[AParams[ParamIndex].DataType]]);
  298. end;
  299. end;
  300. end;
  301. procedure TODBCConnection.FreeParamBuffers(ODBCCursor: TODBCCursor);
  302. var
  303. i:integer;
  304. begin
  305. for i:=0 to High(ODBCCursor.FParamBuf) do
  306. FreeMem(ODBCCursor.FParamBuf[i]);
  307. SetLength(ODBCCursor.FParamBuf,0);
  308. end;
  309. function TODBCConnection.GetHandle: pointer;
  310. begin
  311. // I'm not sure whether this is correct; perhaps we should return nil
  312. // note that FDBHandle is a LongInt, because ODBC handles are integers, not pointers
  313. // I wonder how this will work on 64 bit platforms then (FK)
  314. Result:=pointer(PtrInt(FDBCHandle));
  315. end;
  316. procedure TODBCConnection.DoInternalConnect;
  317. const
  318. BufferLength = 1024; // should be at least 1024 according to the ODBC specification
  319. var
  320. ConnectionString:string;
  321. OutConnectionString:string;
  322. ActualLength:SQLSMALLINT;
  323. begin
  324. // Do not call the inherited method as it checks for a non-empty DatabaseName, and we don't even use DatabaseName!
  325. // inherited DoInternalConnect;
  326. // make sure we have an environment
  327. if not Assigned(FEnvironment) then
  328. begin
  329. if not Assigned(DefaultEnvironment) then
  330. DefaultEnvironment:=TODBCEnvironment.Create;
  331. FEnvironment:=DefaultEnvironment;
  332. end;
  333. // allocate connection handle
  334. ODBCCheckResult(
  335. SQLAllocHandle(SQL_HANDLE_DBC,Environment.FENVHandle,FDBCHandle),
  336. SQL_HANDLE_ENV,Environment.FENVHandle,'Could not allocate ODBC Connection handle.'
  337. );
  338. // connect
  339. ConnectionString:=CreateConnectionString;
  340. SetLength(OutConnectionString,BufferLength-1); // allocate completed connection string buffer (using the ansistring #0 trick)
  341. ODBCCheckResult(
  342. SQLDriverConnect(FDBCHandle, // the ODBC connection handle
  343. nil, // no parent window (would be required for prompts)
  344. PChar(ConnectionString), // the connection string
  345. Length(ConnectionString), // connection string length
  346. @(OutConnectionString[1]),// buffer for storing the completed connection string
  347. BufferLength, // length of the buffer
  348. ActualLength, // the actual length of the completed connection string
  349. SQL_DRIVER_NOPROMPT), // don't prompt for password etc.
  350. SQL_HANDLE_DBC,FDBCHandle,Format('Could not connect with connection string "%s".',[ConnectionString])
  351. );
  352. // commented out as the OutConnectionString is not used further at the moment
  353. // if ActualLength<BufferLength-1 then
  354. // SetLength(OutConnectionString,ActualLength); // fix completed connection string length
  355. // set connection attributes (none yet)
  356. end;
  357. procedure TODBCConnection.DoInternalDisconnect;
  358. var
  359. Res:SQLRETURN;
  360. begin
  361. inherited DoInternalDisconnect;
  362. // disconnect
  363. ODBCCheckResult(
  364. SQLDisconnect(FDBCHandle),
  365. SQL_HANDLE_DBC,FDBCHandle,'Could not disconnect.'
  366. );
  367. // deallocate connection handle
  368. Res:=SQLFreeHandle(SQL_HANDLE_DBC, FDBCHandle);
  369. if Res=SQL_ERROR then
  370. ODBCCheckResult(Res,SQL_HANDLE_DBC,FDBCHandle,'Could not free connection handle.');
  371. end;
  372. function TODBCConnection.AllocateCursorHandle: TSQLCursor;
  373. begin
  374. Result:=TODBCCursor.Create(self);
  375. end;
  376. procedure TODBCConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  377. begin
  378. // make sure we don't deallocate the cursor if the connection was lost already
  379. if not Connected then
  380. (cursor as TODBCCursor).FSTMTHandle:=SQL_NULL_HSTMT;
  381. FreeAndNil(cursor); // the destructor of TODBCCursor frees the ODBC Statement handle
  382. end;
  383. function TODBCConnection.AllocateTransactionHandle: TSQLHandle;
  384. begin
  385. Result:=nil; // not yet supported; will move connection handles to transaction handles later
  386. end;
  387. procedure TODBCConnection.PrepareStatement(cursor: TSQLCursor; ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  388. var
  389. ODBCCursor:TODBCCursor;
  390. begin
  391. ODBCCursor:=cursor as TODBCCursor;
  392. // Parameter handling
  393. // Note: We can only pass ? parameters to ODBC, so we should convert named parameters like :MyID
  394. // ODBCCursor.FParamIndex will map th i-th ? token in the (modified) query to an index for AParams
  395. // Parse the SQL and build FParamIndex
  396. if assigned(AParams) and (AParams.count > 0) then
  397. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psInterbase,ODBCCursor.FParamIndex);
  398. // prepare statement
  399. ODBCCheckResult(
  400. SQLPrepare(ODBCCursor.FSTMTHandle, PChar(buf), Length(buf)),
  401. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not prepare statement.'
  402. );
  403. ODBCCursor.FQuery:=Buf;
  404. end;
  405. procedure TODBCConnection.UnPrepareStatement(cursor: TSQLCursor);
  406. begin
  407. // not necessary in ODBC
  408. end;
  409. function TODBCConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  410. begin
  411. // Tranactions not implemented yet
  412. end;
  413. function TODBCConnection.StartDBTransaction(trans: TSQLHandle; AParams:string): boolean;
  414. begin
  415. // Tranactions not implemented yet
  416. end;
  417. function TODBCConnection.Commit(trans: TSQLHandle): boolean;
  418. begin
  419. // Tranactions not implemented yet
  420. end;
  421. function TODBCConnection.Rollback(trans: TSQLHandle): boolean;
  422. begin
  423. // Tranactions not implemented yet
  424. end;
  425. procedure TODBCConnection.CommitRetaining(trans: TSQLHandle);
  426. begin
  427. // Tranactions not implemented yet
  428. end;
  429. procedure TODBCConnection.RollbackRetaining(trans: TSQLHandle);
  430. begin
  431. // Tranactions not implemented yet
  432. end;
  433. procedure TODBCConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  434. var
  435. ODBCCursor:TODBCCursor;
  436. begin
  437. ODBCCursor:=cursor as TODBCCursor;
  438. // set parameters
  439. if Assigned(APArams) and (AParams.count > 0) then SetParameters(ODBCCursor, AParams);
  440. // execute the statement
  441. ODBCCheckResult(
  442. SQLExecute(ODBCCursor.FSTMTHandle),
  443. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not execute statement.'
  444. );
  445. // free parameter buffers
  446. FreeParamBuffers(ODBCCursor);
  447. end;
  448. function TODBCConnection.Fetch(cursor: TSQLCursor): boolean;
  449. var
  450. ODBCCursor:TODBCCursor;
  451. Res:SQLRETURN;
  452. begin
  453. ODBCCursor:=cursor as TODBCCursor;
  454. // fetch new row
  455. Res:=SQLFetch(ODBCCursor.FSTMTHandle);
  456. if Res<>SQL_NO_DATA then
  457. ODBCCheckResult(Res,SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not fetch new row from result set');
  458. // result is true iff a new row was available
  459. Result:=Res<>SQL_NO_DATA;
  460. end;
  461. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer; out CreateBlob : boolean): boolean;
  462. const
  463. DEFAULT_BLOB_BUFFER_SIZE = 1024;
  464. var
  465. ODBCCursor:TODBCCursor;
  466. StrLenOrInd:SQLINTEGER;
  467. ODBCDateStruct:SQL_DATE_STRUCT;
  468. ODBCTimeStruct:SQL_TIME_STRUCT;
  469. ODBCTimeStampStruct:SQL_TIMESTAMP_STRUCT;
  470. DateTime:TDateTime;
  471. BlobBuffer:pointer;
  472. BlobBufferSize,BytesRead:SQLINTEGER;
  473. BlobMemoryStream:TMemoryStream;
  474. Res:SQLRETURN;
  475. begin
  476. CreateBlob := False;
  477. ODBCCursor:=cursor as TODBCCursor;
  478. // load the field using SQLGetData
  479. // Note: optionally we can implement the use of SQLBindCol later for even more speed
  480. // TODO: finish this
  481. case FieldDef.DataType of
  482. ftFixedChar,ftString: // are both mapped to TStringField
  483. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_CHAR, buffer, FieldDef.Size, @StrLenOrInd);
  484. ftSmallint: // mapped to TSmallintField
  485. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SSHORT, buffer, SizeOf(Smallint), @StrLenOrInd);
  486. ftInteger,ftWord: // mapped to TLongintField
  487. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SLONG, buffer, SizeOf(Longint), @StrLenOrInd);
  488. ftLargeint: // mapped to TLargeintField
  489. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SBIGINT, buffer, SizeOf(Largeint), @StrLenOrInd);
  490. ftFloat: // mapped to TFloatField
  491. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_DOUBLE, buffer, SizeOf(Double), @StrLenOrInd);
  492. ftTime: // mapped to TTimeField
  493. begin
  494. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIME, @ODBCTimeStruct, SizeOf(SQL_TIME_STRUCT), @StrLenOrInd);
  495. if StrLenOrInd<>SQL_NULL_DATA then
  496. begin
  497. DateTime:=TimeStructToDateTime(@ODBCTimeStruct);
  498. Move(DateTime, buffer^, SizeOf(TDateTime));
  499. end;
  500. end;
  501. ftDate: // mapped to TDateField
  502. begin
  503. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_DATE, @ODBCDateStruct, SizeOf(SQL_DATE_STRUCT), @StrLenOrInd);
  504. if StrLenOrInd<>SQL_NULL_DATA then
  505. begin
  506. DateTime:=DateStructToDateTime(@ODBCDateStruct);
  507. Move(DateTime, buffer^, SizeOf(TDateTime));
  508. end;
  509. end;
  510. ftDateTime: // mapped to TDateTimeField
  511. begin
  512. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIMESTAMP, @ODBCTimeStampStruct, SizeOf(SQL_TIMESTAMP_STRUCT), @StrLenOrInd);
  513. if StrLenOrInd<>SQL_NULL_DATA then
  514. begin
  515. DateTime:=TimeStampStructToDateTime(@ODBCTimeStampStruct);
  516. Move(DateTime, buffer^, SizeOf(TDateTime));
  517. end;
  518. end;
  519. ftBoolean: // mapped to TBooleanField
  520. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BIT, buffer, SizeOf(Wordbool), @StrLenOrInd);
  521. ftBytes: // mapped to TBytesField
  522. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  523. ftVarBytes: // mapped to TVarBytesField
  524. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  525. ftBlob, ftMemo: // BLOBs
  526. begin
  527. // Try to discover BLOB data length
  528. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, 0, @StrLenOrInd);
  529. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  530. // Read the data if not NULL
  531. if StrLenOrInd<>SQL_NULL_DATA then
  532. begin
  533. // Determine size of buffer to use
  534. if StrLenOrInd<>SQL_NO_TOTAL then
  535. BlobBufferSize:=StrLenOrInd
  536. else
  537. BlobBufferSize:=DEFAULT_BLOB_BUFFER_SIZE;
  538. try
  539. // init BlobBuffer and BlobMemoryStream to nil pointers
  540. BlobBuffer:=nil;
  541. BlobMemoryStream:=nil;
  542. if BlobBufferSize>0 then // Note: zero-length BLOB is represented as nil pointer in the field buffer to save memory usage
  543. begin
  544. // Allocate the buffer and memorystream
  545. BlobBuffer:=GetMem(BlobBufferSize);
  546. BlobMemoryStream:=TMemoryStream.Create;
  547. // Retrieve data in parts (or effectively in one part if StrLenOrInd<>SQL_NO_TOTAL above)
  548. repeat
  549. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, BlobBuffer, BlobBufferSize, @StrLenOrInd);
  550. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  551. // Append data in buffer to memorystream
  552. if (StrLenOrInd=SQL_NO_TOTAL) or (StrLenOrInd>BlobBufferSize) then
  553. BytesRead:=BlobBufferSize
  554. else
  555. BytesRead:=StrLenOrInd;
  556. BlobMemoryStream.Write(BlobBuffer^, BytesRead);
  557. until Res=SQL_SUCCESS;
  558. end;
  559. // Store memorystream pointer in Field buffer and in the cursor's FBlobStreams list
  560. TObject(buffer^):=BlobMemoryStream;
  561. if BlobMemoryStream<>nil then
  562. ODBCCursor.FBlobStreams.Add(BlobMemoryStream);
  563. // Set BlobMemoryStream to nil, so it won't get freed in the finally block below
  564. BlobMemoryStream:=nil;
  565. finally
  566. BlobMemoryStream.Free;
  567. if BlobBuffer<>nil then
  568. Freemem(BlobBuffer,BlobBufferSize);
  569. end;
  570. end;
  571. end;
  572. // TODO: Loading of other field types
  573. else
  574. raise EODBCException.CreateFmt('Tried to load field of unsupported field type %s',[Fieldtypenames[FieldDef.DataType]]);
  575. end;
  576. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  577. Result:=StrLenOrInd<>SQL_NULL_DATA; // Result indicates whether the value is non-null
  578. // writeln(Format('Field.Size: %d; StrLenOrInd: %d',[FieldDef.Size, StrLenOrInd]));
  579. end;
  580. procedure TODBCConnection.LoadBlobIntoStream(Field: TField;AStream: TStream;cursor: TSQLCursor;ATransaction : TSQLTransaction);
  581. var
  582. ODBCCursor: TODBCCursor;
  583. BlobMemoryStream: TMemoryStream;
  584. begin
  585. Field.GetData(@BlobMemoryStream);
  586. if BlobMemoryStream<>nil then
  587. // AStream.LoadFromStream(BlobMemoryStream);
  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_NULL_HSTMT 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.