OdbcDataReader.cs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. //
  2. // System.Data.Odbc.OdbcDataReader
  3. //
  4. // Author:
  5. // Brian Ritchie ([email protected])
  6. // Daniel Morgan <[email protected]>
  7. // Sureshkumar T <[email protected]> (2004)
  8. //
  9. // Copyright (C) Brian Ritchie, 2002
  10. // Copyright (C) Daniel Morgan, 2002
  11. //
  12. //
  13. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  14. //
  15. // Permission is hereby granted, free of charge, to any person obtaining
  16. // a copy of this software and associated documentation files (the
  17. // "Software"), to deal in the Software without restriction, including
  18. // without limitation the rights to use, copy, modify, merge, publish,
  19. // distribute, sublicense, and/or sell copies of the Software, and to
  20. // permit persons to whom the Software is furnished to do so, subject to
  21. // the following conditions:
  22. //
  23. // The above copyright notice and this permission notice shall be
  24. // included in all copies or substantial portions of the Software.
  25. //
  26. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  27. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  29. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  30. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  31. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  32. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  33. //
  34. using System.Collections;
  35. using System.ComponentModel;
  36. using System.Data;
  37. using System.Data.Common;
  38. #if NET_2_0
  39. using System.Data.ProviderBase;
  40. #endif // NET_2_0
  41. using System.Text;
  42. namespace System.Data.Odbc
  43. {
  44. #if NET_2_0
  45. public sealed class OdbcDataReader : DbDataReaderBase
  46. #else
  47. public sealed class OdbcDataReader : MarshalByRefObject, IDataReader, IDisposable, IDataRecord, IEnumerable
  48. #endif
  49. {
  50. #region Fields
  51. private OdbcCommand command;
  52. private bool open;
  53. private int currentRow;
  54. private OdbcColumn[] cols;
  55. private IntPtr hstmt;
  56. private int _recordsAffected = -1;
  57. bool disposed = false;
  58. private DataTable _dataTableSchema;
  59. #if ONLY_1_1
  60. private CommandBehavior behavior;
  61. #endif // ONLY_1_1
  62. #endregion
  63. #region Constructors
  64. internal OdbcDataReader (OdbcCommand command, CommandBehavior behavior)
  65. #if NET_2_0
  66. : base (behavior)
  67. #endif // NET_2_0
  68. {
  69. this.command = command;
  70. #if ONLY_1_1
  71. this.CommandBehavior=behavior;
  72. #endif // ONLY_1_1
  73. open = true;
  74. currentRow = -1;
  75. hstmt=command.hStmt;
  76. // Init columns array;
  77. short colcount=0;
  78. libodbc.SQLNumResultCols(hstmt, ref colcount);
  79. cols=new OdbcColumn[colcount];
  80. GetSchemaTable ();
  81. }
  82. internal OdbcDataReader (OdbcCommand command, CommandBehavior behavior,
  83. int recordAffected) : this (command, behavior)
  84. {
  85. _recordsAffected = recordAffected;
  86. }
  87. #endregion
  88. #region Properties
  89. #if ONLY_1_1
  90. private CommandBehavior CommandBehavior
  91. {
  92. get { return behavior; }
  93. set { value = behavior; }
  94. }
  95. #endif // ONLY_1_1
  96. #if NET_2_0
  97. [MonoTODO]
  98. public override int VisibleFieldCount
  99. {
  100. get { throw new NotImplementedException (); }
  101. }
  102. [MonoTODO]
  103. protected override bool IsValidRow
  104. {
  105. get { throw new NotImplementedException (); }
  106. }
  107. #endif // NET_2_0
  108. public
  109. #if NET_2_0
  110. override
  111. #endif // NET_2_0
  112. int Depth {
  113. get {
  114. return 0; // no nested selects supported
  115. }
  116. }
  117. public
  118. #if NET_2_0
  119. override
  120. #endif // NET_2_0
  121. int FieldCount {
  122. get {
  123. return cols.Length;
  124. }
  125. }
  126. public
  127. #if NET_2_0
  128. override
  129. #endif // NET_2_0
  130. bool IsClosed {
  131. get {
  132. return !open;
  133. }
  134. }
  135. public
  136. #if NET_2_0
  137. override
  138. #endif // NET_2_0
  139. object this[string name] {
  140. get {
  141. int pos;
  142. if (currentRow == -1)
  143. throw new InvalidOperationException ();
  144. pos = ColIndex(name);
  145. if (pos == -1)
  146. throw new IndexOutOfRangeException ();
  147. return this[pos];
  148. }
  149. }
  150. public
  151. #if NET_2_0
  152. override
  153. #endif // NET_2_0
  154. object this[int index] {
  155. get {
  156. return (object) GetValue (index);
  157. }
  158. }
  159. [MonoTODO]
  160. public
  161. #if NET_2_0
  162. override
  163. #endif // NET_2_0
  164. int RecordsAffected {
  165. get {
  166. return _recordsAffected;
  167. }
  168. }
  169. [MonoTODO]
  170. public
  171. #if NET_2_0
  172. override
  173. #endif // NET_2_0
  174. bool HasRows {
  175. get { throw new NotImplementedException(); }
  176. }
  177. #endregion
  178. #region Methods
  179. private int ColIndex(string colname)
  180. {
  181. int i=0;
  182. foreach (OdbcColumn col in cols)
  183. {
  184. if (col != null) {
  185. if (col.ColumnName == colname)
  186. return i;
  187. if (String.Compare (col.ColumnName, colname, true) == 0)
  188. return i;
  189. }
  190. i++;
  191. }
  192. return -1;
  193. }
  194. // Dynamically load column descriptions as needed.
  195. private OdbcColumn GetColumn(int ordinal)
  196. {
  197. if (cols[ordinal]==null)
  198. {
  199. short bufsize=255;
  200. byte[] colname_buffer=new byte[bufsize];
  201. string colname;
  202. short colname_size=0;
  203. uint ColSize=0;
  204. short DecDigits=0, Nullable=0, dt=0;
  205. OdbcReturn ret=libodbc.SQLDescribeCol(hstmt, Convert.ToUInt16(ordinal+1),
  206. colname_buffer, bufsize, ref colname_size, ref dt, ref ColSize,
  207. ref DecDigits, ref Nullable);
  208. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  209. throw new OdbcException(new OdbcError("SQLDescribeCol",OdbcHandleType.Stmt,hstmt));
  210. colname=System.Text.Encoding.Default.GetString(colname_buffer);
  211. colname=colname.Replace((char) 0,' ').Trim();
  212. OdbcColumn c=new OdbcColumn(colname, (SQL_TYPE) dt);
  213. c.AllowDBNull=(Nullable!=0);
  214. c.Digits=DecDigits;
  215. if (c.IsStringType)
  216. c.MaxLength=(int)ColSize;
  217. cols[ordinal]=c;
  218. }
  219. return cols[ordinal];
  220. }
  221. public
  222. #if NET_2_0
  223. override
  224. #endif // NET_2_0
  225. void Close ()
  226. {
  227. // FIXME : have to implement output parameter binding
  228. open = false;
  229. currentRow = -1;
  230. this.command.FreeIfNotPrepared ();
  231. if ((this.CommandBehavior & CommandBehavior.CloseConnection)==CommandBehavior.CloseConnection) {
  232. this.command.Connection.Close();
  233. }
  234. }
  235. ~OdbcDataReader ()
  236. {
  237. this.Dispose (false);
  238. }
  239. public
  240. #if NET_2_0
  241. override
  242. #endif // NET_2_0
  243. bool GetBoolean (int ordinal)
  244. {
  245. return (bool) GetValue(ordinal);
  246. }
  247. public
  248. #if NET_2_0
  249. override
  250. #endif // NET_2_0
  251. byte GetByte (int ordinal)
  252. {
  253. return (byte) Convert.ToByte(GetValue(ordinal));
  254. }
  255. public
  256. #if NET_2_0
  257. override
  258. #endif // NET_2_0
  259. long GetBytes (int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
  260. {
  261. OdbcReturn ret = OdbcReturn.Error;
  262. bool copyBuffer = false;
  263. int returnVal = 0, outsize = 0;
  264. byte [] tbuff = new byte [length+1];
  265. length = buffer == null ? 0 : length;
  266. ret=libodbc.SQLGetData (hstmt, (ushort) (ordinal+1), SQL_C_TYPE.BINARY, tbuff, length,
  267. ref outsize);
  268. if (ret == OdbcReturn.NoData)
  269. return 0;
  270. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  271. throw new OdbcException (new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt));
  272. OdbcError odbcErr = null;
  273. if ( (ret == OdbcReturn.SuccessWithInfo))
  274. odbcErr = new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt);
  275. if (buffer == null)
  276. return outsize; //if buffer is null,return length of the field
  277. if (ret == OdbcReturn.SuccessWithInfo) {
  278. if (outsize == (int) OdbcLengthIndicator.NoTotal)
  279. copyBuffer = true;
  280. else if (outsize == (int) OdbcLengthIndicator.NullData) {
  281. copyBuffer = false;
  282. returnVal = -1;
  283. } else {
  284. string sqlstate = odbcErr.SQLState;
  285. //SQLState: String Data, Right truncated
  286. if (sqlstate != libodbc.SQLSTATE_RIGHT_TRUNC)
  287. throw new OdbcException ( odbcErr);
  288. copyBuffer = true;
  289. }
  290. } else {
  291. copyBuffer = outsize == -1 ? false : true;
  292. returnVal = outsize;
  293. }
  294. if (copyBuffer) {
  295. int i = 0;
  296. while (tbuff [i] != libodbc.C_NULL) {
  297. buffer [bufferIndex + i] = tbuff [i];
  298. i++;
  299. }
  300. returnVal = i;
  301. }
  302. return returnVal;
  303. }
  304. [MonoTODO]
  305. public
  306. #if NET_2_0
  307. override
  308. #endif // NET_2_0
  309. char GetChar (int ordinal)
  310. {
  311. throw new NotImplementedException ();
  312. }
  313. [MonoTODO]
  314. public
  315. #if NET_2_0
  316. override
  317. #endif // NET_2_0
  318. long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length)
  319. {
  320. throw new NotImplementedException ();
  321. }
  322. [MonoTODO]
  323. [EditorBrowsableAttribute (EditorBrowsableState.Never)]
  324. public
  325. #if NET_2_0
  326. new
  327. #endif // NET_2_0
  328. IDataReader GetData (int ordinal)
  329. {
  330. throw new NotImplementedException ();
  331. }
  332. public
  333. #if NET_2_0
  334. override
  335. #endif // NET_2_0
  336. string GetDataTypeName (int index)
  337. {
  338. return GetColumn(index).OdbcType.ToString();
  339. }
  340. public DateTime GetDate(int ordinal) {
  341. return GetDateTime(ordinal);
  342. }
  343. public
  344. #if NET_2_0
  345. override
  346. #endif // NET_2_0
  347. DateTime GetDateTime (int ordinal)
  348. {
  349. return (DateTime) GetValue(ordinal);
  350. }
  351. [MonoTODO]
  352. public
  353. #if NET_2_0
  354. override
  355. #endif // NET_2_0
  356. decimal GetDecimal (int ordinal)
  357. {
  358. throw new NotImplementedException ();
  359. }
  360. public
  361. #if NET_2_0
  362. override
  363. #endif // NET_2_0
  364. double GetDouble (int ordinal)
  365. {
  366. return (double) GetValue(ordinal);
  367. }
  368. public
  369. #if NET_2_0
  370. override
  371. #endif // NET_2_0
  372. Type GetFieldType (int index)
  373. {
  374. return GetColumn(index).DataType;
  375. }
  376. public
  377. #if NET_2_0
  378. override
  379. #endif // NET_2_0
  380. float GetFloat (int ordinal)
  381. {
  382. return (float) GetValue(ordinal);
  383. }
  384. [MonoTODO]
  385. public
  386. #if NET_2_0
  387. override
  388. #endif // NET_2_0
  389. Guid GetGuid (int ordinal)
  390. {
  391. throw new NotImplementedException ();
  392. }
  393. public
  394. #if NET_2_0
  395. override
  396. #endif // NET_2_0
  397. short GetInt16 (int ordinal)
  398. {
  399. return (short) GetValue(ordinal);
  400. }
  401. public
  402. #if NET_2_0
  403. override
  404. #endif // NET_2_0
  405. int GetInt32 (int ordinal)
  406. {
  407. return (int) GetValue(ordinal);
  408. }
  409. public
  410. #if NET_2_0
  411. override
  412. #endif // NET_2_0
  413. long GetInt64 (int ordinal)
  414. {
  415. return (long) GetValue(ordinal);
  416. }
  417. public
  418. #if NET_2_0
  419. override
  420. #endif // NET_2_0
  421. string GetName (int index)
  422. {
  423. return GetColumn(index).ColumnName;
  424. }
  425. public
  426. #if NET_2_0
  427. override
  428. #endif // NET_2_0
  429. int GetOrdinal (string name)
  430. {
  431. int i=ColIndex(name);
  432. if (i==-1)
  433. throw new IndexOutOfRangeException ();
  434. else
  435. return i;
  436. }
  437. [MonoTODO]
  438. public
  439. #if NET_2_0
  440. override
  441. #endif // NET_2_0
  442. DataTable GetSchemaTable()
  443. {
  444. // FIXME :
  445. // * Map OdbcType to System.Type and assign to DataType.
  446. // This will eliminate the need for IsStringType in
  447. // OdbcColumn.
  448. if (_dataTableSchema != null)
  449. return _dataTableSchema;
  450. DataTable dataTableSchema = null;
  451. // Only Results from SQL SELECT Queries
  452. // get a DataTable for schema of the result
  453. // otherwise, DataTable is null reference
  454. if(cols.Length > 0)
  455. {
  456. dataTableSchema = new DataTable ();
  457. dataTableSchema.Columns.Add ("ColumnName", typeof (string));
  458. dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
  459. dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
  460. dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
  461. dataTableSchema.Columns.Add ("NumericScale", typeof (int));
  462. dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
  463. dataTableSchema.Columns.Add ("IsKey", typeof (bool));
  464. DataColumn dc = dataTableSchema.Columns["IsKey"];
  465. dc.AllowDBNull = true; // IsKey can have a DBNull
  466. dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
  467. dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
  468. dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
  469. dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
  470. dataTableSchema.Columns.Add ("DataType", typeof(Type));
  471. dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
  472. dataTableSchema.Columns.Add ("ProviderType", typeof (int));
  473. dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
  474. dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
  475. dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
  476. dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
  477. dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
  478. dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
  479. dataTableSchema.Columns.Add ("IsLong", typeof (bool));
  480. dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
  481. DataRow schemaRow;
  482. for (int i = 0; i < cols.Length; i += 1 )
  483. {
  484. string baseTableName = String.Empty;
  485. bool isKey = false;
  486. OdbcColumn col=GetColumn(i);
  487. schemaRow = dataTableSchema.NewRow ();
  488. dataTableSchema.Rows.Add (schemaRow);
  489. schemaRow ["ColumnName"] = col.ColumnName;
  490. schemaRow ["ColumnOrdinal"] = i;
  491. schemaRow ["ColumnSize"] = col.MaxLength;
  492. schemaRow ["NumericPrecision"] = GetColumnAttribute (i+1, FieldIdentifier.Precision);
  493. schemaRow ["NumericScale"] = GetColumnAttribute (i+1, FieldIdentifier.Scale);
  494. schemaRow ["BaseTableName"] = GetColumnAttributeStr (i+1, FieldIdentifier.TableName);
  495. schemaRow ["BaseSchemaName"] = GetColumnAttributeStr (i+1, FieldIdentifier.SchemaName);
  496. schemaRow ["BaseCatalogName"] = GetColumnAttributeStr (i+1, FieldIdentifier.CatelogName);
  497. schemaRow ["BaseColumnName"] = GetColumnAttributeStr (i+1, FieldIdentifier.BaseColumnName);
  498. schemaRow ["DataType"] = col.DataType;
  499. schemaRow ["IsUnique"] = false;
  500. schemaRow ["IsKey"] = DBNull.Value;
  501. schemaRow ["AllowDBNull"] = GetColumnAttribute (i+1, FieldIdentifier.Nullable) != libodbc.SQL_NO_NULLS;
  502. schemaRow ["ProviderType"] = (int) col.OdbcType;
  503. schemaRow ["IsAutoIncrement"] = GetColumnAttribute (i+1, FieldIdentifier.AutoUniqueValue) == libodbc.SQL_TRUE;
  504. schemaRow ["IsExpression"] = schemaRow.IsNull ("BaseTableName") || (string) schemaRow ["BaseTableName"] == String.Empty;
  505. schemaRow ["IsAliased"] = (string) schemaRow ["BaseColumnName"] != (string) schemaRow ["ColumnName"];
  506. schemaRow ["IsReadOnly"] = ((bool) schemaRow ["IsExpression"]
  507. || GetColumnAttribute (i+1, FieldIdentifier.Updatable) == libodbc.SQL_ATTR_READONLY);
  508. // FIXME: all of these
  509. schemaRow ["IsIdentity"] = false;
  510. schemaRow ["IsRowVersion"] = false;
  511. schemaRow ["IsHidden"] = false;
  512. schemaRow ["IsLong"] = false;
  513. // FIXME: according to Brian,
  514. // this does not work on MS .NET
  515. // however, we need it for Mono
  516. // for now
  517. // schemaRow.AcceptChanges();
  518. }
  519. // set primary keys
  520. DataRow [] rows = dataTableSchema.Select ("BaseTableName <> ''",
  521. "BaseCatalogName, BaseSchemaName, BaseTableName ASC");
  522. string lastTableName = String.Empty,
  523. lastSchemaName = String.Empty,
  524. lastCatalogName = String.Empty;
  525. string [] keys = null; // assumed to be sorted.
  526. foreach (DataRow row in rows) {
  527. string tableName = (string) row ["BaseTableName"];
  528. string schemaName = (string) row ["BaseSchemaName"];
  529. string catalogName = (string) row ["BaseCatalogName"];
  530. if (tableName != lastTableName || schemaName != lastSchemaName
  531. || catalogName != lastCatalogName)
  532. keys = GetPrimaryKeys (catalogName, schemaName, tableName);
  533. if (keys != null &&
  534. Array.BinarySearch (keys, (string) row ["BaseColumnName"]) >= 0) {
  535. row ["IsKey"] = true;
  536. row ["IsUnique"] = true;
  537. row ["AllowDBNull"] = false;
  538. GetColumn ( ColIndex ( (string) row ["ColumnName"])).AllowDBNull = false;
  539. }
  540. lastTableName = tableName;
  541. lastSchemaName = schemaName;
  542. lastCatalogName = catalogName;
  543. }
  544. dataTableSchema.AcceptChanges();
  545. }
  546. return (_dataTableSchema = dataTableSchema);
  547. }
  548. public
  549. #if NET_2_0
  550. override
  551. #endif // NET_2_0
  552. string GetString (int ordinal)
  553. {
  554. return (string) GetValue(ordinal);
  555. }
  556. [MonoTODO]
  557. public TimeSpan GetTime (int ordinal)
  558. {
  559. throw new NotImplementedException ();
  560. }
  561. public
  562. #if NET_2_0
  563. override
  564. #endif // NET_2_0
  565. object GetValue (int ordinal)
  566. {
  567. if (currentRow == -1)
  568. throw new IndexOutOfRangeException ();
  569. if (ordinal>cols.Length-1 || ordinal<0)
  570. throw new IndexOutOfRangeException ();
  571. OdbcReturn ret;
  572. int outsize=0, bufsize;
  573. byte[] buffer;
  574. OdbcColumn col=GetColumn(ordinal);
  575. object DataValue=null;
  576. ushort ColIndex=Convert.ToUInt16(ordinal+1);
  577. // Check cached values
  578. if (col.Value==null) {
  579. // odbc help file
  580. // mk:@MSITStore:C:\program%20files\Microsoft%20Data%20Access%20SDK\Docs\odbc.chm::/htm/odbcc_data_types.htm
  581. switch (col.OdbcType) {
  582. case OdbcType.Bit:
  583. short bit_data = 0;
  584. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref bit_data, 0, ref outsize);
  585. if (outsize != (int) OdbcLengthIndicator.NullData)
  586. DataValue = bit_data == 0 ? "False" : "True";
  587. break;
  588. case OdbcType.Numeric:
  589. case OdbcType.Decimal:
  590. bufsize=50;
  591. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for decimal.
  592. // FIXME : use Numeric.
  593. ret=libodbc.SQLGetData(hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  594. if (outsize!=-1) {
  595. byte[] temp = new byte[outsize];
  596. for (int i=0;i<outsize;i++)
  597. temp[i]=buffer[i];
  598. DataValue=Decimal.Parse(System.Text.Encoding.Default.GetString(temp));
  599. }
  600. break;
  601. case OdbcType.TinyInt:
  602. short short_data=0;
  603. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref short_data, 0, ref outsize);
  604. DataValue=System.Convert.ToByte(short_data);
  605. break;
  606. case OdbcType.Int:
  607. int int_data=0;
  608. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref int_data, 0, ref outsize);
  609. DataValue=int_data;
  610. break;
  611. case OdbcType.SmallInt:
  612. short sint_data=0;
  613. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref sint_data, 0, ref outsize);
  614. DataValue=sint_data;
  615. break;
  616. case OdbcType.BigInt:
  617. long long_data=0;
  618. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref long_data, 0, ref outsize);
  619. DataValue=long_data;
  620. break;
  621. case OdbcType.NText:
  622. case OdbcType.NVarChar:
  623. bufsize=col.MaxLength*2+1; // Unicode is double byte
  624. buffer=new byte[bufsize];
  625. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  626. if (outsize!=-1)
  627. DataValue=System.Text.Encoding.Unicode.GetString(buffer,0,outsize);
  628. break;
  629. case OdbcType.Text:
  630. case OdbcType.VarChar:
  631. bufsize=col.MaxLength+1;
  632. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  633. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  634. if (outsize!=-1)
  635. DataValue=System.Text.Encoding.Default.GetString(buffer,0,outsize);
  636. break;
  637. case OdbcType.Real:
  638. float float_data=0;
  639. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref float_data, 0, ref outsize);
  640. DataValue=float_data;
  641. break;
  642. case OdbcType.Double:
  643. double double_data=0;
  644. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref double_data, 0, ref outsize);
  645. DataValue=double_data;
  646. break;
  647. case OdbcType.Timestamp:
  648. case OdbcType.DateTime:
  649. case OdbcType.Date:
  650. case OdbcType.Time:
  651. OdbcTimestamp ts_data=new OdbcTimestamp();
  652. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref ts_data, 0, ref outsize);
  653. if (outsize!=-1) // This means SQL_NULL_DATA
  654. DataValue=new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  655. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  656. break;
  657. case OdbcType.Binary :
  658. case OdbcType.Image :
  659. bufsize = col.MaxLength + 1;
  660. buffer = new byte [bufsize];
  661. long read = GetBytes (ordinal, 0, buffer, 0, bufsize);
  662. ret = OdbcReturn.Success;
  663. DataValue = buffer;
  664. break;
  665. default:
  666. bufsize=255;
  667. buffer=new byte[bufsize];
  668. ret=libodbc.SQLGetData(hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  669. if (outsize != (int) OdbcLengthIndicator.NullData)
  670. if (! (ret == OdbcReturn.SuccessWithInfo
  671. && outsize == (int) OdbcLengthIndicator.NoTotal))
  672. DataValue=System.Text.Encoding.Default.GetString(buffer, 0, outsize);
  673. break;
  674. }
  675. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  676. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  677. if (outsize==-1) // This means SQL_NULL_DATA
  678. col.Value=DBNull.Value;
  679. else
  680. col.Value=DataValue;
  681. }
  682. return col.Value;
  683. }
  684. public
  685. #if NET_2_0
  686. override
  687. #endif // NET_2_0
  688. int GetValues (object[] values)
  689. {
  690. int numValues = 0;
  691. // copy values
  692. for (int i = 0; i < values.Length; i++) {
  693. if (i < FieldCount) {
  694. values[i] = GetValue(i);
  695. }
  696. else {
  697. values[i] = null;
  698. }
  699. }
  700. // get number of object instances in array
  701. if (values.Length < FieldCount)
  702. numValues = values.Length;
  703. else if (values.Length == FieldCount)
  704. numValues = FieldCount;
  705. else
  706. numValues = FieldCount;
  707. return numValues;
  708. }
  709. #if ONLY_1_1
  710. [MonoTODO]
  711. IDataReader IDataRecord.GetData (int ordinal)
  712. {
  713. throw new NotImplementedException ();
  714. }
  715. void IDisposable.Dispose ()
  716. {
  717. Dispose (true);
  718. GC.SuppressFinalize (this);
  719. }
  720. IEnumerator IEnumerable.GetEnumerator ()
  721. {
  722. return new DbEnumerator (this);
  723. }
  724. #endif // ONLY_1_1
  725. #if NET_2_0
  726. protected override
  727. #endif
  728. void Dispose (bool disposing)
  729. {
  730. if (disposed)
  731. return;
  732. if (disposing) {
  733. // dispose managed resources
  734. Close ();
  735. }
  736. command = null;
  737. cols = null;
  738. _dataTableSchema = null;
  739. disposed = true;
  740. }
  741. public
  742. #if NET_2_0
  743. override
  744. #endif // NET_2_0
  745. bool IsDBNull (int ordinal)
  746. {
  747. return (GetValue(ordinal) is DBNull);
  748. }
  749. /// <remarks>
  750. /// Move to the next result set.
  751. /// </remarks>
  752. public
  753. #if NET_2_0
  754. override
  755. #endif // NET_2_0
  756. bool NextResult ()
  757. {
  758. OdbcReturn ret = OdbcReturn.Success;
  759. ret = libodbc.SQLMoreResults (hstmt);
  760. if (ret == OdbcReturn.Success) {
  761. short colcount = 0;
  762. libodbc.SQLNumResultCols (hstmt, ref colcount);
  763. cols = new OdbcColumn [colcount];
  764. _dataTableSchema = null; // force fresh creation
  765. GetSchemaTable ();
  766. }
  767. return (ret==OdbcReturn.Success);
  768. }
  769. /// <remarks>
  770. /// Load the next row in the current result set.
  771. /// </remarks>
  772. private bool NextRow ()
  773. {
  774. OdbcReturn ret=libodbc.SQLFetch (hstmt);
  775. if (ret != OdbcReturn.Success)
  776. currentRow = -1;
  777. else
  778. currentRow++;
  779. // Clear cached values from last record
  780. foreach (OdbcColumn col in cols)
  781. {
  782. if (col != null)
  783. col.Value = null;
  784. }
  785. return (ret == OdbcReturn.Success);
  786. }
  787. private int GetColumnAttribute (int column, FieldIdentifier fieldId)
  788. {
  789. OdbcReturn ret = OdbcReturn.Error;
  790. byte [] buffer = new byte [255];
  791. int outsize = 0;
  792. int val = 0;
  793. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  794. buffer, buffer.Length,
  795. ref outsize, ref val);
  796. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  797. throw new OdbcException (new OdbcError ("SQLColAttribute",
  798. OdbcHandleType.Stmt,
  799. hstmt)
  800. );
  801. return val;
  802. }
  803. private string GetColumnAttributeStr (int column, FieldIdentifier fieldId)
  804. {
  805. OdbcReturn ret = OdbcReturn.Error;
  806. byte [] buffer = new byte [255];
  807. int outsize = 0;
  808. int val = 0;
  809. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  810. buffer, buffer.Length,
  811. ref outsize, ref val);
  812. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  813. throw new OdbcException (new OdbcError ("SQLColAttribute",
  814. OdbcHandleType.Stmt,
  815. hstmt)
  816. );
  817. string value = "";
  818. if (outsize > 0)
  819. value = Encoding.Default.GetString (buffer, 0, outsize);
  820. return value;
  821. }
  822. private string [] GetPrimaryKeys (string catalog, string schema, string table)
  823. {
  824. if (cols.Length <= 0)
  825. return new string [0];
  826. ArrayList keys = null;
  827. try {
  828. keys = GetPrimaryKeysBySQLPrimaryKey (catalog, schema, table);
  829. } catch (OdbcException){
  830. try {
  831. keys = GetPrimaryKeysBySQLStatistics (catalog, schema, table);
  832. } catch (OdbcException) {
  833. }
  834. }
  835. keys.Sort ();
  836. return (string []) keys.ToArray (typeof (string));
  837. }
  838. private ArrayList GetPrimaryKeysBySQLPrimaryKey (string catalog, string schema, string table)
  839. {
  840. ArrayList keys = new ArrayList ();
  841. IntPtr handle = IntPtr.Zero;
  842. OdbcReturn ret;
  843. try {
  844. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  845. command.Connection.hDbc, ref handle);
  846. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  847. throw new OdbcException(new OdbcError("SQLAllocHandle",
  848. OdbcHandleType.Dbc,
  849. command.Connection.hDbc));
  850. ret = libodbc.SQLPrimaryKeys (handle, catalog, -3,
  851. schema, -3,
  852. table, -3);
  853. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  854. throw new OdbcException (new OdbcError ("SQLPrimaryKeys", OdbcHandleType.Stmt, handle));
  855. int length = 0;
  856. byte [] primaryKey = new byte [255];
  857. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.CHAR, primaryKey, primaryKey.Length, ref length);
  858. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  859. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  860. int i = 0;
  861. while (true) {
  862. ret = libodbc.SQLFetch (handle);
  863. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  864. break;
  865. string pkey = Encoding.Default.GetString (primaryKey, 0, length);
  866. keys.Add (pkey);
  867. }
  868. } finally {
  869. if (handle != IntPtr.Zero) {
  870. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  871. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  872. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  873. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  874. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  875. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  876. }
  877. }
  878. return keys;
  879. }
  880. private unsafe ArrayList GetPrimaryKeysBySQLStatistics (string catalog, string schema, string table)
  881. {
  882. ArrayList keys = new ArrayList ();
  883. IntPtr handle = IntPtr.Zero;
  884. OdbcReturn ret;
  885. try {
  886. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  887. command.Connection.hDbc, ref handle);
  888. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  889. throw new OdbcException(new OdbcError("SQLAllocHandle",
  890. OdbcHandleType.Dbc,
  891. command.Connection.hDbc));
  892. ret = libodbc.SQLStatistics (handle, catalog, -3,
  893. schema, -3,
  894. table, -3,
  895. libodbc.SQL_INDEX_UNIQUE,
  896. libodbc.SQL_QUICK);
  897. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  898. throw new OdbcException (new OdbcError ("SQLStatistics", OdbcHandleType.Stmt, handle));
  899. // NON_UNIQUE
  900. int nonUniqueLength = 0;
  901. short nonUnique = libodbc.SQL_FALSE;
  902. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.SHORT, ref (short) nonUnique, sizeof (short), ref nonUniqueLength);
  903. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  904. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  905. // COLUMN_NAME
  906. int length = 0;
  907. byte [] colName = new byte [255];
  908. ret = libodbc.SQLBindCol (handle, 9, SQL_C_TYPE.CHAR, colName, colName.Length, ref length);
  909. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  910. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  911. int i = 0;
  912. while (true) {
  913. ret = libodbc.SQLFetch (handle);
  914. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  915. break;
  916. if (nonUnique == libodbc.SQL_TRUE) {
  917. string pkey = Encoding.Default.GetString (colName, 0, length);
  918. keys.Add (pkey);
  919. break;
  920. }
  921. }
  922. } finally {
  923. if (handle != IntPtr.Zero) {
  924. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  925. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  926. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  927. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  928. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  929. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  930. }
  931. }
  932. return keys;
  933. }
  934. public
  935. #if NET_2_0
  936. override
  937. #endif // NET_2_0
  938. bool Read ()
  939. {
  940. return NextRow ();
  941. }
  942. #if NET_2_0
  943. [MonoTODO]
  944. public override object GetProviderSpecificValue (int i)
  945. {
  946. throw new NotImplementedException ();
  947. }
  948. [MonoTODO]
  949. public override int GetProviderSpecificValues (object[] values)
  950. {
  951. throw new NotImplementedException ();
  952. }
  953. [MonoTODO]
  954. public override Type GetProviderSpecificFieldType (int i)
  955. {
  956. throw new NotImplementedException ();
  957. }
  958. #endif // NET_2_0
  959. #endregion
  960. }
  961. }