odbcconn.pas 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. FDataSourceName: string;
  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; // for the Min proc
  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. procedure ODBCCheckResult(HandleType:SQLSMALLINT; AHandle: SQLHANDLE; ErrorMsg: string);
  121. // check return value from SQLGetDiagField/Rec function itself
  122. procedure CheckSQLGetDiagResult(const Res:SQLRETURN);
  123. begin
  124. case Res of
  125. SQL_INVALID_HANDLE:
  126. raise EODBCException.Create('Invalid handle passed to SQLGetDiagRec/Field');
  127. SQL_ERROR:
  128. raise EODBCException.Create('An invalid parameter was passed to SQLGetDiagRec/Field');
  129. SQL_NO_DATA:
  130. raise EODBCException.Create('A too large RecNumber was passed to SQLGetDiagRec/Field');
  131. end;
  132. end;
  133. var
  134. NativeError:SQLINTEGER;
  135. TextLength:SQLSMALLINT;
  136. Res,LastReturnCode:SQLRETURN;
  137. SqlState,MessageText,TotalMessage:string;
  138. RecNumber:SQLSMALLINT;
  139. begin
  140. // check result
  141. Res:=SQLGetDiagField(HandleType,AHandle,0,SQL_DIAG_RETURNCODE,@LastReturnCode,0,TextLength);
  142. CheckSQLGetDiagResult(Res);
  143. if ODBCSucces(LastReturnCode) then
  144. Exit; // no error; all is ok
  145. // build TotalMessage for exception to throw
  146. TotalMessage:=Format('%s ODBC error details:',[ErrorMsg]);
  147. // retrieve status records
  148. SetLength(SqlState,5); // SqlState buffer
  149. RecNumber:=1;
  150. repeat
  151. // dummy call to get correct TextLength
  152. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(SqlState[1]),0,TextLength);
  153. if Res=SQL_NO_DATA then
  154. Break; // no more status records
  155. CheckSQLGetDiagResult(Res);
  156. 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
  157. begin
  158. // allocate large enough buffer
  159. SetLength(MessageText,TextLength); // note: ansistrings of Length>0 are always terminated by a #0 character, so this is safe
  160. // actual call
  161. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(MessageText[1]),Length(MessageText)+1,TextLength);
  162. CheckSQLGetDiagResult(Res);
  163. end;
  164. // add to TotalMessage
  165. TotalMessage:=TotalMessage + Format(' Record %d: SqlState: %s; NativeError: %d; Message: %s;',[RecNumber,SqlState,NativeError,MessageText]);
  166. // incement counter
  167. Inc(RecNumber);
  168. until false;
  169. // raise error
  170. raise EODBCException.Create(TotalMessage);
  171. end;
  172. { TODBCConnection }
  173. // Creates a connection string using the current value of the fields
  174. function TODBCConnection.CreateConnectionString: string;
  175. // encloses a param value with braces if necessary, i.e. when any of the characters []{}(),;?*=!@ is in the value
  176. function EscapeParamValue(const s:string):string;
  177. var
  178. NeedEscape:boolean;
  179. i:integer;
  180. begin
  181. NeedEscape:=false;
  182. for i:=1 to Length(s) do
  183. if s[i] in ['[',']','{','}','(',')',',','*','=','!','@'] then
  184. begin
  185. NeedEscape:=true;
  186. Break;
  187. end;
  188. if NeedEscape then
  189. Result:='{'+s+'}'
  190. else
  191. Result:=s;
  192. end;
  193. var
  194. i: Integer;
  195. Param: string;
  196. EqualSignPos:integer;
  197. begin
  198. Result:='';
  199. if DatabaseName<>'' then Result:=Result + 'DSN='+EscapeParamValue(DatabaseName)+';';
  200. if Driver <>'' then Result:=Result + 'DRIVER='+EscapeParamValue(Driver)+';';
  201. if UserName <>'' then Result:=Result + 'UID='+EscapeParamValue(UserName)+';PWD='+EscapeParamValue(Password)+';';
  202. if FileDSN <>'' then Result:=Result + 'FILEDSN='+EscapeParamValue(FileDSN)+'';
  203. for i:=0 to Params.Count-1 do
  204. begin
  205. Param:=Params[i];
  206. EqualSignPos:=Pos('=',Param);
  207. if EqualSignPos=0 then
  208. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; can''t find a ''='' in ''%s''',[i, Param])
  209. else if EqualSignPos=1 then
  210. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; no identifier before the ''='' in ''%s''',[i, Param])
  211. else
  212. Result:=Result + EscapeParamValue(Copy(Param,1,EqualSignPos-1))+'='+EscapeParamValue(Copy(Param,EqualSignPos+1,MaxInt));
  213. end;
  214. end;
  215. procedure TODBCConnection.SetParameters(ODBCCursor: TODBCCursor; AParams: TParams);
  216. var
  217. ParamIndex:integer;
  218. Buf:pointer;
  219. I:integer;
  220. IntVal:longint;
  221. StrVal:string;
  222. StrLen:SQLINTEGER;
  223. begin
  224. // Note: it is assumed that AParams is the same as the one passed to PrepareStatement, in the sense that
  225. // the parameters have the same order and names
  226. if Length(ODBCCursor.FParamIndex)>0 then
  227. if not Assigned(AParams) then
  228. raise EODBCException.CreateFmt('The query has parameter markers in it, but no actual parameters were passed',[]);
  229. SetLength(ODBCCursor.FParamBuf, Length(ODBCCursor.FParamIndex));
  230. for i:=0 to High(ODBCCursor.FParamIndex) do
  231. begin
  232. ParamIndex:=ODBCCursor.FParamIndex[i];
  233. if (ParamIndex<0) or (ParamIndex>=AParams.Count) then
  234. raise EODBCException.CreateFmt('Parameter %d in query does not have a matching parameter set',[i]);
  235. case AParams[ParamIndex].DataType of
  236. ftInteger:
  237. begin
  238. Buf:=GetMem(4);
  239. IntVal:=AParams[ParamIndex].AsInteger;
  240. Move(IntVal,Buf^,4);
  241. ODBCCursor.FParamBuf[i]:=Buf;
  242. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  243. i+1, // ParameterNumber
  244. SQL_PARAM_INPUT, // InputOutputType
  245. SQL_C_LONG, // ValueType
  246. SQL_INTEGER, // ParameterType
  247. 10, // ColumnSize
  248. 0, // DecimalDigits
  249. Buf, // ParameterValuePtr
  250. 0, // BufferLength
  251. nil); // StrLen_or_IndPtr
  252. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not bind parameter %d',[i]));
  253. end;
  254. ftString:
  255. begin
  256. StrVal:=AParams[ParamIndex].AsString;
  257. StrLen:=Length(StrVal);
  258. Buf:=GetMem(SizeOf(SQLINTEGER)+StrLen);
  259. Move(StrLen, buf^, SizeOf(SQLINTEGER));
  260. Move(StrVal[1],(buf+SizeOf(SQLINTEGER))^,StrLen);
  261. ODBCCursor.FParamBuf[i]:=Buf;
  262. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  263. i+1, // ParameterNumber
  264. SQL_PARAM_INPUT, // InputOutputType
  265. SQL_C_CHAR, // ValueType
  266. SQL_CHAR, // ParameterType
  267. StrLen, // ColumnSize
  268. 0, // DecimalDigits
  269. buf+SizeOf(SQLINTEGER), // ParameterValuePtr
  270. StrLen, // BufferLength
  271. Buf); // StrLen_or_IndPtr
  272. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not bind parameter %d',[i]));
  273. end;
  274. else
  275. raise EDataBaseError.CreateFmt('Parameter %d is of type %s, which not supported yet',[ParamIndex, Fieldtypenames[AParams[ParamIndex].DataType]]);
  276. end;
  277. end;
  278. end;
  279. procedure TODBCConnection.FreeParamBuffers(ODBCCursor: TODBCCursor);
  280. var
  281. i:integer;
  282. begin
  283. for i:=0 to High(ODBCCursor.FParamBuf) do
  284. FreeMem(ODBCCursor.FParamBuf[i]);
  285. end;
  286. function TODBCConnection.GetHandle: pointer;
  287. begin
  288. // I'm not sure whether this is correct; perhaps we should return nil
  289. // note that FDBHandle is a LongInt, because ODBC handles are integers, not pointers
  290. // I wonder how this will work on 64 bit platforms then (FK)
  291. Result:=pointer(PtrInt(FDBCHandle));
  292. end;
  293. procedure TODBCConnection.DoInternalConnect;
  294. const
  295. BufferLength = 1024; // should be at least 1024 according to the ODBC specification
  296. var
  297. ConnectionString:string;
  298. OutConnectionString:string;
  299. ActualLength:SQLSMALLINT;
  300. begin
  301. inherited DoInternalConnect;
  302. // make sure we have an environment
  303. if not Assigned(FEnvironment) then
  304. begin
  305. if not Assigned(DefaultEnvironment) then
  306. DefaultEnvironment:=TODBCEnvironment.Create;
  307. FEnvironment:=DefaultEnvironment;
  308. end;
  309. // allocate connection handle
  310. SQLAllocHandle(SQL_HANDLE_DBC,Environment.FENVHandle,FDBCHandle);
  311. ODBCCheckResult(SQL_HANDLE_ENV,Environment.FENVHandle,'Could not allocate ODBC Connection handle.');
  312. // connect
  313. ConnectionString:=CreateConnectionString;
  314. SetLength(OutConnectionString,BufferLength-1); // allocate completed connection string buffer (using the ansistring #0 trick)
  315. SQLDriverConnect(FDBCHandle, // the ODBC connection handle
  316. 0, // no parent window (would be required for prompts)
  317. PChar(ConnectionString), // the connection string
  318. Length(ConnectionString), // connection string length
  319. @(OutConnectionString[1]),// buffer for storing the completed connection string
  320. BufferLength, // length of the buffer
  321. ActualLength, // the actual length of the completed connection string
  322. SQL_DRIVER_NOPROMPT); // don't prompt for password etc.
  323. ODBCCheckResult(SQL_HANDLE_DBC,FDBCHandle,Format('Could not connect with connection string "%s".',[ConnectionString]));
  324. if ActualLength<BufferLength-1 then
  325. SetLength(OutConnectionString,ActualLength); // fix completed connection string length
  326. // set connection attributes (none yet)
  327. end;
  328. procedure TODBCConnection.DoInternalDisconnect;
  329. begin
  330. inherited DoInternalDisconnect;
  331. // disconnect
  332. SQLDisconnect(FDBCHandle);
  333. ODBCCheckResult(SQL_HANDLE_DBC,FDBCHandle,'Could not disconnect.');
  334. // deallocate connection handle
  335. if SQLFreeHandle(SQL_HANDLE_DBC, FDBCHandle)=SQL_ERROR then
  336. ODBCCheckResult(SQL_HANDLE_DBC,FDBCHandle,'Could not free connection handle.');
  337. end;
  338. function TODBCConnection.AllocateCursorHandle: TSQLCursor;
  339. begin
  340. Result:=TODBCCursor.Create(self);
  341. end;
  342. procedure TODBCConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  343. begin
  344. FreeAndNil(cursor); // the destructor of TODBCCursor frees the ODBC Statement handle
  345. end;
  346. function TODBCConnection.AllocateTransactionHandle: TSQLHandle;
  347. begin
  348. Result:=nil; // not yet supported; will move connection handles to transaction handles later
  349. end;
  350. procedure TODBCConnection.PrepareStatement(cursor: TSQLCursor; ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  351. type
  352. // used for ParamPart
  353. TStringPart = record
  354. Start,Stop:integer;
  355. end;
  356. const
  357. ParamAllocStepSize = 8;
  358. var
  359. ODBCCursor:TODBCCursor;
  360. p,ParamNameStart,BufStart:PChar;
  361. ParamName:string;
  362. QuestionMarkParamCount,ParameterIndex,NewLength:integer;
  363. ParamCount:integer; // actual number of parameters encountered so far;
  364. // always <= Length(ParamPart) = Length(ODBCCursor.FParamIndex)
  365. // ODBCCursor.FParamIndex will have length ParamCount in the end
  366. ParamPart:array of TStringPart; // describe which parts of buf are parameters
  367. NewQueryLength:integer;
  368. NewQuery:string;
  369. NewQueryIndex,BufIndex,CopyLen,i:integer;
  370. begin
  371. ODBCCursor:=cursor as TODBCCursor;
  372. // Parameter handling
  373. // Note: We can only pass ? parameters to ODBC, so we should convert named parameters like :MyID
  374. // ODBCCursor.FParamIndex will map th i-th ? token in the (modified) query to an index for AParams
  375. // Parse the SQL and build FParamIndex
  376. ParamCount:=0;
  377. NewQueryLength:=Length(buf);
  378. SetLength(ParamPart,ParamAllocStepSize);
  379. SetLength(ODBCCursor.FParamIndex,ParamAllocStepSize);
  380. QuestionMarkParamCount:=0; // number of ? params found in query so far
  381. p:=PChar(buf);
  382. BufStart:=p; // used to calculate ParamPart.Start values
  383. repeat
  384. case p^ of
  385. '''': // single quote delimited string (not obligatory in ODBC, but let's handle it anyway)
  386. begin
  387. Inc(p);
  388. while not (p^ in [#0, '''']) do
  389. begin
  390. if p^='\' then Inc(p,2) // make sure we handle \' and \\ correct
  391. else Inc(p);
  392. end;
  393. if p^='''' then Inc(p); // skip final '
  394. end;
  395. '"': // double quote delimited string
  396. begin
  397. Inc(p);
  398. while not (p^ in [#0, '"']) do
  399. begin
  400. if p^='\' then Inc(p,2) // make sure we handle \" and \\ correct
  401. else Inc(p);
  402. end;
  403. if p^='"' then Inc(p); // skip final "
  404. end;
  405. '-': // possible start of -- comment
  406. begin
  407. Inc(p);
  408. if p='-' then // -- comment
  409. begin
  410. repeat // skip until at end of line
  411. Inc(p);
  412. until p^ in [#10, #0];
  413. end
  414. end;
  415. '/': // possible start of /* */ comment
  416. begin
  417. Inc(p);
  418. if p^='*' then // /* */ comment
  419. begin
  420. repeat
  421. Inc(p);
  422. if p^='*' then // possible end of comment
  423. begin
  424. Inc(p);
  425. if p^='/' then Break; // end of comment
  426. end;
  427. until p^=#0;
  428. if p^='/' then Inc(p); // skip final /
  429. end;
  430. end;
  431. ':','?': // parameter
  432. begin
  433. Inc(ParamCount);
  434. if ParamCount>Length(ParamPart) then
  435. begin
  436. NewLength:=Length(ParamPart)+ParamAllocStepSize;
  437. SetLength(ParamPart,NewLength);
  438. SetLength(ODBCCursor.FParamIndex,NewLength);
  439. end;
  440. if p^=':' then
  441. begin // find parameter name
  442. Inc(p);
  443. ParamNameStart:=p;
  444. while not (p^ in (SQLDelimiterCharacters+[#0])) do
  445. Inc(p);
  446. ParamName:=Copy(ParamNameStart,1,p-ParamNameStart);
  447. end
  448. else
  449. begin
  450. Inc(p);
  451. ParamNameStart:=p;
  452. ParamName:='';
  453. end;
  454. // find ParameterIndex
  455. if ParamName<>'' then
  456. begin
  457. if AParams=nil then
  458. raise EDataBaseError.CreateFmt('Found parameter marker with name %s in the query, but no actual parameters are given at all',[ParamName]);
  459. ParameterIndex:=AParams.ParamByName(ParamName).Index // lookup parameter in AParams
  460. end
  461. else
  462. begin
  463. ParameterIndex:=QuestionMarkParamCount;
  464. Inc(QuestionMarkParamCount);
  465. end;
  466. // store ParameterIndex in FParamIndex, ParamPart data
  467. ODBCCursor.FParamIndex[ParamCount-1]:=ParameterIndex;
  468. ParamPart[ParamCount-1].Start:=ParamNameStart-BufStart;
  469. ParamPart[ParamCount-1].Stop:=p-BufStart+1;
  470. // update NewQueryLength
  471. Dec(NewQueryLength,p-ParamNameStart);
  472. end;
  473. #0:Break;
  474. else
  475. Inc(p);
  476. end;
  477. until false;
  478. SetLength(ParamPart,ParamCount);
  479. SetLength(ODBCCursor.FParamIndex,ParamCount);
  480. if ParamCount>0 then
  481. begin
  482. // replace :ParamName by ? (using ParamPart array and NewQueryLength)
  483. SetLength(NewQuery,NewQueryLength);
  484. NewQueryIndex:=1;
  485. BufIndex:=1;
  486. for i:=0 to High(ParamPart) do
  487. begin
  488. CopyLen:=ParamPart[i].Start-BufIndex;
  489. Move(buf[BufIndex],NewQuery[NewQueryIndex],CopyLen);
  490. Inc(NewQueryIndex,CopyLen);
  491. NewQuery[NewQueryIndex]:='?';
  492. Inc(NewQueryIndex);
  493. BufIndex:=ParamPart[i].Stop;
  494. end;
  495. CopyLen:=Length(Buf)+1-BufIndex;
  496. Move(buf[BufIndex],NewQuery[NewQueryIndex],CopyLen);
  497. end
  498. else
  499. NewQuery:=buf;
  500. // prepare statement
  501. SQLPrepare(ODBCCursor.FSTMTHandle, PChar(NewQuery), Length(NewQuery));
  502. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not prepare statement.');
  503. ODBCCursor.FQuery:=NewQuery;
  504. end;
  505. procedure TODBCConnection.UnPrepareStatement(cursor: TSQLCursor);
  506. begin
  507. // not necessary in ODBC
  508. end;
  509. function TODBCConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  510. begin
  511. // Tranactions not implemented yet
  512. end;
  513. function TODBCConnection.StartDBTransaction(trans: TSQLHandle; AParams:string): boolean;
  514. begin
  515. // Tranactions not implemented yet
  516. end;
  517. function TODBCConnection.Commit(trans: TSQLHandle): boolean;
  518. begin
  519. // Tranactions not implemented yet
  520. end;
  521. function TODBCConnection.Rollback(trans: TSQLHandle): boolean;
  522. begin
  523. // Tranactions not implemented yet
  524. end;
  525. procedure TODBCConnection.CommitRetaining(trans: TSQLHandle);
  526. begin
  527. // Tranactions not implemented yet
  528. end;
  529. procedure TODBCConnection.RollbackRetaining(trans: TSQLHandle);
  530. begin
  531. // Tranactions not implemented yet
  532. end;
  533. procedure TODBCConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  534. var
  535. ODBCCursor:TODBCCursor;
  536. Res:SQLRETURN;
  537. begin
  538. ODBCCursor:=cursor as TODBCCursor;
  539. // set parameters
  540. SetParameters(ODBCCursor, AParams);
  541. // execute the statement
  542. Res:=SQLExecute(ODBCCursor.FSTMTHandle);
  543. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not execute statement.');
  544. // free parameter buffers
  545. FreeParamBuffers(ODBCCursor);
  546. end;
  547. function TODBCConnection.Fetch(cursor: TSQLCursor): boolean;
  548. var
  549. ODBCCursor:TODBCCursor;
  550. Res:SQLRETURN;
  551. begin
  552. ODBCCursor:=cursor as TODBCCursor;
  553. // fetch new row
  554. Res:=SQLFetch(ODBCCursor.FSTMTHandle);
  555. if Res<>SQL_NO_DATA then
  556. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not fetch new row from result set');
  557. // result is true iff a new row was available
  558. Result:=Res<>SQL_NO_DATA;
  559. end;
  560. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer): boolean;
  561. var
  562. ODBCCursor:TODBCCursor;
  563. StrLenOrInd:SQLINTEGER;
  564. ODBCDateStruct:SQL_DATE_STRUCT;
  565. ODBCTimeStruct:SQL_TIME_STRUCT;
  566. ODBCTimeStampStruct:SQL_TIMESTAMP_STRUCT;
  567. DateTime:TDateTime;
  568. begin
  569. ODBCCursor:=cursor as TODBCCursor;
  570. // load the field using SQLGetData
  571. // Note: optionally we can implement the use of SQLBindCol later for even more speed
  572. // TODO: finish this
  573. case FieldDef.DataType of
  574. ftFixedChar,ftString: // are both mapped to TStringField
  575. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_CHAR, buffer, FieldDef.Size, @StrLenOrInd);
  576. ftSmallint: // mapped to TSmallintField
  577. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SSHORT, buffer, SizeOf(Smallint), @StrLenOrInd);
  578. ftInteger,ftWord: // mapped to TLongintField
  579. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SLONG, buffer, SizeOf(Longint), @StrLenOrInd);
  580. ftLargeint: // mapped to TLargeintField
  581. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SBIGINT, buffer, SizeOf(Largeint), @StrLenOrInd);
  582. ftFloat: // mapped to TFloatField
  583. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_DOUBLE, buffer, SizeOf(Double), @StrLenOrInd);
  584. ftTime: // mapped to TTimeField
  585. begin
  586. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIME, @ODBCTimeStruct, SizeOf(SQL_TIME_STRUCT), @StrLenOrInd);
  587. DateTime:=TimeStructToDateTime(@ODBCTimeStruct);
  588. Move(DateTime, buffer^, SizeOf(TDateTime));
  589. end;
  590. ftDate: // mapped to TDateField
  591. begin
  592. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_DATE, @ODBCDateStruct, SizeOf(SQL_DATE_STRUCT), @StrLenOrInd);
  593. DateTime:=DateStructToDateTime(@ODBCDateStruct);
  594. Move(DateTime, buffer^, SizeOf(TDateTime));
  595. end;
  596. ftDateTime: // mapped to TDateTimeField
  597. begin
  598. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIMESTAMP, @ODBCTimeStampStruct, SizeOf(SQL_TIMESTAMP_STRUCT), @StrLenOrInd);
  599. DateTime:=TimeStampStructToDateTime(@ODBCTimeStampStruct);
  600. Move(DateTime, buffer^, SizeOf(TDateTime));
  601. end;
  602. ftBoolean: // mapped to TBooleanField
  603. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BIT, buffer, SizeOf(Wordbool), @StrLenOrInd);
  604. ftBytes: // mapped to TBytesField
  605. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  606. ftVarBytes: // mapped to TVarBytesField
  607. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  608. // TODO: Loading of other field types
  609. else
  610. raise EODBCException.CreateFmt('Tried to load field of unsupported field type %s',[Fieldtypenames[FieldDef.DataType]]);
  611. end;
  612. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  613. Result:=StrLenOrInd<>SQL_NULL_DATA; // Result indicates whether the value is non-null
  614. // writeln(Format('Field.Size: %d; StrLenOrInd: %d',[FieldDef.Size, StrLenOrInd]));
  615. end;
  616. function TODBCConnection.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
  617. begin
  618. // TODO: implement TODBCConnection.CreateBlobStream
  619. Result:=nil;
  620. end;
  621. procedure TODBCConnection.FreeFldBuffers(cursor: TSQLCursor);
  622. var
  623. ODBCCursor:TODBCCursor;
  624. begin
  625. ODBCCursor:=cursor as TODBCCursor;
  626. SQLFreeStmt(ODBCCursor.FSTMTHandle, SQL_CLOSE);
  627. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not close ODBC statement cursor.');
  628. end;
  629. procedure TODBCConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TFieldDefs);
  630. const
  631. ColNameDefaultLength = 40; // should be > 0, because an ansistring of length 0 is a nil pointer instead of a pointer to a #0
  632. var
  633. ODBCCursor:TODBCCursor;
  634. ColumnCount:SQLSMALLINT;
  635. i:integer;
  636. ColNameLength,DataType,DecimalDigits,Nullable:SQLSMALLINT;
  637. ColumnSize:SQLUINTEGER;
  638. ColName:string;
  639. FieldType:TFieldType;
  640. FieldSize:word;
  641. begin
  642. ODBCCursor:=cursor as TODBCCursor;
  643. // get number of columns in result set
  644. SQLNumResultCols(ODBCCursor.FSTMTHandle, ColumnCount);
  645. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not determine number of columns in result set.');
  646. for i:=1 to ColumnCount do
  647. begin
  648. SetLength(ColName,ColNameDefaultLength); // also garantuees uniqueness
  649. // call with default column name buffer
  650. SQLDescribeCol(ODBCCursor.FSTMTHandle, // statement handle
  651. i, // column number, is 1-based (Note: column 0 is the bookmark column in ODBC)
  652. @(ColName[1]), // default buffer
  653. ColNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  654. ColNameLength, // actual column name length
  655. DataType, // the SQL datatype for the column
  656. ColumnSize, // column size
  657. DecimalDigits, // number of decimal digits
  658. Nullable); // SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
  659. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get column properties for column %d.',[i]));
  660. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  661. SetLength(ColName,ColNameLength);
  662. // check whether entire column name was returned
  663. if ColNameLength>ColNameDefaultLength then
  664. begin
  665. // request column name with buffer that is long enough
  666. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  667. i, // column number
  668. SQL_DESC_NAME, // the column name or alias
  669. @(ColName[1]), // buffer
  670. ColNameLength+1, // buffer size
  671. @ColNameLength, // actual length
  672. nil); // no numerical output
  673. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get column name for column %d.',[i]));
  674. end;
  675. // convert type
  676. // NOTE: I made some guesses here after I found only limited information about TFieldType; please report any problems
  677. case DataType of
  678. SQL_CHAR: begin FieldType:=ftFixedChar; FieldSize:=ColumnSize+1; end;
  679. SQL_VARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end;
  680. SQL_LONGVARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end; // no fixed maximum length; make ftMemo when blobs are supported
  681. SQL_WCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end;
  682. SQL_WVARCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end;
  683. SQL_WLONGVARCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end; // no fixed maximum length; make ftMemo when blobs are supported
  684. SQL_DECIMAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  685. SQL_NUMERIC: begin FieldType:=ftFloat; FieldSize:=0; end;
  686. SQL_SMALLINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  687. SQL_INTEGER: begin FieldType:=ftInteger; FieldSize:=0; end;
  688. SQL_REAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  689. SQL_FLOAT: begin FieldType:=ftFloat; FieldSize:=0; end;
  690. SQL_DOUBLE: begin FieldType:=ftFloat; FieldSize:=0; end;
  691. SQL_BIT: begin FieldType:=ftBoolean; FieldSize:=0; end;
  692. SQL_TINYINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  693. SQL_BIGINT: begin FieldType:=ftLargeint; FieldSize:=0; end;
  694. SQL_BINARY: begin FieldType:=ftBytes; FieldSize:=ColumnSize; end;
  695. SQL_VARBINARY: begin FieldType:=ftVarBytes; FieldSize:=ColumnSize; end;
  696. SQL_LONGVARBINARY: begin FieldType:=ftBlob; FieldSize:=ColumnSize; end;
  697. SQL_TYPE_DATE: begin FieldType:=ftDate; FieldSize:=0; end;
  698. SQL_TYPE_TIME: begin FieldType:=ftTime; FieldSize:=0; end;
  699. SQL_TYPE_TIMESTAMP:begin FieldType:=ftTimeStamp; FieldSize:=0; end;
  700. { SQL_TYPE_UTCDATETIME:FieldType:=ftUnknown;}
  701. { SQL_TYPE_UTCTIME: FieldType:=ftUnknown; }
  702. { SQL_INTERVAL_MONTH: FieldType:=ftUnknown;}
  703. { SQL_INTERVAL_YEAR: FieldType:=ftUnknown;}
  704. { SQL_INTERVAL_YEAR_TO_MONTH: FieldType:=ftUnknown;}
  705. { SQL_INTERVAL_DAY: FieldType:=ftUnknown;}
  706. { SQL_INTERVAL_HOUR: FieldType:=ftUnknown;}
  707. { SQL_INTERVAL_MINUTE: FieldType:=ftUnknown;}
  708. { SQL_INTERVAL_SECOND: FieldType:=ftUnknown;}
  709. { SQL_INTERVAL_DAY_TO_HOUR: FieldType:=ftUnknown;}
  710. { SQL_INTERVAL_DAY_TO_MINUTE: FieldType:=ftUnknown;}
  711. { SQL_INTERVAL_DAY_TO_SECOND: FieldType:=ftUnknown;}
  712. { SQL_INTERVAL_HOUR_TO_MINUTE: FieldType:=ftUnknown;}
  713. { SQL_INTERVAL_HOUR_TO_SECOND: FieldType:=ftUnknown;}
  714. { SQL_INTERVAL_MINUTE_TO_SECOND:FieldType:=ftUnknown;}
  715. { SQL_GUID: begin FieldType:=ftGuid; FieldSize:=ColumnSize; end; } // no TGuidField exists yet in the db unit
  716. else
  717. begin FieldType:=ftUnknown; FieldSize:=ColumnSize; end
  718. end;
  719. // add FieldDef
  720. TFieldDef.Create(FieldDefs, ColName, FieldType, FieldSize, False, i);
  721. end;
  722. end;
  723. procedure TODBCConnection.UpdateIndexDefs(var IndexDefs: TIndexDefs; TableName: string);
  724. begin
  725. inherited UpdateIndexDefs(IndexDefs, TableName);
  726. // TODO: implement this
  727. end;
  728. function TODBCConnection.GetSchemaInfoSQL(SchemaType: TSchemaType; SchemaObjectName, SchemaObjectPattern: string): string;
  729. begin
  730. Result:=inherited GetSchemaInfoSQL(SchemaType, SchemaObjectName, SchemaObjectPattern);
  731. // TODO: implement this
  732. end;
  733. { TODBCEnvironment }
  734. constructor TODBCEnvironment.Create;
  735. begin
  736. // make sure odbc is loaded
  737. if ODBCLoadCount=0 then LoadOdbc;
  738. Inc(ODBCLoadCount);
  739. // allocate environment handle
  740. if SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, FENVHandle)=SQL_Error then
  741. 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
  742. // set odbc version
  743. SQLSetEnvAttr(FENVHandle, SQL_ATTR_ODBC_VERSION, SQLPOINTER(SQL_OV_ODBC3), 0);
  744. ODBCCheckResult(SQL_HANDLE_ENV, FENVHandle,'Could not set ODBC version to 3.');
  745. end;
  746. destructor TODBCEnvironment.Destroy;
  747. begin
  748. // free environment handle
  749. if SQLFreeHandle(SQL_HANDLE_ENV, FENVHandle)=SQL_ERROR then
  750. ODBCCheckResult(SQL_HANDLE_ENV, FENVHandle, 'Could not free ODBC Environment handle.');
  751. // free odbc if not used by any TODBCEnvironment object anymore
  752. Dec(ODBCLoadCount);
  753. if ODBCLoadCount=0 then UnLoadOdbc;
  754. end;
  755. { TODBCCursor }
  756. constructor TODBCCursor.Create(Connection:TODBCConnection);
  757. begin
  758. // allocate statement handle
  759. SQLAllocHandle(SQL_HANDLE_STMT, Connection.FDBCHandle, FSTMTHandle);
  760. ODBCCheckResult(SQL_HANDLE_DBC, Connection.FDBCHandle, 'Could not allocate ODBC Statement handle.');
  761. end;
  762. destructor TODBCCursor.Destroy;
  763. begin
  764. inherited Destroy;
  765. // deallocate statement handle
  766. if SQLFreeHandle(SQL_HANDLE_STMT, FSTMTHandle)=SQL_ERROR then
  767. ODBCCheckResult(SQL_HANDLE_STMT, FSTMTHandle, 'Could not free ODBC Statement handle.');
  768. end;
  769. { finalization }
  770. finalization
  771. if Assigned(DefaultEnvironment) then
  772. DefaultEnvironment.Free;
  773. end.