odbcconn.pas 64 KB

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