odbcconn.pas 63 KB

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