odbcconn.pas 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  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, db, sqldb, BufDataset, odbcsqldyn;
  16. type
  17. // forward declarations
  18. TODBCConnection = class;
  19. { TODBCCursor }
  20. TODBCCursor = class(TSQLCursor)
  21. protected
  22. FSTMTHandle:SQLHSTMT; // ODBC Statement Handle
  23. FQuery:string; // last prepared query, with :ParamName converted to ?
  24. FParamIndex:TParamBinding; // maps the i-th parameter in the query to the TParams passed to PrepareStatement
  25. FParamBuf:array of pointer; // buffers that can be used to bind the i-th parameter in the query
  26. 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. type
  46. TDBMSInfo = record
  47. GetLastInsertIDSQL: string; // SQL statement for get last insert value for autoincrement column
  48. end;
  49. var
  50. FDriver: string;
  51. FEnvironment:TODBCEnvironment;
  52. FDBCHandle:SQLHDBC; // ODBC Connection Handle
  53. FFileDSN: string;
  54. FDBMSInfo: TDBMSInfo;
  55. procedure SetParameters(ODBCCursor:TODBCCursor; AParams:TParams);
  56. procedure FreeParamBuffers(ODBCCursor:TODBCCursor);
  57. protected
  58. // Overrides from TSQLConnection
  59. function GetHandle:pointer; override;
  60. // - Connect/disconnect
  61. procedure DoInternalConnect; override;
  62. procedure DoInternalDisconnect; override;
  63. // - Handle (de)allocation
  64. function AllocateCursorHandle:TSQLCursor; override;
  65. procedure DeAllocateCursorHandle(var cursor:TSQLCursor); override;
  66. function AllocateTransactionHandle:TSQLHandle; override;
  67. // - Statement handling
  68. function StrToStatementType(s : string) : TStatementType; override;
  69. procedure PrepareStatement(cursor:TSQLCursor; ATransaction:TSQLTransaction; buf:string; AParams:TParams); override;
  70. procedure UnPrepareStatement(cursor:TSQLCursor); override;
  71. // - Transaction handling
  72. function GetTransactionHandle(trans:TSQLHandle):pointer; override;
  73. function StartDBTransaction(trans:TSQLHandle; AParams:string):boolean; override;
  74. function Commit(trans:TSQLHandle):boolean; override;
  75. function Rollback(trans:TSQLHandle):boolean; override;
  76. procedure CommitRetaining(trans:TSQLHandle); override;
  77. procedure RollbackRetaining(trans:TSQLHandle); override;
  78. // - Statement execution
  79. procedure Execute(cursor:TSQLCursor; ATransaction:TSQLTransaction; AParams:TParams); override;
  80. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  81. function RefreshLastInsertID(Query : TCustomSQLQuery; Field : TField): boolean; override;
  82. // - Result retrieving
  83. procedure AddFieldDefs(cursor:TSQLCursor; FieldDefs:TFieldDefs); override;
  84. function Fetch(cursor:TSQLCursor):boolean; override;
  85. function LoadField(cursor:TSQLCursor; FieldDef:TFieldDef; buffer:pointer; out CreateBlob : boolean):boolean; override;
  86. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction : TSQLTransaction); override;
  87. procedure FreeFldBuffers(cursor:TSQLCursor); override;
  88. // - UpdateIndexDefs
  89. procedure UpdateIndexDefs(IndexDefs:TIndexDefs; TableName:string); override;
  90. // - Schema info
  91. function GetSchemaInfoSQL(SchemaType:TSchemaType; SchemaObjectName, SchemaObjectPattern:string):string; override;
  92. // Internal utility functions
  93. function CreateConnectionString:string;
  94. public
  95. constructor Create(AOwner : TComponent); override;
  96. function GetConnectionInfo(InfoType:TConnInfoType): string; override;
  97. property Environment:TODBCEnvironment read FEnvironment;
  98. published
  99. property Driver:string read FDriver write FDriver; // will be passed as DRIVER connection parameter
  100. property FileDSN:string read FFileDSN write FFileDSN; // will be passed as FILEDSN parameter
  101. // Redeclare properties from TSQLConnection
  102. property Password; // will be passed as PWD connection parameter
  103. property Transaction;
  104. property UserName; // will be passed as UID connection parameter
  105. property CharSet;
  106. property HostName; // ignored
  107. // Redeclare properties from TDatabase
  108. property Connected;
  109. property Role;
  110. property DatabaseName; // will be passed as DSN connection parameter
  111. property KeepConnection;
  112. property LoginPrompt; // if true, ODBC drivers might prompt for more details that are not in the connection string
  113. property Params; // will be added to connection string
  114. property OnLogin;
  115. end;
  116. EODBCException = class(ESQLDatabaseError);
  117. { TODBCConnectionDef }
  118. TODBCConnectionDef = Class(TConnectionDef)
  119. Class Function TypeName : String; override;
  120. Class Function ConnectionClass : TSQLConnectionClass; override;
  121. Class Function Description : String; override;
  122. end;
  123. implementation
  124. uses
  125. ctypes;
  126. const
  127. DefaultEnvironment:TODBCEnvironment = nil;
  128. ODBCLoadCount:integer = 0; // ODBC is loaded when > 0; modified by TODBCEnvironment.Create/Destroy
  129. { Generic ODBC helper functions }
  130. function ODBCSuccess(const Res:SQLRETURN):boolean;
  131. begin
  132. Result:=(Res=SQL_SUCCESS) or (Res=SQL_SUCCESS_WITH_INFO);
  133. end;
  134. function ODBCResultToStr(Res:SQLRETURN):string;
  135. begin
  136. case Res of
  137. SQL_SUCCESS: Result:='SQL_SUCCESS';
  138. SQL_SUCCESS_WITH_INFO:Result:='SQL_SUCCESS_WITH_INFO';
  139. SQL_ERROR: Result:='SQL_ERROR';
  140. SQL_INVALID_HANDLE: Result:='SQL_INVALID_HANDLE';
  141. SQL_NO_DATA: Result:='SQL_NO_DATA';
  142. SQL_NEED_DATA: Result:='SQL_NEED_DATA';
  143. SQL_STILL_EXECUTING: Result:='SQL_STILL_EXECUTING';
  144. else
  145. Result:='';
  146. end;
  147. end;
  148. procedure ODBCCheckResult(LastReturnCode:SQLRETURN; HandleType:SQLSMALLINT; AHandle: SQLHANDLE; ErrorMsg: string; const FmtArgs:array of const);
  149. // check return value from SQLGetDiagField/Rec function itself
  150. procedure CheckSQLGetDiagResult(const Res:SQLRETURN);
  151. begin
  152. case Res of
  153. SQL_INVALID_HANDLE:
  154. raise EODBCException.Create('Invalid handle passed to SQLGetDiagRec/Field');
  155. SQL_ERROR:
  156. raise EODBCException.Create('An invalid parameter was passed to SQLGetDiagRec/Field');
  157. SQL_NO_DATA:
  158. raise EODBCException.Create('A too large RecNumber was passed to SQLGetDiagRec/Field');
  159. end;
  160. end;
  161. var
  162. NativeError, NativeError1: SQLINTEGER;
  163. TextLength:SQLSMALLINT;
  164. Res:SQLRETURN;
  165. SqlState, SQLState1, MessageText, TotalMessage: string;
  166. RecNumber:SQLSMALLINT;
  167. begin
  168. // check result
  169. if ODBCSuccess(LastReturnCode) then
  170. Exit; // no error; all is ok
  171. //WriteLn('LastResultCode: ',ODBCResultToStr(LastReturnCode));
  172. try
  173. NativeError1:=0;
  174. SQLState1:='';
  175. // build TotalMessage for exception to throw
  176. TotalMessage:=Format(ErrorMsg,FmtArgs)+Format(' ODBC error details: LastReturnCode: %s;',[ODBCResultToStr(LastReturnCode)]);
  177. // retrieve status records
  178. SetLength(MessageText,1);
  179. RecNumber:=1;
  180. repeat
  181. SetLength(SqlState,5); // reset 5-character buffer
  182. // dummy call to get correct TextLength
  183. //WriteLn('Getting error record ',RecNumber);
  184. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(MessageText[1]),0,TextLength);
  185. if Res=SQL_NO_DATA then
  186. Break; // no more status records
  187. CheckSQLGetDiagResult(Res);
  188. 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
  189. begin
  190. // allocate large enough buffer
  191. SetLength(MessageText,TextLength); // note: ansistrings of Length>0 are always terminated by a #0 character, so this is safe
  192. // actual call
  193. Res:=SQLGetDiagRec(HandleType,AHandle,RecNumber,@(SqlState[1]),NativeError,@(MessageText[1]),Length(MessageText)+1,TextLength);
  194. CheckSQLGetDiagResult(Res);
  195. end;
  196. // add to TotalMessage
  197. TotalMessage:=TotalMessage+Format(' Record %d: SqlState: %s; NativeError: %d; Message: %s;',[RecNumber,SqlState,NativeError,MessageText]);
  198. // save most significant error
  199. if RecNumber = 1 then
  200. begin
  201. NativeError1 := NativeError;
  202. SQLState1 := SqlState;
  203. end;
  204. // incement counter
  205. Inc(RecNumber);
  206. until false;
  207. except
  208. on E:EODBCException do begin
  209. TotalMessage:=TotalMessage+Format('Could not get error message: %s',[E.Message]);
  210. end
  211. end;
  212. // raise error
  213. raise EODBCException.CreateFmt(TotalMessage, [], nil, NativeError1, SQLState1);
  214. end;
  215. procedure ODBCCheckResult(LastReturnCode:SQLRETURN; HandleType:SQLSMALLINT; AHandle: SQLHANDLE; ErrorMsg: string);
  216. begin
  217. ODBCCheckResult(LastReturnCode, HandleType, AHandle, ErrorMsg, []);
  218. end;
  219. { TODBCConnection }
  220. // Creates a connection string using the current value of the fields
  221. function TODBCConnection.CreateConnectionString: string;
  222. // encloses a param value with braces if necessary, i.e. when any of the characters []{}(),;?*=!@ is in the value
  223. function EscapeParamValue(const s:string):string;
  224. var
  225. NeedEscape:boolean;
  226. i:integer;
  227. begin
  228. NeedEscape:=false;
  229. for i:=1 to Length(s) do
  230. if s[i] in ['[',']','{','}','(',')',',','*','=','!','@'] then
  231. begin
  232. NeedEscape:=true;
  233. Break;
  234. end;
  235. if NeedEscape then
  236. Result:='{'+s+'}'
  237. else
  238. Result:=s;
  239. end;
  240. var
  241. i: Integer;
  242. Param: string;
  243. EqualSignPos:integer;
  244. begin
  245. Result:='';
  246. if DatabaseName<>'' then Result:=Result + 'DSN='+EscapeParamValue(DatabaseName)+';';
  247. if Driver <>'' then Result:=Result + 'DRIVER='+EscapeParamValue(Driver)+';';
  248. if UserName <>'' then Result:=Result + 'UID='+EscapeParamValue(UserName)+';PWD='+EscapeParamValue(Password)+';';
  249. if FileDSN <>'' then Result:=Result + 'FILEDSN='+EscapeParamValue(FileDSN)+'';
  250. for i:=0 to Params.Count-1 do
  251. begin
  252. Param:=Params[i];
  253. EqualSignPos:=Pos('=',Param);
  254. if EqualSignPos=0 then
  255. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; can''t find a ''='' in ''%s''',[i, Param])
  256. else if EqualSignPos=1 then
  257. raise EODBCException.CreateFmt('Invalid parameter in Params[%d]; no identifier before the ''='' in ''%s''',[i, Param])
  258. else
  259. Result:=Result + EscapeParamValue(Copy(Param,1,EqualSignPos-1))+'='+EscapeParamValue(Copy(Param,EqualSignPos+1,MaxInt))+';';
  260. end;
  261. end;
  262. constructor TODBCConnection.Create(AOwner: TComponent);
  263. begin
  264. inherited Create(AOwner);
  265. FConnOptions := FConnOptions + [sqSupportEmptyDatabaseName, sqEscapeRepeat, sqEscapeSlash];
  266. end;
  267. function TODBCConnection.StrToStatementType(s : string) : TStatementType;
  268. begin
  269. case Lowercase(s) of
  270. 'transform': // MS Access
  271. Result := stSelect;
  272. 'exec', 'call':
  273. Result := stExecProcedure;
  274. else
  275. Result := inherited StrToStatementType(s);
  276. end;
  277. end;
  278. (*
  279. function BCDToNumericStruct(const bcd: TBCD): SQL_NUMERIC_STRUCT;
  280. var i, j, p: integer;
  281. nibble: Byte;
  282. a, m, carry: DWord;
  283. BigInt: array[0..3] of QWord;
  284. qw: QWord;
  285. pdw: PDWord;
  286. begin
  287. Result.precision := BCDPrecision(bcd);
  288. if Result.precision = 0 then Result.precision := 1; // if bcd is NULL
  289. Result.scale := BCDScale(bcd);
  290. if IsBCDNegative(bcd) then
  291. Result.sign := 0
  292. else
  293. Result.sign := 1;
  294. // BigInt := 0
  295. FillByte(BigInt, sizeof(BigInt), 0);
  296. // process BCD nibbles (high nibble is at 0)
  297. p := Result.precision;
  298. i := 0;
  299. while p > 0 do
  300. begin
  301. nibble := bcd.Fraction[i];
  302. if p = 1 then
  303. begin
  304. a := nibble shr 4;
  305. m := 10;
  306. end
  307. else
  308. begin
  309. a := (nibble shr 4)*10 + nibble and $0F;
  310. m := 100;
  311. end;
  312. // BigInt := BigInt * m + a
  313. // big multiplication
  314. j := 0; carry := 0;
  315. repeat
  316. qw := BigInt[j] * m + carry;
  317. BigInt[j] := qw and $FFFFFFFF;
  318. carry := qw shr 32;
  319. inc(j);
  320. until j>high(BigInt);
  321. // big addition
  322. j := 0; carry := 0;
  323. repeat
  324. qw := BigInt[j] + a + carry;
  325. BigInt[j] := qw and $FFFFFFFF;
  326. carry := qw shr 32;
  327. inc(j);
  328. until (carry = 0) or (j>high(BigInt));
  329. dec(p,2);
  330. inc(i);
  331. end;
  332. // SQL_NUMERIC_STRUCT.val size must be 16 bytes (128bit integer)
  333. pdw := @Result.val;
  334. for j:=0 to high(BigInt) do
  335. begin
  336. pdw^ := NtoLE(BigInt[j]);
  337. inc(pdw);
  338. end;
  339. end;
  340. *)
  341. procedure TODBCConnection.SetParameters(ODBCCursor: TODBCCursor; AParams: TParams);
  342. var
  343. ParamIndex: integer;
  344. PVal, Buf, PStrLenOrInd: pointer;
  345. I, Size: integer;
  346. IntVal: clong;
  347. LargeVal: clonglong;
  348. StrVal: ansistring;
  349. WideStrVal: widestring;
  350. FloatVal: cdouble;
  351. DateVal: SQL_DATE_STRUCT;
  352. TimeVal: SQL_TIME_STRUCT;
  353. TimeStampVal: SQL_TIMESTAMP_STRUCT;
  354. BoolVal: byte;
  355. NumericVal: SQL_NUMERIC_STRUCT;
  356. ColumnSize: SQLULEN;
  357. BufferLength, StrLenOrInd: SQLLEN;
  358. CType, SqlType, DecimalDigits:SQLSMALLINT;
  359. APD: SQLHDESC;
  360. BytesVal: TBytes;
  361. begin
  362. // Note: it is assumed that AParams is the same as the one passed to PrepareStatement, in the sense that
  363. // the parameters have the same order and names
  364. if Length(ODBCCursor.FParamIndex)>0 then
  365. if not Assigned(AParams) then
  366. raise EODBCException.CreateFmt('The query has parameter markers in it, but no actual parameters were passed',[]);
  367. SetLength(ODBCCursor.FParamBuf, Length(ODBCCursor.FParamIndex));
  368. for i:=0 to High(ODBCCursor.FParamIndex) do
  369. ODBCCursor.FParamBuf[i]:=nil;
  370. for i:=0 to High(ODBCCursor.FParamIndex) do
  371. begin
  372. ParamIndex:=ODBCCursor.FParamIndex[i];
  373. if (ParamIndex<0) or (ParamIndex>=AParams.Count) then
  374. raise EODBCException.CreateFmt('Parameter %d in query does not have a matching parameter set',[i]);
  375. DecimalDigits:=0;
  376. BufferLength:=0;
  377. StrLenOrInd:=0;
  378. case AParams[ParamIndex].DataType of
  379. ftInteger, ftSmallInt, ftWord, ftAutoInc:
  380. begin
  381. IntVal:=AParams[ParamIndex].AsInteger;
  382. PVal:=@IntVal;
  383. Size:=SizeOf(IntVal);
  384. CType:=SQL_C_LONG;
  385. SqlType:=SQL_INTEGER;
  386. ColumnSize:=10;
  387. end;
  388. ftLargeInt:
  389. begin
  390. LargeVal:=AParams[ParamIndex].AsLargeInt;
  391. PVal:=@LargeVal;
  392. Size:=SizeOf(LargeVal);
  393. CType:=SQL_C_SBIGINT;
  394. SqlType:=SQL_BIGINT;
  395. ColumnSize:=19;
  396. end;
  397. ftBlob, ftBytes, ftVarBytes:
  398. begin
  399. BytesVal:=AParams[ParamIndex].AsBytes;
  400. StrLenOrInd:=Length(BytesVal);
  401. if Length(BytesVal)=0 then //HY104
  402. begin
  403. BytesVal:=[0];
  404. StrLenOrInd:=SQL_NTS;
  405. end;
  406. PVal:=@BytesVal[0];
  407. Size:=Length(BytesVal);
  408. ColumnSize:=Size;
  409. BufferLength:=Size;
  410. CType:=SQL_C_BINARY;
  411. case AParams[ParamIndex].DataType of
  412. ftBytes, ftVarBytes: SqlType:=SQL_VARBINARY;
  413. else // ftBlob
  414. SqlType:=SQL_LONGVARBINARY;
  415. end;
  416. end;
  417. ftString, ftFixedChar, ftMemo, ftGuid, // string parameters must be passed as widestring to support FPC 3.0.x character conversion
  418. ftWideString, ftFixedWideChar, ftWideMemo:
  419. begin
  420. WideStrVal:=AParams[ParamIndex].AsWideString;
  421. StrLenOrInd:=Length(WideStrVal)*sizeof(widechar);
  422. if WideStrVal='' then //HY104
  423. begin
  424. WideStrVal:=#0;
  425. StrLenOrInd:=SQL_NTS;
  426. end;
  427. PVal:=@WideStrVal[1];
  428. Size:=Length(WideStrVal)*sizeof(widechar);
  429. ColumnSize:=Size; //The defined or maximum column size in characters of the column or parameter
  430. BufferLength:=Size;
  431. CType:=SQL_C_WCHAR;
  432. case AParams[ParamIndex].DataType of
  433. ftMemo, ftWideMemo: SqlType:=SQL_WLONGVARCHAR;
  434. else SqlType:=SQL_WVARCHAR;
  435. end;
  436. end;
  437. ftFloat:
  438. begin
  439. FloatVal:=AParams[ParamIndex].AsFloat;
  440. PVal:=@FloatVal;
  441. Size:=SizeOf(FloatVal);
  442. CType:=SQL_C_DOUBLE;
  443. SqlType:=SQL_DOUBLE;
  444. ColumnSize:=15;
  445. end;
  446. ftCurrency, ftBCD:
  447. begin
  448. NumericVal:=CurrToNumericStruct(AParams[ParamIndex].AsCurrency);
  449. PVal:=@NumericVal;
  450. Size:=SizeOf(NumericVal);
  451. CType:=SQL_C_NUMERIC;
  452. SqlType:=SQL_NUMERIC;
  453. ColumnSize:=NumericVal.precision;
  454. DecimalDigits:=NumericVal.scale;
  455. end;
  456. ftFmtBCD:
  457. begin
  458. // bind FmtBCD parameter as string to support higher precision than 10^38 (supported by SQL_NUMERIC_STRUCT)
  459. StrVal:=GetAsSQLText(AParams[ParamIndex]);
  460. StrLenOrInd:=Length(StrVal);
  461. PVal:=@StrVal[1];
  462. Size:=Length(StrVal);
  463. CType:=SQL_C_CHAR;
  464. SqlType:=SQL_CHAR;
  465. ColumnSize:=Size;
  466. BufferLength:=Size;
  467. end;
  468. ftDate:
  469. begin
  470. DateVal:=DateTimeToDateStruct(AParams[ParamIndex].AsDate);
  471. PVal:=@DateVal;
  472. Size:=SizeOf(DateVal);
  473. CType:=SQL_C_TYPE_DATE;
  474. SqlType:=SQL_TYPE_DATE;
  475. ColumnSize:=10;
  476. end;
  477. ftTime:
  478. begin
  479. TimeVal:=DateTimeToTimeStruct(AParams[ParamIndex].AsTime);
  480. PVal:=@TimeVal;
  481. Size:=SizeOf(TimeVal);
  482. CType:=SQL_C_TYPE_TIME;
  483. SqlType:=SQL_TYPE_TIME;
  484. ColumnSize:=12;
  485. end;
  486. ftDateTime:
  487. begin
  488. DateTime2TimeStampStruct(TimeStampVal, AParams[ParamIndex].AsDateTime);
  489. PVal:=@TimeStampVal;
  490. Size:=SizeOf(TimeStampVal);
  491. CType:=SQL_C_TYPE_TIMESTAMP;
  492. SqlType:=SQL_TYPE_TIMESTAMP;
  493. ColumnSize:=23;
  494. DecimalDigits:=3; // fractional seconds
  495. end;
  496. ftBoolean:
  497. begin
  498. BoolVal:=ord(AParams[ParamIndex].AsBoolean);
  499. PVal:=@BoolVal;
  500. Size:=SizeOf(BoolVal);
  501. CType:=SQL_C_BIT;
  502. SqlType:=SQL_BIT;
  503. ColumnSize:=Size;
  504. end;
  505. ftUnknown:
  506. begin
  507. if AParams[ParamIndex].IsNull then // Null variant is stored as ftUnknown - send it over as TINYINT (it doesn't really matter what type)
  508. begin
  509. PVal:=nil;
  510. Size:=0;
  511. CType:=SQL_C_TINYINT;
  512. SqlType:=SQL_TINYINT;
  513. ColumnSize:=Size;
  514. end else
  515. raise EDataBaseError.CreateFmt('Not-null unknown Parameter (index %d) is not supported.',[ParamIndex]);
  516. end;
  517. else
  518. raise EDataBaseError.CreateFmt('Parameter %d is of type %s, which not supported yet',[ParamIndex, Fieldtypenames[AParams[ParamIndex].DataType]]);
  519. end;
  520. if AParams[ParamIndex].IsNull then
  521. StrLenOrInd:=SQL_NULL_DATA;
  522. Buf:=GetMem(Size+SizeOf(StrLenOrInd));
  523. if Size>0 then
  524. Move(PVal^, Buf^, Size);
  525. if StrLenOrInd<>0 then
  526. begin
  527. PStrLenOrInd:=Buf + Size;
  528. Move(StrLenOrInd, PStrLenOrInd^, SizeOf(StrLenOrInd));
  529. end
  530. else
  531. PStrLenOrInd:=nil;
  532. ODBCCursor.FParamBuf[i]:=Buf;
  533. ODBCCheckResult(
  534. SQLBindParameter(ODBCCursor.FSTMTHandle, // StatementHandle
  535. i+1, // ParameterNumber
  536. SQL_PARAM_INPUT, // InputOutputType
  537. CType, // ValueType
  538. SqlType, // ParameterType
  539. ColumnSize, // ColumnSize
  540. DecimalDigits, // DecimalDigits
  541. Buf, // ParameterValuePtr
  542. BufferLength, // BufferLength
  543. PStrLenOrInd), // StrLen_or_IndPtr
  544. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not bind parameter %d.', [i]
  545. );
  546. // required by MSSQL:
  547. if CType = SQL_C_NUMERIC then
  548. begin
  549. ODBCCheckResult(
  550. SQLGetStmtAttr(ODBCCursor.FSTMTHandle, SQL_ATTR_APP_PARAM_DESC, @APD, 0, nil),
  551. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get parameter descriptor.'
  552. );
  553. SQLSetDescRec(APD, i+1, SQL_C_NUMERIC, 0, ColumnSize+2, ColumnSize, DecimalDigits, Buf, PStrLenOrInd, PStrLenOrInd);
  554. end;
  555. end;
  556. end;
  557. procedure TODBCConnection.FreeParamBuffers(ODBCCursor: TODBCCursor);
  558. var
  559. i:integer;
  560. begin
  561. for i:=0 to High(ODBCCursor.FParamBuf) do
  562. if assigned(ODBCCursor.FParamBuf[i]) then
  563. FreeMem(ODBCCursor.FParamBuf[i]);
  564. SetLength(ODBCCursor.FParamBuf,0);
  565. end;
  566. function TODBCConnection.GetHandle: pointer;
  567. begin
  568. // I'm not sure whether this is correct; perhaps we should return nil
  569. // note that FDBHandle is a LongInt, because ODBC handles are integers, not pointers
  570. // I wonder how this will work on 64 bit platforms then (FK)
  571. Result:=pointer(PtrInt(FDBCHandle));
  572. end;
  573. procedure TODBCConnection.DoInternalConnect;
  574. const
  575. BufferLength = 1024; // should be at least 1024 according to the ODBC specification
  576. var
  577. ConnectionString:string;
  578. OutConnectionString:string;
  579. ActualLength:SQLSMALLINT;
  580. DBMS_NAME: array[0..20] of AnsiChar;
  581. begin
  582. // Do not call the inherited method as it checks for a non-empty DatabaseName, and we don't even use DatabaseName!
  583. // inherited DoInternalConnect;
  584. // make sure we have an environment
  585. if not Assigned(FEnvironment) then
  586. begin
  587. if not Assigned(DefaultEnvironment) then
  588. DefaultEnvironment:=TODBCEnvironment.Create;
  589. FEnvironment:=DefaultEnvironment;
  590. end;
  591. // allocate connection handle
  592. ODBCCheckResult(
  593. SQLAllocHandle(SQL_HANDLE_DBC,Environment.FENVHandle,FDBCHandle),
  594. SQL_HANDLE_ENV,Environment.FENVHandle,'Could not allocate ODBC Connection handle.'
  595. );
  596. try
  597. // connect
  598. ConnectionString:=CreateConnectionString;
  599. SetLength(OutConnectionString,BufferLength-1); // allocate completed connection string buffer (using the ansistring #0 trick)
  600. ODBCCheckResult(
  601. SQLDriverConnect(FDBCHandle, // the ODBC connection handle
  602. nil, // no parent window (would be required for prompts)
  603. PChar(ConnectionString), // the connection string
  604. Length(ConnectionString), // connection string length
  605. @(OutConnectionString[1]),// buffer for storing the completed connection string
  606. BufferLength, // length of the buffer
  607. ActualLength, // the actual length of the completed connection string
  608. SQL_DRIVER_NOPROMPT), // don't prompt for password etc.
  609. SQL_HANDLE_DBC,FDBCHandle,'Could not connect with connection string "%s".',[ConnectionString]
  610. );
  611. except
  612. on E:Exception do begin
  613. // free connection handle
  614. ODBCCheckResult(
  615. SQLFreeHandle(SQL_HANDLE_DBC,FDBCHandle),
  616. SQL_HANDLE_DBC,FDBCHandle,'Could not free ODBC Connection handle.'
  617. );
  618. raise; // re-raise exception
  619. end;
  620. end;
  621. // set DBMS specific options
  622. if SQLGetInfo(FDBCHandle, SQL_DBMS_NAME, @DBMS_NAME, sizeof(DBMS_NAME), @ActualLength) = SQL_SUCCESS then
  623. case AnsiString(DBMS_NAME) of
  624. 'Microsoft SQL Server':
  625. begin
  626. FDBMSInfo.GetLastInsertIDSQL := 'SELECT @@IDENTITY';
  627. Include(FConnOptions, sqLastInsertID);
  628. end;
  629. 'MySQL':
  630. begin
  631. FDBMSInfo.GetLastInsertIDSQL := 'SELECT last_insert_id()';
  632. Include(FConnOptions, sqLastInsertID);
  633. end;
  634. else
  635. begin
  636. FDBMSInfo.GetLastInsertIDSQL := '';
  637. Exclude(FConnOptions, sqLastInsertID);
  638. end;
  639. end;
  640. // set connection attributes (none yet)
  641. end;
  642. procedure TODBCConnection.DoInternalDisconnect;
  643. var
  644. Res:SQLRETURN;
  645. begin
  646. inherited DoInternalDisconnect;
  647. // disconnect
  648. ODBCCheckResult(
  649. SQLDisconnect(FDBCHandle),
  650. SQL_HANDLE_DBC,FDBCHandle,'Could not disconnect.'
  651. );
  652. // deallocate connection handle
  653. Res:=SQLFreeHandle(SQL_HANDLE_DBC, FDBCHandle);
  654. if Res=SQL_ERROR then
  655. ODBCCheckResult(Res,SQL_HANDLE_DBC,FDBCHandle,'Could not free ODBC Connection handle.');
  656. end;
  657. function TODBCConnection.AllocateCursorHandle: TSQLCursor;
  658. begin
  659. Result:=TODBCCursor.Create(self);
  660. end;
  661. procedure TODBCConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  662. begin
  663. FreeAndNil(cursor); // the destructor of TODBCCursor frees the ODBC Statement handle
  664. end;
  665. function TODBCConnection.AllocateTransactionHandle: TSQLHandle;
  666. begin
  667. Result:=nil; // not yet supported; will move connection handles to transaction handles later
  668. end;
  669. procedure TODBCConnection.PrepareStatement(cursor: TSQLCursor; ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  670. var
  671. ODBCCursor:TODBCCursor;
  672. begin
  673. ODBCCursor:=cursor as TODBCCursor;
  674. // allocate statement handle
  675. ODBCCheckResult(
  676. SQLAllocHandle(SQL_HANDLE_STMT, FDBCHandle, ODBCCursor.FSTMTHandle),
  677. SQL_HANDLE_DBC, FDBCHandle, 'Could not allocate ODBC Statement handle.'
  678. );
  679. ODBCCursor.FPrepared:=True;
  680. // Parameter handling
  681. // Note: We can only pass ? parameters to ODBC, so we should convert named parameters like :MyID
  682. // ODBCCursor.FParamIndex will map th i-th ? token in the (modified) query to an index for AParams
  683. // Parse the SQL and build FParamIndex
  684. if assigned(AParams) and (AParams.count > 0) then
  685. begin
  686. buf := AParams.ParseSQL(buf,false,sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions,psInterbase,ODBCCursor.FParamIndex);
  687. if LogEvent(detActualSQL) then
  688. Log(detActualSQL,Buf);
  689. end;
  690. // prepare statement
  691. ODBCCursor.FQuery:=Buf;
  692. if not (ODBCCursor.FSchemaType in [stTables, stSysTables, stColumns, stProcedures, stIndexes]) then
  693. begin
  694. ODBCCheckResult(
  695. SQLPrepare(ODBCCursor.FSTMTHandle, PChar(buf), Length(buf)),
  696. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not prepare statement.'
  697. );
  698. end;
  699. if ODBCCursor.FSchemaType <> stNoSchema then
  700. ODBCCursor.FStatementType:=stSelect;
  701. end;
  702. procedure TODBCConnection.UnPrepareStatement(cursor: TSQLCursor);
  703. var Res:SQLRETURN;
  704. begin
  705. with TODBCCursor(cursor) do
  706. begin
  707. if FSTMTHandle<>SQL_NULL_HSTMT then
  708. begin
  709. // deallocate statement handle
  710. Res:=SQLFreeHandle(SQL_HANDLE_STMT, FSTMTHandle);
  711. if Res=SQL_ERROR then
  712. ODBCCheckResult(Res,SQL_HANDLE_STMT, FSTMTHandle, 'Could not free ODBC Statement handle.');
  713. FSTMTHandle:=SQL_NULL_HSTMT;
  714. FPrepared := False;
  715. end;
  716. end;
  717. end;
  718. function TODBCConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  719. begin
  720. Result := nil;
  721. end;
  722. function TODBCConnection.StartDBTransaction(trans: TSQLHandle; AParams:string): boolean;
  723. var AutoCommit: SQLINTEGER;
  724. begin
  725. // set some connection attributes
  726. if StrToBoolDef(Params.Values['AUTOCOMMIT'], False) then
  727. AutoCommit := SQL_AUTOCOMMIT_ON
  728. else
  729. AutoCommit := SQL_AUTOCOMMIT_OFF;
  730. ODBCCheckResult(
  731. SQLSetConnectAttr(FDBCHandle, SQL_ATTR_AUTOCOMMIT, SQLPOINTER(AutoCommit), SQL_IS_UINTEGER),
  732. SQL_HANDLE_DBC,FDBCHandle,'Could not start transaction!'
  733. );
  734. Result := AutoCommit=SQL_AUTOCOMMIT_OFF;
  735. end;
  736. function TODBCConnection.Commit(trans: TSQLHandle): boolean;
  737. begin
  738. ODBCCheckResult(
  739. SQLEndTran(SQL_HANDLE_DBC, FDBCHandle, SQL_COMMIT),
  740. SQL_HANDLE_DBC, FDBCHandle, 'Could not commit!'
  741. );
  742. Result := True;
  743. end;
  744. function TODBCConnection.Rollback(trans: TSQLHandle): boolean;
  745. begin
  746. ODBCCheckResult(
  747. SQLEndTran(SQL_HANDLE_DBC, FDBCHandle, SQL_ROLLBACK),
  748. SQL_HANDLE_DBC, FDBCHandle, 'Could not rollback!'
  749. );
  750. Result := True;
  751. end;
  752. procedure TODBCConnection.CommitRetaining(trans: TSQLHandle);
  753. begin
  754. Commit(trans);
  755. end;
  756. procedure TODBCConnection.RollbackRetaining(trans: TSQLHandle);
  757. begin
  758. Rollback(trans);
  759. end;
  760. procedure TODBCConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  761. const
  762. TABLE_TYPE_USER='TABLE,VIEW,GLOBAL TEMPORARY,LOCAL TEMPORARY'; //no spaces before/after comma
  763. TABLE_TYPE_SYSTEM='SYSTEM TABLE';
  764. var
  765. ODBCCursor:TODBCCursor;
  766. Res:SQLRETURN;
  767. ColumnCount:SQLSMALLINT;
  768. begin
  769. ODBCCursor:=cursor as TODBCCursor;
  770. try
  771. // set parameters
  772. if Assigned(APArams) and (AParams.count > 0) then SetParameters(ODBCCursor, AParams);
  773. // execute the statement
  774. case ODBCCursor.FSchemaType of
  775. stTables : Res:=SQLTables (ODBCCursor.FSTMTHandle, nil, 0, nil, 0, nil, 0, TABLE_TYPE_USER, length(TABLE_TYPE_USER) );
  776. stSysTables : Res:=SQLTables (ODBCCursor.FSTMTHandle, nil, 0, nil, 0, nil, 0, TABLE_TYPE_SYSTEM, length(TABLE_TYPE_SYSTEM) );
  777. stColumns : Res:=SQLColumns(ODBCCursor.FSTMTHandle, nil, 0, nil, 0, @ODBCCursor.FQuery[1], length(ODBCCursor.FQuery), nil, 0 );
  778. stProcedures: Res:=SQLProcedures(ODBCCursor.FSTMTHandle, nil, 0, nil, 0, nil, 0 );
  779. stIndexes : Res:=SQLStatistics(ODBCCursor.FSTMTHandle, nil, 0, nil, 0, @ODBCCursor.FQuery[1], length(ODBCCursor.FQuery), SQL_INDEX_ALL, SQL_QUICK);
  780. else Res:=SQLExecute(ODBCCursor.FSTMTHandle); //SQL_NO_DATA returns searched update or delete statement that does not affect any rows
  781. end; {case}
  782. if (Res<>SQL_NO_DATA) then ODBCCheckResult( Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not execute statement.' );
  783. if ODBCSuccess(SQLNumResultCols(ODBCCursor.FSTMTHandle, ColumnCount)) then
  784. ODBCCursor.FSelectable:=ColumnCount>0
  785. else
  786. ODBCCursor.FSelectable:=False;
  787. finally
  788. // free parameter buffers
  789. FreeParamBuffers(ODBCCursor);
  790. end;
  791. end;
  792. function TODBCConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  793. var
  794. RowCount: SQLLEN;
  795. begin
  796. if assigned(cursor) then
  797. if ODBCSuccess( SQLRowCount((cursor as TODBCCursor).FSTMTHandle, RowCount) ) then
  798. Result:=RowCount
  799. else
  800. Result:=-1
  801. else
  802. Result:=-1;
  803. end;
  804. function TODBCConnection.RefreshLastInsertID(Query : TCustomSQLQuery; Field : TField): boolean;
  805. var
  806. STMTHandle: SQLHSTMT;
  807. StrLenOrInd: SQLLEN;
  808. LastInsertID: LargeInt;
  809. begin
  810. Result := false;
  811. if SQLAllocHandle(SQL_HANDLE_STMT, FDBCHandle, STMTHandle) = SQL_SUCCESS then
  812. begin
  813. if SQLExecDirect(STMTHandle, PChar(FDBMSInfo.GetLastInsertIDSQL), Length(FDBMSInfo.GetLastInsertIDSQL)) = SQL_SUCCESS then
  814. if SQLFetch(STMTHandle) = SQL_SUCCESS then
  815. if SQLGetData(STMTHandle, 1, SQL_C_SBIGINT, @LastInsertID, SizeOf(LargeInt), @StrLenOrInd) = SQL_SUCCESS then
  816. Field.AsLargeInt := LastInsertID;
  817. SQLFreeHandle(SQL_HANDLE_STMT, STMTHandle);
  818. end;
  819. end;
  820. procedure TODBCConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TFieldDefs);
  821. const
  822. ColNameDefaultLength = 40; // should be > 0, because an ansistring of length 0 is a nil pointer instead of a pointer to a #0
  823. TypeNameDefaultLength = 80; // idem
  824. BLOB_BUF_SIZE = 0;
  825. var
  826. ODBCCursor:TODBCCursor;
  827. ColumnCount:SQLSMALLINT;
  828. i:integer;
  829. ColNameLength,TypeNameLength,DataType,DecimalDigits,Nullable:SQLSMALLINT;
  830. ColumnSize:SQLULEN;
  831. ColName,TypeName:string;
  832. FieldType:TFieldType;
  833. FieldSize:word;
  834. AutoIncAttr, FixedPrecScale, Unsigned, Updatable: SQLLEN;
  835. begin
  836. ODBCCursor:=cursor as TODBCCursor;
  837. // get number of columns in result set
  838. ODBCCheckResult(
  839. SQLNumResultCols(ODBCCursor.FSTMTHandle, ColumnCount),
  840. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not determine number of columns in result set.'
  841. );
  842. AutoIncAttr:=SQL_FALSE;
  843. for i:=1 to ColumnCount do
  844. begin
  845. SetLength(ColName,ColNameDefaultLength); // also garantuees uniqueness
  846. // call with default column name buffer
  847. ODBCCheckResult(
  848. SQLDescribeCol(ODBCCursor.FSTMTHandle, // statement handle
  849. i, // column number, is 1-based (Note: column 0 is the bookmark column in ODBC)
  850. @(ColName[1]), // default buffer
  851. ColNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  852. ColNameLength, // actual column name length
  853. DataType, // the SQL datatype for the column
  854. ColumnSize, // column size (in characters)
  855. DecimalDigits, // number of decimal digits
  856. Nullable), // SQL_NO_NULLS, SQL_NULLABLE or SQL_NULLABLE_UNKNOWN
  857. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get column properties for column %d.',[i]
  858. );
  859. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  860. SetLength(ColName,ColNameLength);
  861. // check whether entire column name was returned
  862. if ColNameLength>ColNameDefaultLength then
  863. begin
  864. // request column name with buffer that is long enough
  865. ODBCCheckResult(
  866. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  867. i, // column number
  868. SQL_DESC_NAME, // the column name or alias
  869. @(ColName[1]), // buffer
  870. ColNameLength+1, // buffer size
  871. @ColNameLength, // actual length
  872. nil), // no numerical output
  873. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get column name for column %d.',[i]
  874. );
  875. end;
  876. // convert type
  877. // NOTE: I made some guesses here after I found only limited information about TFieldType; please report any problems
  878. case DataType of
  879. SQL_CHAR: begin FieldType:=ftFixedChar; FieldSize:=ColumnSize; end;
  880. SQL_VARCHAR: begin FieldType:=ftString; FieldSize:=ColumnSize; end;
  881. SQL_LONGVARCHAR: begin FieldType:=ftMemo; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  882. SQL_WCHAR: begin FieldType:=ftFixedWideChar; FieldSize:=ColumnSize; end;
  883. SQL_WVARCHAR: begin FieldType:=ftWideString; FieldSize:=ColumnSize; end;
  884. SQL_SS_XML,
  885. SQL_WLONGVARCHAR: begin FieldType:=ftWideMemo; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  886. SQL_DECIMAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  887. SQL_NUMERIC: begin FieldType:=ftFloat; FieldSize:=0; end;
  888. SQL_SMALLINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  889. SQL_INTEGER: begin FieldType:=ftInteger; FieldSize:=0; end;
  890. SQL_REAL: begin FieldType:=ftFloat; FieldSize:=0; end;
  891. SQL_FLOAT: begin FieldType:=ftFloat; FieldSize:=0; end;
  892. SQL_DOUBLE: begin FieldType:=ftFloat; FieldSize:=0; end;
  893. SQL_BIT: begin FieldType:=ftBoolean; FieldSize:=0; end;
  894. SQL_TINYINT: begin FieldType:=ftSmallint; FieldSize:=0; end;
  895. SQL_BIGINT: begin FieldType:=ftLargeint; FieldSize:=0; end;
  896. SQL_BINARY: begin FieldType:=ftBytes; FieldSize:=ColumnSize; end;
  897. SQL_VARBINARY: begin FieldType:=ftVarBytes; FieldSize:=ColumnSize; end;
  898. SQL_LONGVARBINARY: begin FieldType:=ftBlob; FieldSize:=BLOB_BUF_SIZE; end; // is a blob
  899. SQL_TYPE_DATE: begin FieldType:=ftDate; FieldSize:=0; end;
  900. SQL_SS_TIME2,
  901. SQL_TYPE_TIME: begin FieldType:=ftTime; FieldSize:=0; end;
  902. SQL_TYPE_TIMESTAMP:begin FieldType:=ftDateTime; FieldSize:=0; end;
  903. { SQL_TYPE_UTCDATETIME:FieldType:=ftUnknown;}
  904. { SQL_TYPE_UTCTIME: FieldType:=ftUnknown;}
  905. { SQL_INTERVAL_MONTH: FieldType:=ftUnknown;}
  906. { SQL_INTERVAL_YEAR: FieldType:=ftUnknown;}
  907. { SQL_INTERVAL_YEAR_TO_MONTH: FieldType:=ftUnknown;}
  908. { SQL_INTERVAL_DAY: FieldType:=ftUnknown;}
  909. { SQL_INTERVAL_HOUR: FieldType:=ftUnknown;}
  910. { SQL_INTERVAL_MINUTE: FieldType:=ftUnknown;}
  911. { SQL_INTERVAL_SECOND: FieldType:=ftUnknown;}
  912. { SQL_INTERVAL_DAY_TO_HOUR: FieldType:=ftUnknown;}
  913. { SQL_INTERVAL_DAY_TO_MINUTE: FieldType:=ftUnknown;}
  914. { SQL_INTERVAL_DAY_TO_SECOND: FieldType:=ftUnknown;}
  915. { SQL_INTERVAL_HOUR_TO_MINUTE: FieldType:=ftUnknown;}
  916. { SQL_INTERVAL_HOUR_TO_SECOND: FieldType:=ftUnknown;}
  917. { SQL_INTERVAL_MINUTE_TO_SECOND:FieldType:=ftUnknown;}
  918. SQL_GUID: begin FieldType:=ftGuid; FieldSize:=38; end; //SQL_GUID defines 36, but TGuidField requires 38
  919. SQL_SS_VARIANT: begin FieldType:=ftVariant; FieldSize:=0; end;
  920. else
  921. begin FieldType:=ftUnknown; FieldSize:=ColumnSize; end
  922. end;
  923. if (FieldType in [ftString,ftFixedChar]) and // field types mapped to TStringField
  924. (FieldSize > MaxSmallint) then
  925. begin
  926. FieldSize := MaxSmallint;
  927. end
  928. else
  929. // any exact numeric type with scale 0 can have identity attr.
  930. // only one column per table can have identity attr.
  931. if (FieldType in [ftInteger,ftLargeInt]) and (AutoIncAttr=SQL_FALSE) then
  932. begin
  933. ODBCCheckResult(
  934. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  935. i, // column number
  936. SQL_DESC_AUTO_UNIQUE_VALUE, // FieldIdentifier
  937. nil, // buffer
  938. 0, // buffer size
  939. nil, // actual length
  940. @AutoIncAttr), // NumericAttribute
  941. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get autoincrement attribute for column %d.',[i]
  942. );
  943. if (AutoIncAttr=SQL_TRUE) and (FieldType=ftInteger) then
  944. FieldType:=ftAutoInc;
  945. end
  946. else
  947. if FieldType in [ftFloat] then
  948. begin
  949. FixedPrecScale:=0;
  950. ODBCCheckResult(
  951. SQLColAttribute(ODBCCursor.FSTMTHandle,
  952. i,
  953. SQL_DESC_FIXED_PREC_SCALE,
  954. nil,
  955. 0,
  956. nil,
  957. @FixedPrecScale),
  958. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get money attribute for column %d.',[i]
  959. );
  960. if FixedPrecScale=SQL_TRUE then
  961. FieldType:=ftCurrency;
  962. end;
  963. if FieldType in [ftSmallint] then
  964. begin
  965. Unsigned:=0;
  966. ODBCCheckResult(
  967. SQLColAttribute(ODBCCursor.FSTMTHandle,
  968. i,
  969. SQL_DESC_UNSIGNED,
  970. nil,
  971. 0,
  972. nil,
  973. @Unsigned),
  974. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get unsigned attribute for column %d.',[i]
  975. );
  976. if Unsigned=SQL_TRUE then
  977. case FieldType of
  978. ftSmallint: FieldType:=ftWord;
  979. end;
  980. end;
  981. Updatable:=0;
  982. ODBCCheckResult(
  983. SQLColAttribute(ODBCCursor.FSTMTHandle,
  984. i,
  985. SQL_DESC_UPDATABLE,
  986. nil,
  987. 0,
  988. nil,
  989. @Updatable),
  990. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get updatable attribute for column %d.',[i]
  991. );
  992. if FieldType=ftUnknown then // if unknown field type encountered, try finding more specific information about the ODBC SQL DataType
  993. begin
  994. SetLength(TypeName,TypeNameDefaultLength); // also garantuees uniqueness
  995. ODBCCheckResult(
  996. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  997. i, // column number
  998. SQL_DESC_TYPE_NAME, // FieldIdentifier indicating the datasource dependent data type name (useful for diagnostics)
  999. @(TypeName[1]), // default buffer
  1000. TypeNameDefaultLength+1, // and its length; we include the #0 terminating any ansistring of Length > 0 in the buffer
  1001. @TypeNameLength, // actual type name length
  1002. nil // no need for a pointer to return a numeric attribute at
  1003. ),
  1004. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get datasource dependent type name for column %s.',[ColName]
  1005. );
  1006. // truncate buffer or make buffer long enough for entire column name (note: the call is the same for both cases!)
  1007. SetLength(TypeName,TypeNameLength);
  1008. // check whether entire column name was returned
  1009. if TypeNameLength>TypeNameDefaultLength then
  1010. begin
  1011. // request column name with buffer that is long enough
  1012. ODBCCheckResult(
  1013. SQLColAttribute(ODBCCursor.FSTMTHandle, // statement handle
  1014. i, // column number
  1015. SQL_DESC_TYPE_NAME, // FieldIdentifier indicating the datasource dependent data type name (useful for diagnostics)
  1016. @(TypeName[1]), // buffer
  1017. TypeNameLength+1, // buffer size
  1018. @TypeNameLength, // actual length
  1019. nil), // no need for a pointer to return a numeric attribute at
  1020. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get datasource dependent type name for column %s.',[ColName]
  1021. );
  1022. end;
  1023. DatabaseErrorFmt('Column %s has an unknown or unsupported column type. Datasource dependent type name: %s. ODBC SQL data type code: %d.', [ColName, TypeName, DataType]);
  1024. end;
  1025. // add FieldDef
  1026. AddFieldDef(FieldDefs, i, ColName, FieldType, FieldSize, -1, False, (Nullable=SQL_NO_NULLS) and (AutoIncAttr=SQL_FALSE), Updatable=SQL_ATTR_READONLY);
  1027. end;
  1028. end;
  1029. function TODBCConnection.Fetch(cursor: TSQLCursor): boolean;
  1030. var
  1031. ODBCCursor:TODBCCursor;
  1032. Res:SQLRETURN;
  1033. begin
  1034. ODBCCursor:=cursor as TODBCCursor;
  1035. // fetch new row
  1036. Res:=SQLFetch(ODBCCursor.FSTMTHandle);
  1037. if Res<>SQL_NO_DATA then
  1038. ODBCCheckResult(Res,SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not fetch new row from result set.');
  1039. // result is true if a new row was available
  1040. Result:=Res<>SQL_NO_DATA;
  1041. end;
  1042. const
  1043. DEFAULT_BLOB_BUFFER_SIZE = 1024;
  1044. function TODBCConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer; out CreateBlob : boolean): boolean;
  1045. const
  1046. SQL_CA_SS_VARIANT_TYPE = 1215;
  1047. var
  1048. ODBCCursor:TODBCCursor;
  1049. StrLenOrInd,VariantCType:SQLLEN;
  1050. ODBCDateStruct:SQL_DATE_STRUCT;
  1051. ODBCTimeStruct:SQL_TIME_STRUCT;
  1052. ODBCTimeStampStruct:SQL_TIMESTAMP_STRUCT;
  1053. DateTime:TDateTime;
  1054. Res:SQLRETURN;
  1055. begin
  1056. CreateBlob := False;
  1057. ODBCCursor:=cursor as TODBCCursor;
  1058. // load the field using SQLGetData
  1059. // Note: optionally we can implement the use of SQLBindCol later for even more speed
  1060. // TODO: finish this
  1061. case FieldDef.DataType of
  1062. ftWideString,ftFixedWideChar: // mapped to TWideStringField
  1063. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_WCHAR, buffer, FieldDef.Size*FieldDef.CharSize+sizeof(WideChar), @StrLenOrInd); //buffer must contain space for the null-termination character
  1064. ftGuid, ftFixedChar,ftString: // are mapped to a TStringField (including TGuidField)
  1065. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_CHAR, buffer, FieldDef.Size*FieldDef.CharSize+1, @StrLenOrInd);
  1066. ftSmallint: // mapped to TSmallintField
  1067. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SSHORT, buffer, SizeOf(Smallint), @StrLenOrInd);
  1068. ftInteger,ftAutoInc: // mapped to TLongintField
  1069. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SLONG, buffer, SizeOf(Longint), @StrLenOrInd);
  1070. ftWord: // mapped to TWordField
  1071. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_USHORT, buffer, SizeOf(Word), @StrLenOrInd);
  1072. ftLargeint: // mapped to TLargeintField
  1073. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_SBIGINT, buffer, SizeOf(Largeint), @StrLenOrInd);
  1074. ftFloat,ftCurrency: // mapped to TFloatField
  1075. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_DOUBLE, buffer, SizeOf(Double), @StrLenOrInd);
  1076. ftTime: // mapped to TTimeField
  1077. begin
  1078. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIME, @ODBCTimeStruct, SizeOf(SQL_TIME_STRUCT), @StrLenOrInd);
  1079. if StrLenOrInd<>SQL_NULL_DATA then
  1080. begin
  1081. DateTime:=TimeStructToDateTime(@ODBCTimeStruct);
  1082. Move(DateTime, buffer^, SizeOf(TDateTime));
  1083. end;
  1084. end;
  1085. ftDate: // mapped to TDateField
  1086. begin
  1087. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_DATE, @ODBCDateStruct, SizeOf(SQL_DATE_STRUCT), @StrLenOrInd);
  1088. if StrLenOrInd<>SQL_NULL_DATA then
  1089. begin
  1090. DateTime:=DateStructToDateTime(@ODBCDateStruct);
  1091. Move(DateTime, buffer^, SizeOf(TDateTime));
  1092. end;
  1093. end;
  1094. ftDateTime: // mapped to TDateTimeField
  1095. begin
  1096. // Seems like not all ODBC-drivers (mysql on Linux) set the fractional part. Initialize
  1097. // it's value to avoid 'random' data.
  1098. ODBCTimeStampStruct.Fraction:=0;
  1099. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_TYPE_TIMESTAMP, @ODBCTimeStampStruct, SizeOf(SQL_TIMESTAMP_STRUCT), @StrLenOrInd);
  1100. if StrLenOrInd<>SQL_NULL_DATA then
  1101. begin
  1102. DateTime:=TimeStampStructToDateTime(@ODBCTimeStampStruct);
  1103. Move(DateTime, buffer^, SizeOf(TDateTime));
  1104. end;
  1105. end;
  1106. ftBoolean: // mapped to TBooleanField
  1107. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BIT, buffer, SizeOf(Wordbool), @StrLenOrInd);
  1108. ftBytes: // mapped to TBytesField
  1109. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, FieldDef.Size, @StrLenOrInd);
  1110. ftVarBytes: // mapped to TVarBytesField
  1111. begin
  1112. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer+SizeOf(Word), FieldDef.Size, @StrLenOrInd);
  1113. if StrLenOrInd < 0 then
  1114. PWord(buffer)^ := 0
  1115. else
  1116. PWord(buffer)^ := StrLenOrInd;
  1117. end;
  1118. ftVariant:
  1119. begin
  1120. // Try to read sql_variant header
  1121. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, 0, @StrLenOrInd);
  1122. if ODBCSuccess(Res) then
  1123. begin
  1124. Res := SQLColAttribute(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_CA_SS_VARIANT_TYPE, nil, 0, nil, @VariantCType);
  1125. // map only types, which holds values directly in TVarData record
  1126. case VariantCType of
  1127. SQL_C_SSHORT, SQL_C_USHORT, SQL_C_SLONG, SQL_C_ULONG, SQL_C_SBIGINT:
  1128. begin
  1129. VariantCType := SQL_C_SBIGINT;
  1130. PVarData(buffer)^.vtype := varInt64;
  1131. buffer := @PVarData(buffer)^.vint64;
  1132. end;
  1133. SQL_C_FLOAT, SQL_C_DOUBLE:
  1134. begin
  1135. VariantCType := SQL_C_DOUBLE;
  1136. PVarData(buffer)^.vtype := varDouble;
  1137. buffer := @PVarData(buffer)^.vdouble;
  1138. end
  1139. else
  1140. StrLenOrInd := SQL_NULL_DATA;
  1141. end;
  1142. if StrLenOrInd<>SQL_NULL_DATA then
  1143. Res := SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, VariantCType, buffer, 8, @StrLenOrInd);
  1144. end;
  1145. end;
  1146. ftWideMemo,
  1147. ftBlob, ftMemo: // BLOBs
  1148. begin
  1149. //Writeln('BLOB');
  1150. // Try to discover BLOB data length
  1151. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, buffer, 0, @StrLenOrInd);
  1152. // Read the data if not NULL
  1153. if ODBCSuccess(Res) and (StrLenOrInd<>SQL_NULL_DATA) then
  1154. begin
  1155. CreateBlob:=true; // defer actual loading of blob data to LoadBlobIntoBuffer method
  1156. //WriteLn('Deferring loading of blob of length ',StrLenOrInd);
  1157. end;
  1158. end;
  1159. // TODO: Loading of other field types
  1160. else
  1161. raise EODBCException.CreateFmt('Tried to load field of unsupported field type %s',[Fieldtypenames[FieldDef.DataType]]);
  1162. end;
  1163. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  1164. Result:=StrLenOrInd<>SQL_NULL_DATA; // Result indicates whether the value is non-null
  1165. //writeln(Format('Field.Size: %d; StrLenOrInd: %d',[FieldDef.Size, StrLenOrInd]));
  1166. end;
  1167. procedure TODBCConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef; ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  1168. var
  1169. ODBCCursor: TODBCCursor;
  1170. Res: SQLRETURN;
  1171. StrLenOrInd:SQLLEN;
  1172. BlobBuffer:pointer;
  1173. BlobBufferSize,BytesRead:SQLINTEGER;
  1174. BlobMemoryStream:TMemoryStream;
  1175. begin
  1176. ODBCCursor:=cursor as TODBCCursor;
  1177. // Try to discover BLOB data length
  1178. // NB MS ODBC requires that TargetValuePtr is not nil, so we supply it with a valid pointer, even though BufferLength is 0
  1179. StrLenOrInd:=0;
  1180. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, @BlobBuffer, 0, @StrLenOrInd);
  1181. if Res<>SQL_NO_DATA then
  1182. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not get field data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  1183. // Read the data if not NULL
  1184. if StrLenOrInd<>SQL_NULL_DATA then
  1185. begin
  1186. // Determine size of buffer to use
  1187. if StrLenOrInd<>SQL_NO_TOTAL then begin
  1188. // Size is known on beforehand
  1189. // set size & alloc buffer
  1190. //WriteLn('Loading blob of length ',StrLenOrInd);
  1191. BlobBufferSize:=StrLenOrInd;
  1192. ABlobBuf^.BlobBuffer^.Size:=BlobBufferSize;
  1193. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize);
  1194. // get blob data
  1195. if BlobBufferSize>0 then begin
  1196. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize, @StrLenOrInd);
  1197. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not load blob data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  1198. end;
  1199. end else begin
  1200. // Size is not known on beforehand; read data in chuncks; write to a TMemoryStream (which implements O(n) writing)
  1201. BlobBufferSize:=DEFAULT_BLOB_BUFFER_SIZE;
  1202. // init BlobBuffer and BlobMemoryStream to nil pointers
  1203. BlobBuffer:=nil; // the buffer that will hold the chuncks of data; not to be confused with ABlobBuf^.BlobBuffer
  1204. BlobMemoryStream:=nil;
  1205. try
  1206. // Allocate the buffer and memorystream
  1207. BlobBuffer:=GetMem(BlobBufferSize);
  1208. BlobMemoryStream:=TMemoryStream.Create;
  1209. // Retrieve data in parts
  1210. repeat
  1211. Res:=SQLGetData(ODBCCursor.FSTMTHandle, FieldDef.Index+1, SQL_C_BINARY, BlobBuffer, BlobBufferSize, @StrLenOrInd);
  1212. ODBCCheckResult(Res, SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not load (partial) blob data for field "%s" (index %d).',[FieldDef.Name, FieldDef.Index+1]);
  1213. // Append data in buffer to memorystream
  1214. if (StrLenOrInd=SQL_NO_TOTAL) or (StrLenOrInd>BlobBufferSize) then
  1215. BytesRead:=BlobBufferSize
  1216. else
  1217. BytesRead:=StrLenOrInd;
  1218. BlobMemoryStream.Write(BlobBuffer^, BytesRead);
  1219. until Res=SQL_SUCCESS;
  1220. // Copy memory stream data to ABlobBuf^.BlobBuffer
  1221. BlobBufferSize:=BlobMemoryStream.Size; // actual blob size
  1222. // alloc ABlobBuf^.BlobBuffer
  1223. ABlobBuf^.BlobBuffer^.Size:=BlobBufferSize;
  1224. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer, BlobBufferSize);
  1225. // read memory stream data into ABlobBuf^.BlobBuffer
  1226. BlobMemoryStream.Position:=0;
  1227. BlobMemoryStream.Read(ABlobBuf^.BlobBuffer^.Buffer^, BlobBufferSize);
  1228. finally
  1229. // free buffer and memory stream
  1230. BlobMemoryStream.Free;
  1231. if BlobBuffer<>nil then
  1232. Freemem(BlobBuffer,BlobBufferSize);
  1233. end;
  1234. end;
  1235. end;
  1236. end;
  1237. procedure TODBCConnection.FreeFldBuffers(cursor: TSQLCursor);
  1238. var
  1239. ODBCCursor:TODBCCursor;
  1240. begin
  1241. ODBCCursor:=cursor as TODBCCursor;
  1242. if ODBCCursor.FSTMTHandle <> SQL_NULL_HSTMT then
  1243. ODBCCheckResult(
  1244. SQLFreeStmt(ODBCCursor.FSTMTHandle, SQL_CLOSE),
  1245. SQL_HANDLE_STMT, ODBCCursor.FSTMTHandle, 'Could not close ODBC statement cursor.'
  1246. );
  1247. end;
  1248. procedure TODBCConnection.UpdateIndexDefs(IndexDefs: TIndexDefs; TableName: string);
  1249. var
  1250. Len: integer;
  1251. StmtHandle:SQLHSTMT;
  1252. Res:SQLRETURN;
  1253. IndexDef: TIndexDef;
  1254. KeyName: String;
  1255. // variables for binding
  1256. NonUnique :SQLSMALLINT; NonUniqueIndOrLen :SQLLEN;
  1257. IndexName :string; IndexNameIndOrLen :SQLLEN;
  1258. _Type :SQLSMALLINT; _TypeIndOrLen :SQLLEN;
  1259. OrdinalPos:SQLSMALLINT; OrdinalPosIndOrLen:SQLLEN;
  1260. ColName :string; ColNameIndOrLen :SQLLEN;
  1261. AscOrDesc :char; AscOrDescIndOrLen :SQLLEN;
  1262. PKName :string; PKNameIndOrLen :SQLLEN;
  1263. const
  1264. DEFAULT_NAME_LEN = 255;
  1265. begin
  1266. Len := length(TableName);
  1267. if Len > 2 then
  1268. if (TableName[1] in ['"','`']) and (TableName[Len] in ['"','`']) then
  1269. TableName := AnsiDequotedStr(TableName, TableName[1])
  1270. else if (TableName[1] in ['[']) and (TableName[Len] in [']']) then
  1271. TableName := copy(TableName, 2, Len-2);
  1272. // allocate statement handle
  1273. StmtHandle := SQL_NULL_HANDLE;
  1274. ODBCCheckResult(
  1275. SQLAllocHandle(SQL_HANDLE_STMT, FDBCHandle, StmtHandle),
  1276. SQL_HANDLE_DBC, FDBCHandle, 'Could not allocate ODBC Statement handle.'
  1277. );
  1278. try
  1279. // Disabled: only works if we can specify a SchemaName and, if supported by the data source, a CatalogName
  1280. // otherwise SQLPrimaryKeys returns error HY0009 (Invalid use of null pointer)
  1281. // set the SQL_ATTR_METADATA_ID so parameters to Catalog functions are considered as identifiers (e.g. case-insensitive)
  1282. //ODBCCheckResult(
  1283. // SQLSetStmtAttr(StmtHandle, SQL_ATTR_METADATA_ID, SQLPOINTER(SQL_TRUE), SQL_IS_UINTEGER),
  1284. // SQL_HANDLE_STMT, StmtHandle, 'Could not set SQL_ATTR_METADATA_ID statement attribute to SQL_TRUE.'
  1285. //);
  1286. // alloc result column buffers
  1287. SetLength(ColName, DEFAULT_NAME_LEN);
  1288. SetLength(PKName, DEFAULT_NAME_LEN);
  1289. SetLength(IndexName,DEFAULT_NAME_LEN);
  1290. // Fetch primary key info using SQLPrimaryKeys
  1291. ODBCCheckResult(
  1292. SQLPrimaryKeys(
  1293. StmtHandle,
  1294. nil, 0, // any catalog
  1295. nil, 0, // any schema
  1296. PChar(TableName), Length(TableName)
  1297. ),
  1298. SQL_HANDLE_STMT, StmtHandle, 'Could not retrieve primary key metadata for table %s using SQLPrimaryKeys.', [TableName]
  1299. );
  1300. // init key name & fields; we will set the IndexDefs.Option ixPrimary below when there is a match by IndexName=KeyName
  1301. KeyName:='';
  1302. try
  1303. // bind result columns; the column numbers are documented in the reference for SQLStatistics
  1304. ODBCCheckResult(SQLBindCol(StmtHandle, 4, SQL_C_CHAR , @ColName[1], Length(ColName)+1, @ColNameIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind primary key metadata column COLUMN_NAME.');
  1305. ODBCCheckResult(SQLBindCol(StmtHandle, 5, SQL_C_SSHORT, @OrdinalPos, 0, @OrdinalPosIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind primary key metadata column KEY_SEQ.');
  1306. ODBCCheckResult(SQLBindCol(StmtHandle, 6, SQL_C_CHAR , @PKName [1], Length(PKName )+1, @PKNameIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind primary key metadata column PK_NAME.');
  1307. // fetch result
  1308. repeat
  1309. // go to next row; loads data in bound columns
  1310. Res:=SQLFetch(StmtHandle);
  1311. // if no more row, break
  1312. if Res=SQL_NO_DATA then
  1313. Break;
  1314. // handle data
  1315. if ODBCSuccess(Res) then begin
  1316. if OrdinalPos=1 then begin
  1317. // create new IndexDef if OrdinalPos=1
  1318. IndexDef:=IndexDefs.AddIndexDef;
  1319. IndexDef.Name:=PChar(@PKName[1]);
  1320. IndexDef.Fields:=PChar(@ColName[1]);
  1321. IndexDef.Options:=IndexDef.Options+[ixUnique]+[ixPrimary]; // Primary key is always unique
  1322. KeyName:=IndexDef.Name;
  1323. end else begin
  1324. assert(Assigned(IndexDef));
  1325. IndexDef.Fields:=IndexDef.Fields+';'+PChar(@ColName[1]); // NB ; is the separator to be used for IndexDef.Fields
  1326. end;
  1327. end else begin
  1328. ODBCCheckResult(Res, SQL_HANDLE_STMT, StmtHandle, 'Could not fetch primary key metadata row.');
  1329. end;
  1330. until false;
  1331. finally
  1332. // unbind columns & close cursor
  1333. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_UNBIND), SQL_HANDLE_STMT, StmtHandle, 'Could not unbind columns.');
  1334. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_CLOSE), SQL_HANDLE_STMT, StmtHandle, 'Could not close cursor.');
  1335. end;
  1336. //WriteLn('KeyName: ',KeyName,'; KeyFields: ',KeyFields);
  1337. // use SQLStatistics to get index information
  1338. ODBCCheckResult(
  1339. SQLStatistics(
  1340. StmtHandle,
  1341. nil, 0, // catalog unknown; request for all catalogs
  1342. nil, 0, // schema unknown; request for all schemas
  1343. PChar(TableName), Length(TableName), // request information for TableName
  1344. SQL_INDEX_ALL,
  1345. SQL_QUICK
  1346. ),
  1347. SQL_HANDLE_STMT, StmtHandle, 'Could not retrieve index metadata for table %s using SQLStatistics.', [TableName]
  1348. );
  1349. try
  1350. // bind result columns; the column numbers are documented in the reference for SQLStatistics
  1351. ODBCCheckResult(SQLBindCol(StmtHandle, 4, SQL_C_SSHORT, @NonUnique , 0, @NonUniqueIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column NON_UNIQUE.');
  1352. ODBCCheckResult(SQLBindCol(StmtHandle, 6, SQL_C_CHAR , @IndexName[1], Length(IndexName)+1, @IndexNameIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column INDEX_NAME.');
  1353. ODBCCheckResult(SQLBindCol(StmtHandle, 7, SQL_C_SSHORT, @_Type , 0, @_TypeIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column TYPE.');
  1354. ODBCCheckResult(SQLBindCol(StmtHandle, 8, SQL_C_SSHORT, @OrdinalPos, 0, @OrdinalPosIndOrLen), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column ORDINAL_POSITION.');
  1355. ODBCCheckResult(SQLBindCol(StmtHandle, 9, SQL_C_CHAR , @ColName [1], Length(ColName )+1, @ColNameIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column COLUMN_NAME.');
  1356. ODBCCheckResult(SQLBindCol(StmtHandle, 10, SQL_C_CHAR , @AscOrDesc , 1, @AscOrDescIndOrLen ), SQL_HANDLE_STMT, StmtHandle, 'Could not bind index metadata column ASC_OR_DESC.');
  1357. // clear index defs
  1358. IndexDef:=nil;
  1359. // fetch result
  1360. repeat
  1361. // go to next row; loads data in bound columns
  1362. Res:=SQLFetch(StmtHandle);
  1363. // if no more row, break
  1364. if Res=SQL_NO_DATA then
  1365. Break;
  1366. // handle data
  1367. if ODBCSuccess(Res) then begin
  1368. // note: SQLStatistics not only returns index info, but also statistics; we skip the latter
  1369. if _Type<>SQL_TABLE_STAT then begin
  1370. if PChar(@IndexName[1])=KeyName then begin
  1371. // The indexdef is already made as the primary key
  1372. // Only if the index is descending is not known yet.
  1373. if (AscOrDescIndOrLen<>SQL_NULL_DATA) and (AscOrDesc='D') then begin
  1374. IndexDef:=IndexDefs.Find(KeyName);
  1375. IndexDef.Options:=IndexDef.Options+[ixDescending];
  1376. end;
  1377. end else if (OrdinalPos=1) or not Assigned(IndexDef) then begin
  1378. // create new IndexDef if OrdinalPos=1 or not Assigned(IndexDef) (the latter should not occur though)
  1379. IndexDef:=IndexDefs.AddIndexDef;
  1380. IndexDef.Name:=PChar(@IndexName[1]); // treat ansistring as zero terminated string
  1381. IndexDef.Fields:=PChar(@ColName[1]);
  1382. if NonUnique=SQL_FALSE then
  1383. IndexDef.Options:=IndexDef.Options+[ixUnique];
  1384. if (AscOrDescIndOrLen<>SQL_NULL_DATA) and (AscOrDesc='D') then
  1385. IndexDef.Options:=IndexDef.Options+[ixDescending];
  1386. // TODO: figure out how we can tell whether COLUMN_NAME is an expression or not
  1387. // if it is an expression, we should include ixExpression in Options and set Expression to ColName
  1388. end else // NB we re-use the last IndexDef
  1389. IndexDef.Fields:=IndexDef.Fields+';'+PChar(@ColName[1]); // NB ; is the separator to be used for IndexDef.Fields
  1390. end;
  1391. end else begin
  1392. ODBCCheckResult(Res, SQL_HANDLE_STMT, StmtHandle, 'Could not fetch index metadata row.');
  1393. end;
  1394. until false;
  1395. finally
  1396. // unbind columns & close cursor
  1397. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_UNBIND), SQL_HANDLE_STMT, StmtHandle, 'Could not unbind columns.');
  1398. ODBCCheckResult(SQLFreeStmt(StmtHandle, SQL_CLOSE), SQL_HANDLE_STMT, StmtHandle, 'Could not close cursor.');
  1399. end;
  1400. finally
  1401. if StmtHandle<>SQL_NULL_HANDLE then begin
  1402. // Free the statement handle
  1403. Res:=SQLFreeHandle(SQL_HANDLE_STMT, StmtHandle);
  1404. if Res=SQL_ERROR then
  1405. ODBCCheckResult(Res, SQL_HANDLE_STMT, STMTHandle, 'Could not free ODBC Statement handle.');
  1406. end;
  1407. end;
  1408. end;
  1409. function TODBCConnection.GetSchemaInfoSQL(SchemaType: TSchemaType; SchemaObjectName, SchemaObjectPattern: string): string;
  1410. begin
  1411. if SchemaType in [stTables, stSysTables, stColumns, stProcedures, stIndexes] then
  1412. begin
  1413. if SchemaObjectName<>'' then
  1414. Result := SchemaObjectName
  1415. else
  1416. Result := ' ';
  1417. end
  1418. else
  1419. Result := inherited;
  1420. end;
  1421. function TODBCConnection.GetConnectionInfo(InfoType: TConnInfoType): string;
  1422. var i,l: SQLSMALLINT;
  1423. b: array[0..41] of AnsiChar;
  1424. begin
  1425. case InfoType of
  1426. citServerType:
  1427. i:=SQL_DBMS_NAME;
  1428. citServerVersion,
  1429. citServerVersionString:
  1430. i:=SQL_DBMS_VER;
  1431. citClientName:
  1432. i:=SQL_DRIVER_NAME;
  1433. citClientVersion:
  1434. i:=SQL_DRIVER_VER;
  1435. else
  1436. Result:=inherited GetConnectionInfo(InfoType);
  1437. Exit;
  1438. end;
  1439. if Connected and (SQLGetInfo(FDBCHandle, i, @b, sizeof(b), @l) = SQL_SUCCESS) then
  1440. SetString(Result, @b, l)
  1441. else
  1442. Result:='';
  1443. end;
  1444. { TODBCEnvironment }
  1445. constructor TODBCEnvironment.Create;
  1446. begin
  1447. // make sure odbc is loaded
  1448. if ODBCLoadCount=0 then InitialiseOdbc;
  1449. Inc(ODBCLoadCount);
  1450. // allocate environment handle
  1451. if SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, FENVHandle)=SQL_Error then
  1452. 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
  1453. // set odbc version
  1454. ODBCCheckResult(
  1455. SQLSetEnvAttr(FENVHandle, SQL_ATTR_ODBC_VERSION, SQLPOINTER(SQL_OV_ODBC3), 0),
  1456. SQL_HANDLE_ENV, FENVHandle,'Could not set ODBC version to 3.'
  1457. );
  1458. end;
  1459. destructor TODBCEnvironment.Destroy;
  1460. var
  1461. Res:SQLRETURN;
  1462. begin
  1463. // free environment handle
  1464. if assigned(FENVHandle) then
  1465. begin
  1466. Res:=SQLFreeHandle(SQL_HANDLE_ENV, FENVHandle);
  1467. if Res=SQL_ERROR then
  1468. ODBCCheckResult(Res,SQL_HANDLE_ENV, FENVHandle, 'Could not free ODBC Environment handle.');
  1469. end;
  1470. // free odbc if not used by any TODBCEnvironment object anymore
  1471. if ODBCLoadCount>0 then
  1472. begin
  1473. Dec(ODBCLoadCount);
  1474. if ODBCLoadCount=0 then ReleaseOdbc;
  1475. end;
  1476. end;
  1477. { TODBCCursor }
  1478. constructor TODBCCursor.Create(Connection:TODBCConnection);
  1479. begin
  1480. end;
  1481. destructor TODBCCursor.Destroy;
  1482. begin
  1483. inherited Destroy;
  1484. end;
  1485. class function TODBCConnectionDef.TypeName: String;
  1486. begin
  1487. Result:='ODBC';
  1488. end;
  1489. class function TODBCConnectionDef.ConnectionClass: TSQLConnectionClass;
  1490. begin
  1491. Result:=TODBCConnection;
  1492. end;
  1493. class function TODBCConnectionDef.Description: String;
  1494. begin
  1495. Result:='Connect to any database via an ODBC driver';
  1496. end;
  1497. initialization
  1498. RegisterConnection(TODBCConnectionDef);
  1499. finalization
  1500. UnRegisterConnection(TODBCConnectionDef);
  1501. if Assigned(DefaultEnvironment) then
  1502. DefaultEnvironment.Free;
  1503. end.