odbcconn.pas 63 KB

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