odbcconn.pas 56 KB

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