odbcconn.pas 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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. Result:=pointer(FDBCHandle); // note that FDBHandle is a LongInt, because ODBC handles are integers, not pointers
  290. end;
  291. procedure TODBCConnection.DoInternalConnect;
  292. const
  293. BufferLength = 1024; // should be at least 1024 according to the ODBC specification
  294. var
  295. ConnectionString:string;
  296. OutConnectionString:string;
  297. ActualLength:SQLSMALLINT;
  298. begin
  299. inherited DoInternalConnect;
  300. // make sure we have an environment
  301. if not Assigned(FEnvironment) then
  302. begin
  303. if not Assigned(DefaultEnvironment) then
  304. DefaultEnvironment:=TODBCEnvironment.Create;
  305. FEnvironment:=DefaultEnvironment;
  306. end;
  307. // allocate connection handle
  308. SQLAllocHandle(SQL_HANDLE_DBC,Environment.FENVHandle,FDBCHandle);
  309. ODBCCheckResult(SQL_HANDLE_ENV,Environment.FENVHandle,'Could not allocate ODBC Connection handle.');
  310. // connect
  311. ConnectionString:=CreateConnectionString;
  312. SetLength(OutConnectionString,BufferLength-1); // allocate completed connection string buffer (using the ansistring #0 trick)
  313. SQLDriverConnect(FDBCHandle, // the ODBC connection handle
  314. 0, // no parent window (would be required for prompts)
  315. PChar(ConnectionString), // the connection string
  316. Length(ConnectionString), // connection string length
  317. @(OutConnectionString[1]),// buffer for storing the completed connection string
  318. BufferLength, // length of the buffer
  319. ActualLength, // the actual length of the completed connection string
  320. SQL_DRIVER_NOPROMPT); // don't prompt for password etc.
  321. ODBCCheckResult(SQL_HANDLE_DBC,FDBCHandle,Format('Could not connect with connection string "%s".',[ConnectionString]));
  322. if ActualLength<BufferLength-1 then
  323. SetLength(OutConnectionString,ActualLength); // fix completed connection string length
  324. // set connection attributes (none yet)
  325. end;
  326. procedure TODBCConnection.DoInternalDisconnect;
  327. begin
  328. inherited DoInternalDisconnect;
  329. // disconnect
  330. SQLDisconnect(FDBCHandle);
  331. ODBCCheckResult(SQL_HANDLE_DBC,FDBCHandle,'Could not disconnect.');
  332. // deallocate connection handle
  333. if SQLFreeHandle(SQL_HANDLE_DBC, FDBCHandle)=SQL_ERROR then
  334. ODBCCheckResult(SQL_HANDLE_DBC,FDBCHandle,'Could not free connection handle.');
  335. end;
  336. function TODBCConnection.AllocateCursorHandle: TSQLCursor;
  337. begin
  338. Result:=TODBCCursor.Create(self);
  339. end;
  340. procedure TODBCConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  341. begin
  342. FreeAndNil(cursor); // the destructor of TODBCCursor frees the ODBC Statement handle
  343. end;
  344. function TODBCConnection.AllocateTransactionHandle: TSQLHandle;
  345. begin
  346. Result:=nil; // not yet supported; will move connection handles to transaction handles later
  347. end;
  348. procedure TODBCConnection.PrepareStatement(cursor: TSQLCursor; ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  349. type
  350. // used for ParamPart
  351. TStringPart = record
  352. Start,Stop:integer;
  353. end;
  354. const
  355. ParamAllocStepSize = 8;
  356. var
  357. ODBCCursor:TODBCCursor;
  358. p,ParamNameStart,BufStart:PChar;
  359. ParamName:string;
  360. QuestionMarkParamCount,ParameterIndex,NewLength:integer;
  361. ParamCount:integer; // actual number of parameters encountered so far;
  362. // always <= Length(ParamPart) = Length(ODBCCursor.FParamIndex)
  363. // ODBCCursor.FParamIndex will have length ParamCount in the end
  364. ParamPart:array of TStringPart; // describe which parts of buf are parameters
  365. NewQueryLength:integer;
  366. NewQuery:string;
  367. NewQueryIndex,BufIndex,CopyLen,i:integer;
  368. begin
  369. ODBCCursor:=cursor as TODBCCursor;
  370. // Parameter handling
  371. // Note: We can only pass ? parameters to ODBC, so we should convert named parameters like :MyID
  372. // ODBCCursor.FParamIndex will map th i-th ? token in the (modified) query to an index for AParams
  373. // Parse the SQL and build FParamIndex
  374. ParamCount:=0;
  375. NewQueryLength:=Length(buf);
  376. SetLength(ParamPart,ParamAllocStepSize);
  377. SetLength(ODBCCursor.FParamIndex,ParamAllocStepSize);
  378. QuestionMarkParamCount:=0; // number of ? params found in query so far
  379. p:=PChar(buf);
  380. BufStart:=p; // used to calculate ParamPart.Start values
  381. repeat
  382. case p^ of
  383. '''': // single quote delimited string (not obligatory in ODBC, but let's handle it anyway)
  384. begin
  385. Inc(p);
  386. while not (p^ in [#0, '''']) do
  387. begin
  388. if p^='\' then Inc(p,2) // make sure we handle \' and \\ correct
  389. else Inc(p);
  390. end;
  391. if p^='''' then Inc(p); // skip final '
  392. end;
  393. '"': // double quote delimited string
  394. begin
  395. Inc(p);
  396. while not (p^ in [#0, '"']) do
  397. begin
  398. if p^='\' then Inc(p,2) // make sure we handle \" and \\ correct
  399. else Inc(p);
  400. end;
  401. if p^='"' then Inc(p); // skip final "
  402. end;
  403. '-': // possible start of -- comment
  404. begin
  405. Inc(p);
  406. if p='-' then // -- comment
  407. begin
  408. repeat // skip until at end of line
  409. Inc(p);
  410. until p^ in [#10, #0];
  411. end
  412. end;
  413. '/': // possible start of /* */ comment
  414. begin
  415. Inc(p);
  416. if p^='*' then // /* */ comment
  417. begin
  418. repeat
  419. Inc(p);
  420. if p^='*' then // possible end of comment
  421. begin
  422. Inc(p);
  423. if p^='/' then Break; // end of comment
  424. end;
  425. until p^=#0;
  426. if p^='/' then Inc(p); // skip final /
  427. end;
  428. end;
  429. ':','?': // parameter
  430. begin
  431. Inc(ParamCount);
  432. if ParamCount>Length(ParamPart) then
  433. begin
  434. NewLength:=Length(ParamPart)+ParamAllocStepSize;
  435. SetLength(ParamPart,NewLength);
  436. SetLength(ODBCCursor.FParamIndex,NewLength);
  437. end;
  438. if p^=':' then
  439. begin // find parameter name
  440. Inc(p);
  441. ParamNameStart:=p;
  442. while not (p^ in (SQLDelimiterCharacters+[#0])) do
  443. Inc(p);
  444. ParamName:=Copy(ParamNameStart,1,p-ParamNameStart);
  445. end
  446. else
  447. begin
  448. Inc(p);
  449. ParamNameStart:=p;
  450. ParamName:='';
  451. end;
  452. // find ParameterIndex
  453. if ParamName<>'' then
  454. begin
  455. if AParams=nil then
  456. raise EDataBaseError.CreateFmt('Found parameter marker with name %s in the query, but no actual parameters are given at all',[ParamName]);
  457. ParameterIndex:=AParams.ParamByName(ParamName).Index // lookup parameter in AParams
  458. end
  459. else
  460. begin
  461. ParameterIndex:=QuestionMarkParamCount;
  462. Inc(QuestionMarkParamCount);
  463. end;
  464. // store ParameterIndex in FParamIndex, ParamPart data
  465. ODBCCursor.FParamIndex[ParamCount-1]:=ParameterIndex;
  466. ParamPart[ParamCount-1].Start:=ParamNameStart-BufStart;
  467. ParamPart[ParamCount-1].Stop:=p-BufStart+1;
  468. // update NewQueryLength
  469. Dec(NewQueryLength,p-ParamNameStart);
  470. end;
  471. #0:Break;
  472. else
  473. Inc(p);
  474. end;
  475. until false;
  476. SetLength(ParamPart,ParamCount);
  477. SetLength(ODBCCursor.FParamIndex,ParamCount);
  478. if ParamCount>0 then
  479. begin
  480. // replace :ParamName by ? (using ParamPart array and NewQueryLength)
  481. SetLength(NewQuery,NewQueryLength);
  482. NewQueryIndex:=1;
  483. BufIndex:=1;
  484. for i:=0 to High(ParamPart) do
  485. begin
  486. CopyLen:=ParamPart[i].Start-BufIndex;
  487. Move(buf[BufIndex],NewQuery[NewQueryIndex],CopyLen);
  488. Inc(NewQueryIndex,CopyLen);
  489. NewQuery[NewQueryIndex]:='?';
  490. Inc(NewQueryIndex);
  491. BufIndex:=ParamPart[i].Stop;
  492. end;
  493. CopyLen:=Length(Buf)+1-BufIndex;
  494. Move(buf[BufIndex],NewQuery[NewQueryIndex],CopyLen);
  495. end
  496. else
  497. NewQuery:=buf;
  498. // prepare statement
  499. SQLPrepare(ODBCCursor.FSTMTHandle, PChar(NewQuery), Length(NewQuery));
  500. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not prepare statement.');
  501. ODBCCursor.FQuery:=NewQuery;
  502. end;
  503. procedure TODBCConnection.UnPrepareStatement(cursor: TSQLCursor);
  504. begin
  505. // not necessary in ODBC
  506. end;
  507. function TODBCConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  508. begin
  509. // Tranactions not implemented yet
  510. end;
  511. function TODBCConnection.StartDBTransaction(trans: TSQLHandle; AParams:string): boolean;
  512. begin
  513. // Tranactions not implemented yet
  514. end;
  515. function TODBCConnection.Commit(trans: TSQLHandle): boolean;
  516. begin
  517. // Tranactions not implemented yet
  518. end;
  519. function TODBCConnection.Rollback(trans: TSQLHandle): boolean;
  520. begin
  521. // Tranactions not implemented yet
  522. end;
  523. procedure TODBCConnection.CommitRetaining(trans: TSQLHandle);
  524. begin
  525. // Tranactions not implemented yet
  526. end;
  527. procedure TODBCConnection.RollbackRetaining(trans: TSQLHandle);
  528. begin
  529. // Tranactions not implemented yet
  530. end;
  531. procedure TODBCConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  532. var
  533. ODBCCursor:TODBCCursor;
  534. Res:SQLRETURN;
  535. begin
  536. ODBCCursor:=cursor as TODBCCursor;
  537. // set parameters
  538. SetParameters(ODBCCursor, AParams);
  539. // execute the statement
  540. Res:=SQLExecute(ODBCCursor.FSTMTHandle);
  541. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not execute statement.');
  542. // free parameter buffers
  543. FreeParamBuffers(ODBCCursor);
  544. end;
  545. function TODBCConnection.Fetch(cursor: TSQLCursor): boolean;
  546. var
  547. ODBCCursor:TODBCCursor;
  548. Res:SQLRETURN;
  549. begin
  550. ODBCCursor:=cursor as TODBCCursor;
  551. // fetch new row
  552. Res:=SQLFetch(ODBCCursor.FSTMTHandle);
  553. if Res<>SQL_NO_DATA then
  554. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not fetch new row from result set');
  555. // result is true iff a new row was available
  556. Result:=Res<>SQL_NO_DATA;
  557. end;
  558. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer): boolean;
  559. var
  560. ODBCCursor:TODBCCursor;
  561. StrLenOrInd:SQLINTEGER;
  562. ODBCDateStruct:SQL_DATE_STRUCT;
  563. ODBCTimeStruct:SQL_TIME_STRUCT;
  564. ODBCTimeStampStruct:SQL_TIMESTAMP_STRUCT;
  565. DateTime:TDateTime;
  566. begin
  567. ODBCCursor:=cursor as TODBCCursor;
  568. // load the field using SQLGetData
  569. // Note: optionally we can implement the use of SQLBindCol later for even more speed
  570. // TODO: finish this
  571. case FieldDef.DataType of
  572. ftFixedChar,ftString: // are both mapped to TStringField
  573. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_CHAR, buffer, FieldDef.Size, @StrLenOrInd);
  574. ftSmallint: // mapped to TSmallintField
  575. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SSHORT, buffer, SizeOf(Smallint), @StrLenOrInd);
  576. ftInteger,ftWord: // mapped to TLongintField
  577. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SLONG, buffer, SizeOf(Longint), @StrLenOrInd);
  578. ftLargeint: // mapped to TLargeintField
  579. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SBIGINT, buffer, SizeOf(Largeint), @StrLenOrInd);
  580. ftFloat: // mapped to TFloatField
  581. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_DOUBLE, buffer, SizeOf(Double), @StrLenOrInd);
  582. ftTime: // mapped to TTimeField
  583. begin
  584. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIME, @ODBCTimeStruct, SizeOf(SQL_TIME_STRUCT), @StrLenOrInd);
  585. DateTime:=TimeStructToDateTime(@ODBCTimeStruct);
  586. Move(DateTime, buffer^, SizeOf(TDateTime));
  587. end;
  588. ftDate: // mapped to TDateField
  589. begin
  590. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_DATE, @ODBCDateStruct, SizeOf(SQL_DATE_STRUCT), @StrLenOrInd);
  591. DateTime:=DateStructToDateTime(@ODBCDateStruct);
  592. Move(DateTime, buffer^, SizeOf(TDateTime));
  593. end;
  594. ftDateTime: // mapped to TDateTimeField
  595. begin
  596. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIMESTAMP, @ODBCTimeStampStruct, SizeOf(SQL_TIMESTAMP_STRUCT), @StrLenOrInd);
  597. DateTime:=TimeStampStructToDateTime(@ODBCTimeStampStruct);
  598. Move(DateTime, buffer^, SizeOf(TDateTime));
  599. end;
  600. ftBoolean: // mapped to TBooleanField
  601. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BIT, buffer, SizeOf(Wordbool), @StrLenOrInd);
  602. ftBytes: // mapped to TBytesField
  603. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  604. ftVarBytes: // mapped to TVarBytesField
  605. SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  606. // TODO: Loading of other field types
  607. else
  608. raise EODBCException.CreateFmt('Tried to load field of unsupported field type %s',[Fieldtypenames[FieldDef.DataType]]);
  609. end;
  610. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get field data for field ''%s'' (index %d).',[FieldDef.Name, FieldDef.Index+1]));
  611. Result:=StrLenOrInd<>SQL_NULL_DATA; // Result indicates whether the value is non-null
  612. // writeln(Format('Field.Size: %d; StrLenOrInd: %d',[FieldDef.Size, StrLenOrInd]));
  613. end;
  614. function TODBCConnection.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
  615. begin
  616. // TODO: implement TODBCConnection.CreateBlobStream
  617. Result:=nil;
  618. end;
  619. procedure TODBCConnection.FreeFldBuffers(cursor: TSQLCursor);
  620. var
  621. ODBCCursor:TODBCCursor;
  622. begin
  623. ODBCCursor:=cursor as TODBCCursor;
  624. SQLFreeStmt(ODBCCursor.FSTMTHandle, SQL_CLOSE);
  625. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not close ODBC statement cursor.');
  626. end;
  627. procedure TODBCConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TFieldDefs);
  628. const
  629. ColNameDefaultLength = 40; // should be > 0, because an ansistring of length 0 is a nil pointer instead of a pointer to a #0
  630. var
  631. ODBCCursor:TODBCCursor;
  632. ColumnCount:SQLSMALLINT;
  633. i:integer;
  634. ColNameLength,DataType,DecimalDigits,Nullable:SQLSMALLINT;
  635. ColumnSize:SQLUINTEGER;
  636. ColName:string;
  637. FieldType:TFieldType;
  638. FieldSize:word;
  639. begin
  640. ODBCCursor:=cursor as TODBCCursor;
  641. // get number of columns in result set
  642. SQLNumResultCols(ODBCCursor.FSTMTHandle, ColumnCount);
  643. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not determine number of columns in result set.');
  644. for i:=1 to ColumnCount do
  645. begin
  646. SetLength(ColName,ColNameDefaultLength); // also garantuees uniqueness
  647. // call with default column name buffer
  648. SQLDescribeCol(ODBCCursor.FSTMTHandle, // statement handle
  649. i, // column number, is 1-based (Note: column 0 is the bookmark column in ODBC)
  650. @(ColName[1]), // default buffer
  651. ColNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  652. ColNameLength, // actual column name length
  653. DataType, // the SQL datatype for the column
  654. ColumnSize, // column size
  655. DecimalDigits, // number of decimal digits
  656. Nullable); // SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
  657. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get column properties for column %d.',[i]));
  658. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  659. SetLength(ColName,ColNameLength);
  660. // check whether entire column name was returned
  661. if ColNameLength>ColNameDefaultLength then
  662. begin
  663. // request column name with buffer that is long enough
  664. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  665. i, // column number
  666. SQL_DESC_NAME, // the column name or alias
  667. @(ColName[1]), // buffer
  668. ColNameLength+1, // buffer size
  669. @ColNameLength, // actual length
  670. nil); // no numerical output
  671. ODBCCheckResult(SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, Format('Could not get column name for column %d.',[i]));
  672. end;
  673. // convert type
  674. // NOTE: I made some guesses here after I found only limited information about TFieldType; please report any problems
  675. case DataType of
  676. SQL_CHAR: begin FieldType:=ftFixedChar; FieldSize:=ColumnSize+1; end;
  677. SQL_VARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end;
  678. SQL_LONGVARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize+1; end; // no fixed maximum length; make ftMemo when blobs are supported
  679. SQL_WCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end;
  680. SQL_WVARCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end;
  681. SQL_WLONGVARCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize+1; end; // no fixed maximum length; make ftMemo when blobs are supported
  682. SQL_DECIMAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  683. SQL_NUMERIC: begin FieldType:=ftFloat; FieldSize:=0; end;
  684. SQL_SMALLINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  685. SQL_INTEGER: begin FieldType:=ftInteger; FieldSize:=0; end;
  686. SQL_REAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  687. SQL_FLOAT: begin FieldType:=ftFloat; FieldSize:=0; end;
  688. SQL_DOUBLE: begin FieldType:=ftFloat; FieldSize:=0; end;
  689. SQL_BIT: begin FieldType:=ftBoolean; FieldSize:=0; end;
  690. SQL_TINYINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  691. SQL_BIGINT: begin FieldType:=ftLargeint; FieldSize:=0; end;
  692. SQL_BINARY: begin FieldType:=ftBytes; FieldSize:=ColumnSize; end;
  693. SQL_VARBINARY: begin FieldType:=ftVarBytes; FieldSize:=ColumnSize; end;
  694. SQL_LONGVARBINARY: begin FieldType:=ftBlob; FieldSize:=ColumnSize; end;
  695. SQL_TYPE_DATE: begin FieldType:=ftDate; FieldSize:=0; end;
  696. SQL_TYPE_TIME: begin FieldType:=ftTime; FieldSize:=0; end;
  697. SQL_TYPE_TIMESTAMP:begin FieldType:=ftTimeStamp; FieldSize:=0; end;
  698. { SQL_TYPE_UTCDATETIME:FieldType:=ftUnknown;}
  699. { SQL_TYPE_UTCTIME: FieldType:=ftUnknown; }
  700. { SQL_INTERVAL_MONTH: FieldType:=ftUnknown;}
  701. { SQL_INTERVAL_YEAR: FieldType:=ftUnknown;}
  702. { SQL_INTERVAL_YEAR_TO_MONTH: FieldType:=ftUnknown;}
  703. { SQL_INTERVAL_DAY: FieldType:=ftUnknown;}
  704. { SQL_INTERVAL_HOUR: FieldType:=ftUnknown;}
  705. { SQL_INTERVAL_MINUTE: FieldType:=ftUnknown;}
  706. { SQL_INTERVAL_SECOND: FieldType:=ftUnknown;}
  707. { SQL_INTERVAL_DAY_TO_HOUR: FieldType:=ftUnknown;}
  708. { SQL_INTERVAL_DAY_TO_MINUTE: FieldType:=ftUnknown;}
  709. { SQL_INTERVAL_DAY_TO_SECOND: FieldType:=ftUnknown;}
  710. { SQL_INTERVAL_HOUR_TO_MINUTE: FieldType:=ftUnknown;}
  711. { SQL_INTERVAL_HOUR_TO_SECOND: FieldType:=ftUnknown;}
  712. { SQL_INTERVAL_MINUTE_TO_SECOND:FieldType:=ftUnknown;}
  713. { SQL_GUID: begin FieldType:=ftGuid; FieldSize:=ColumnSize; end; } // no TGuidField exists yet in the db unit
  714. else
  715. begin FieldType:=ftUnknown; FieldSize:=ColumnSize; end
  716. end;
  717. // add FieldDef
  718. TFieldDef.Create(FieldDefs, ColName, FieldType, FieldSize, False, i);
  719. end;
  720. end;
  721. procedure TODBCConnection.UpdateIndexDefs(var IndexDefs: TIndexDefs; TableName: string);
  722. begin
  723. inherited UpdateIndexDefs(IndexDefs, TableName);
  724. // TODO: implement this
  725. end;
  726. function TODBCConnection.GetSchemaInfoSQL(SchemaType: TSchemaType; SchemaObjectName, SchemaObjectPattern: string): string;
  727. begin
  728. Result:=inherited GetSchemaInfoSQL(SchemaType, SchemaObjectName, SchemaObjectPattern);
  729. // TODO: implement this
  730. end;
  731. { TODBCEnvironment }
  732. constructor TODBCEnvironment.Create;
  733. begin
  734. // make sure odbc is loaded
  735. if ODBCLoadCount=0 then LoadOdbc;
  736. Inc(ODBCLoadCount);
  737. // allocate environment handle
  738. if SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, FENVHandle)=SQL_Error then
  739. 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
  740. // set odbc version
  741. SQLSetEnvAttr(FENVHandle, SQL_ATTR_ODBC_VERSION, SQLPOINTER(SQL_OV_ODBC3), 0);
  742. ODBCCheckResult(SQL_HANDLE_ENV, FENVHandle,'Could not set ODBC version to 3.');
  743. end;
  744. destructor TODBCEnvironment.Destroy;
  745. begin
  746. // free environment handle
  747. if SQLFreeHandle(SQL_HANDLE_ENV, FENVHandle)=SQL_ERROR then
  748. ODBCCheckResult(SQL_HANDLE_ENV, FENVHandle, 'Could not free ODBC Environment handle.');
  749. // free odbc if not used by any TODBCEnvironment object anymore
  750. Dec(ODBCLoadCount);
  751. if ODBCLoadCount=0 then UnLoadOdbc;
  752. end;
  753. { TODBCCursor }
  754. constructor TODBCCursor.Create(Connection:TODBCConnection);
  755. begin
  756. // allocate statement handle
  757. SQLAllocHandle(SQL_HANDLE_STMT, Connection.FDBCHandle, FSTMTHandle);
  758. ODBCCheckResult(SQL_HANDLE_DBC, Connection.FDBCHandle, 'Could not allocate ODBC Statement handle.');
  759. end;
  760. destructor TODBCCursor.Destroy;
  761. begin
  762. inherited Destroy;
  763. // deallocate statement handle
  764. if SQLFreeHandle(SQL_HANDLE_STMT, FSTMTHandle)=SQL_ERROR then
  765. ODBCCheckResult(SQL_HANDLE_STMT, FSTMTHandle, 'Could not free ODBC Statement handle.');
  766. end;
  767. { finalization }
  768. finalization
  769. if Assigned(DefaultEnvironment) then
  770. DefaultEnvironment.Free;
  771. end.