odbcconn.pas 35 KB

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