odbcconn.pas 62 KB

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