odbcconn.pas 60 KB

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