odbcconn.pas 66 KB

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