OdbcDataReader.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. //
  2. // System.Data.Odbc.OdbcDataReader
  3. //
  4. // Author:
  5. // Brian Ritchie ([email protected])
  6. // Daniel Morgan <[email protected]>
  7. //
  8. // Copyright (C) Brian Ritchie, 2002
  9. // Copyright (C) Daniel Morgan, 2002
  10. //
  11. //
  12. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System.Collections;
  34. using System.ComponentModel;
  35. using System.Data;
  36. using System.Data.Common;
  37. using System.Text;
  38. namespace System.Data.Odbc
  39. {
  40. public sealed class OdbcDataReader : MarshalByRefObject, IDataReader, IDisposable, IDataRecord, IEnumerable
  41. {
  42. #region Fields
  43. private OdbcCommand command;
  44. private bool open;
  45. private int currentRow;
  46. private OdbcColumn[] cols;
  47. private IntPtr hstmt;
  48. private CommandBehavior behavior;
  49. #endregion
  50. #region Constructors
  51. internal OdbcDataReader (OdbcCommand command, CommandBehavior behavior)
  52. {
  53. this.command = command;
  54. this.behavior=behavior;
  55. open = true;
  56. currentRow = -1;
  57. hstmt=command.hStmt;
  58. // Init columns array;
  59. short colcount=0;
  60. libodbc.SQLNumResultCols(hstmt, ref colcount);
  61. cols=new OdbcColumn[colcount];
  62. }
  63. #endregion
  64. #region Properties
  65. public int Depth {
  66. get {
  67. return 0; // no nested selects supported
  68. }
  69. }
  70. public int FieldCount {
  71. get {
  72. return cols.Length;
  73. }
  74. }
  75. public bool IsClosed {
  76. get {
  77. return !open;
  78. }
  79. }
  80. public object this[string name] {
  81. get {
  82. int pos;
  83. if (currentRow == -1)
  84. throw new InvalidOperationException ();
  85. pos = ColIndex(name);
  86. if (pos == -1)
  87. throw new IndexOutOfRangeException ();
  88. return this[pos];
  89. }
  90. }
  91. public object this[int index] {
  92. get {
  93. return (object) GetValue (index);
  94. }
  95. }
  96. public int RecordsAffected {
  97. get {
  98. return -1;
  99. }
  100. }
  101. [MonoTODO]
  102. public bool HasRows {
  103. get { throw new NotImplementedException(); }
  104. }
  105. #endregion
  106. #region Methods
  107. private int ColIndex(string colname)
  108. {
  109. int i=0;
  110. foreach (OdbcColumn col in cols)
  111. {
  112. if (col.ColumnName==colname)
  113. return i;
  114. i++;
  115. }
  116. return 0;
  117. }
  118. // Dynamically load column descriptions as needed.
  119. private OdbcColumn GetColumn(int ordinal)
  120. {
  121. if (cols[ordinal]==null)
  122. {
  123. short bufsize=255;
  124. byte[] colname_buffer=new byte[bufsize];
  125. string colname;
  126. short colname_size=0;
  127. uint ColSize=0;
  128. short DecDigits=0, Nullable=0, dt=0;
  129. OdbcReturn ret=libodbc.SQLDescribeCol(hstmt, Convert.ToUInt16(ordinal+1),
  130. colname_buffer, bufsize, ref colname_size, ref dt, ref ColSize,
  131. ref DecDigits, ref Nullable);
  132. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  133. throw new OdbcException(new OdbcError("SQLDescribeCol",OdbcHandleType.Stmt,hstmt));
  134. colname=System.Text.Encoding.Default.GetString(colname_buffer);
  135. colname=colname.Replace((char) 0,' ').Trim();
  136. OdbcColumn c=new OdbcColumn(colname, (OdbcType) dt);
  137. c.AllowDBNull=(Nullable!=0);
  138. c.Digits=DecDigits;
  139. if (c.IsStringType)
  140. c.MaxLength=(int)ColSize;
  141. cols[ordinal]=c;
  142. }
  143. return cols[ordinal];
  144. }
  145. public void Close ()
  146. {
  147. OdbcReturn ret=libodbc.SQLCloseCursor(hstmt);
  148. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  149. throw new OdbcException(new OdbcError("SQLCloseCursor",OdbcHandleType.Stmt,hstmt));
  150. open = false;
  151. currentRow = -1;
  152. if ((behavior & CommandBehavior.CloseConnection)==CommandBehavior.CloseConnection)
  153. this.command.Connection.Close();
  154. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, hstmt);
  155. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  156. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,hstmt));
  157. }
  158. ~OdbcDataReader ()
  159. {
  160. if (open)
  161. Close ();
  162. }
  163. public bool GetBoolean (int ordinal)
  164. {
  165. return (bool) GetValue(ordinal);
  166. }
  167. public byte GetByte (int ordinal)
  168. {
  169. return (byte) Convert.ToByte(GetValue(ordinal));
  170. }
  171. public long GetBytes (int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
  172. {
  173. OdbcReturn ret = OdbcReturn.Error;
  174. bool copyBuffer = false;
  175. int returnVal = 0, outsize = 0;
  176. byte [] tbuff = new byte [length+1];
  177. length = buffer == null ? 0 : length;
  178. ret=libodbc.SQLGetData (hstmt, (ushort) (ordinal+1), OdbcType.Binary, tbuff, length,
  179. ref outsize);
  180. if (ret == OdbcReturn.NoData)
  181. return 0;
  182. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  183. throw new OdbcException (new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt));
  184. OdbcError odbcErr = null;
  185. if ( (ret == OdbcReturn.SuccessWithInfo))
  186. odbcErr = new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt);
  187. if (buffer == null)
  188. return outsize; //if buffer is null,return length of the field
  189. if (ret == OdbcReturn.SuccessWithInfo) {
  190. if (outsize == (int) OdbcLengthIndicator.NoTotal)
  191. copyBuffer = true;
  192. else if (outsize == (int) OdbcLengthIndicator.NullData) {
  193. copyBuffer = false;
  194. returnVal = -1;
  195. } else {
  196. string sqlstate = odbcErr.SQLState;
  197. //SQLState: String Data, Right truncated
  198. if (sqlstate != libodbc.SQLSTATE_RIGHT_TRUNC)
  199. throw new OdbcException ( odbcErr);
  200. copyBuffer = true;
  201. }
  202. } else {
  203. copyBuffer = outsize == -1 ? false : true;
  204. returnVal = outsize;
  205. }
  206. if (copyBuffer) {
  207. int i = 0;
  208. while (tbuff [i] != libodbc.C_NULL) {
  209. buffer [bufferIndex + i] = tbuff [i];
  210. i++;
  211. }
  212. returnVal = i;
  213. }
  214. return returnVal;
  215. }
  216. [MonoTODO]
  217. public char GetChar (int ordinal)
  218. {
  219. throw new NotImplementedException ();
  220. }
  221. [MonoTODO]
  222. public long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length)
  223. {
  224. throw new NotImplementedException ();
  225. }
  226. [MonoTODO]
  227. [EditorBrowsableAttribute (EditorBrowsableState.Never)]
  228. public IDataReader GetData (int ordinal)
  229. {
  230. throw new NotImplementedException ();
  231. }
  232. public string GetDataTypeName (int index)
  233. {
  234. return GetColumn(index).OdbcType.ToString();
  235. }
  236. public DateTime GetDate(int ordinal) {
  237. return GetDateTime(ordinal);
  238. }
  239. public DateTime GetDateTime (int ordinal)
  240. {
  241. return (DateTime) GetValue(ordinal);
  242. }
  243. [MonoTODO]
  244. public decimal GetDecimal (int ordinal)
  245. {
  246. throw new NotImplementedException ();
  247. }
  248. public double GetDouble (int ordinal)
  249. {
  250. return (double) GetValue(ordinal);
  251. }
  252. public Type GetFieldType (int index)
  253. {
  254. return GetColumn(index).DataType;
  255. }
  256. public float GetFloat (int ordinal)
  257. {
  258. return (float) GetValue(ordinal);
  259. }
  260. [MonoTODO]
  261. public Guid GetGuid (int ordinal)
  262. {
  263. throw new NotImplementedException ();
  264. }
  265. public short GetInt16 (int ordinal)
  266. {
  267. return (short) GetValue(ordinal);
  268. }
  269. public int GetInt32 (int ordinal)
  270. {
  271. return (int) GetValue(ordinal);
  272. }
  273. public long GetInt64 (int ordinal)
  274. {
  275. return (long) GetValue(ordinal);
  276. }
  277. public string GetName (int index)
  278. {
  279. return GetColumn(index).ColumnName;
  280. }
  281. public int GetOrdinal (string name)
  282. {
  283. if (currentRow == -1)
  284. throw new IndexOutOfRangeException ();
  285. int i=ColIndex(name);
  286. if (i==-1)
  287. throw new IndexOutOfRangeException ();
  288. else
  289. return i;
  290. }
  291. [MonoTODO]
  292. public DataTable GetSchemaTable()
  293. {
  294. DataTable dataTableSchema = null;
  295. // Only Results from SQL SELECT Queries
  296. // get a DataTable for schema of the result
  297. // otherwise, DataTable is null reference
  298. if(cols.Length > 0)
  299. {
  300. dataTableSchema = new DataTable ();
  301. dataTableSchema.Columns.Add ("ColumnName", typeof (string));
  302. dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
  303. dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
  304. dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
  305. dataTableSchema.Columns.Add ("NumericScale", typeof (int));
  306. dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
  307. dataTableSchema.Columns.Add ("IsKey", typeof (bool));
  308. DataColumn dc = dataTableSchema.Columns["IsKey"];
  309. dc.AllowDBNull = true; // IsKey can have a DBNull
  310. dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
  311. dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
  312. dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
  313. dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
  314. dataTableSchema.Columns.Add ("DataType", typeof(Type));
  315. dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
  316. dataTableSchema.Columns.Add ("ProviderType", typeof (int));
  317. dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
  318. dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
  319. dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
  320. dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
  321. dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
  322. dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
  323. dataTableSchema.Columns.Add ("IsLong", typeof (bool));
  324. dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
  325. DataRow schemaRow;
  326. for (int i = 0; i < cols.Length; i += 1 )
  327. {
  328. OdbcColumn col=GetColumn(i);
  329. schemaRow = dataTableSchema.NewRow ();
  330. dataTableSchema.Rows.Add (schemaRow);
  331. schemaRow["ColumnName"] = col.ColumnName;
  332. schemaRow["ColumnOrdinal"] = i + 1;
  333. schemaRow["ColumnSize"] = col.MaxLength;
  334. schemaRow["NumericPrecision"] = 0;
  335. schemaRow["NumericScale"] = 0;
  336. // TODO: need to get KeyInfo
  337. schemaRow["IsUnique"] = false;
  338. schemaRow["IsKey"] = DBNull.Value;
  339. schemaRow["BaseCatalogName"] = "";
  340. schemaRow["BaseColumnName"] = col.ColumnName;
  341. schemaRow["BaseSchemaName"] = "";
  342. schemaRow["BaseTableName"] = "";
  343. schemaRow["DataType"] = col.DataType;
  344. schemaRow["AllowDBNull"] = col.AllowDBNull;
  345. schemaRow["ProviderType"] = (int) col.OdbcType;
  346. // TODO: all of these
  347. schemaRow["IsAliased"] = false;
  348. schemaRow["IsExpression"] = false;
  349. schemaRow["IsIdentity"] = false;
  350. schemaRow["IsAutoIncrement"] = false;
  351. schemaRow["IsRowVersion"] = false;
  352. schemaRow["IsHidden"] = false;
  353. schemaRow["IsLong"] = false;
  354. schemaRow["IsReadOnly"] = false;
  355. // FIXME: according to Brian,
  356. // this does not work on MS .NET
  357. // however, we need it for Mono
  358. // for now
  359. schemaRow.AcceptChanges();
  360. }
  361. }
  362. dataTableSchema.AcceptChanges();
  363. return dataTableSchema;
  364. }
  365. public string GetString (int ordinal)
  366. {
  367. return (string) GetValue(ordinal);
  368. }
  369. [MonoTODO]
  370. public TimeSpan GetTime (int ordinal)
  371. {
  372. throw new NotImplementedException ();
  373. }
  374. public object GetValue (int ordinal)
  375. {
  376. if (currentRow == -1)
  377. throw new IndexOutOfRangeException ();
  378. if (ordinal>cols.Length-1 || ordinal<0)
  379. throw new IndexOutOfRangeException ();
  380. OdbcReturn ret;
  381. int outsize=0, bufsize;
  382. byte[] buffer;
  383. OdbcColumn col=GetColumn(ordinal);
  384. object DataValue=null;
  385. ushort ColIndex=Convert.ToUInt16(ordinal+1);
  386. // Check cached values
  387. if (col.Value==null)
  388. {
  389. // odbc help file
  390. // mk:@MSITStore:C:\program%20files\Microsoft%20Data%20Access%20SDK\Docs\odbc.chm::/htm/odbcc_data_types.htm
  391. switch (col.OdbcType)
  392. {
  393. case OdbcType.Decimal:
  394. bufsize=50;
  395. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for decimal
  396. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  397. byte[] temp = new byte[outsize];
  398. for (int i=0;i<outsize;i++)
  399. temp[i]=buffer[i];
  400. if (outsize!=-1)
  401. DataValue=Decimal.Parse(System.Text.Encoding.Default.GetString(temp));
  402. break;
  403. case OdbcType.TinyInt:
  404. short short_data=0;
  405. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.TinyInt, ref short_data, 0, ref outsize);
  406. DataValue=System.Convert.ToByte(short_data);
  407. break;
  408. case OdbcType.Int:
  409. int int_data=0;
  410. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Int, ref int_data, 0, ref outsize);
  411. DataValue=int_data;
  412. break;
  413. case OdbcType.SmallInt:
  414. short sint_data=0;
  415. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.SmallInt, ref sint_data, 0, ref outsize);
  416. DataValue=sint_data;
  417. break;
  418. case OdbcType.BigInt:
  419. long long_data=0;
  420. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.BigInt, ref long_data, 0, ref outsize);
  421. DataValue=long_data;
  422. break;
  423. case OdbcType.NVarChar:
  424. bufsize=col.MaxLength*2+1; // Unicode is double byte
  425. buffer=new byte[bufsize];
  426. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.NVarChar, buffer, bufsize, ref outsize);
  427. if (outsize!=-1)
  428. DataValue=System.Text.Encoding.Unicode.GetString(buffer,0,outsize);
  429. break;
  430. case OdbcType.VarChar:
  431. bufsize=col.MaxLength+1;
  432. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  433. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  434. if (outsize!=-1)
  435. DataValue=System.Text.Encoding.Default.GetString(buffer,0,outsize);
  436. break;
  437. case OdbcType.Real:
  438. float float_data=0;
  439. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Real, ref float_data, 0, ref outsize);
  440. DataValue=float_data;
  441. break;
  442. case OdbcType.Timestamp:
  443. case OdbcType.DateTime:
  444. case OdbcType.Date:
  445. case OdbcType.Time:
  446. OdbcTimestamp ts_data=new OdbcTimestamp();
  447. if (col.OdbcType == OdbcType.Timestamp)
  448. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Timestamp, ref ts_data, 0, ref outsize);
  449. else if (col.OdbcType == OdbcType.DateTime)
  450. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.DateTime, ref ts_data, 0, ref outsize);
  451. else if (col.OdbcType == OdbcType.Date)
  452. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Date, ref ts_data, 0, ref outsize);
  453. else // FIXME: how to get TIME datatype ??
  454. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.DateTime, ref ts_data, 0, ref outsize);
  455. if (outsize!=-1) // This means SQL_NULL_DATA
  456. DataValue=new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  457. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  458. break;
  459. case OdbcType.Binary :
  460. case OdbcType.Image :
  461. bufsize = col.MaxLength + 1;
  462. buffer = new byte [bufsize];
  463. long read = GetBytes (ordinal, 0, buffer, 0, bufsize);
  464. ret = OdbcReturn.Success;
  465. DataValue = buffer;
  466. break;
  467. default:
  468. bufsize=255;
  469. buffer=new byte[bufsize];
  470. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  471. DataValue=System.Text.Encoding.Default.GetString(buffer);
  472. break;
  473. }
  474. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  475. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  476. if (outsize==-1) // This means SQL_NULL_DATA
  477. col.Value=DBNull.Value;
  478. else
  479. col.Value=DataValue;
  480. }
  481. return col.Value;
  482. }
  483. public int GetValues (object[] values)
  484. {
  485. int numValues = 0;
  486. // copy values
  487. for (int i = 0; i < values.Length; i++) {
  488. if (i < FieldCount) {
  489. values[i] = GetValue(i);
  490. }
  491. else {
  492. values[i] = null;
  493. }
  494. }
  495. // get number of object instances in array
  496. if (values.Length < FieldCount)
  497. numValues = values.Length;
  498. else if (values.Length == FieldCount)
  499. numValues = FieldCount;
  500. else
  501. numValues = FieldCount;
  502. return numValues;
  503. }
  504. [MonoTODO]
  505. IDataReader IDataRecord.GetData (int ordinal)
  506. {
  507. throw new NotImplementedException ();
  508. }
  509. [MonoTODO]
  510. void IDisposable.Dispose ()
  511. {
  512. }
  513. [MonoTODO]
  514. IEnumerator IEnumerable.GetEnumerator ()
  515. {
  516. return new DbEnumerator (this);
  517. }
  518. public bool IsDBNull (int ordinal)
  519. {
  520. return (GetValue(ordinal) is DBNull);
  521. }
  522. public bool NextResult ()
  523. {
  524. OdbcReturn ret=libodbc.SQLFetch(hstmt);
  525. if (ret!=OdbcReturn.Success)
  526. currentRow=-1;
  527. else
  528. currentRow++;
  529. GetSchemaTable();
  530. // Clear cached values from last record
  531. foreach (OdbcColumn col in cols)
  532. {
  533. if (col!=null)
  534. col.Value=null;
  535. }
  536. return (ret==OdbcReturn.Success);
  537. }
  538. public bool Read ()
  539. {
  540. return NextResult();
  541. }
  542. #endregion
  543. }
  544. }