2
0

OdbcDataReader.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. private string GetSQLState (IntPtr hstmt, ushort recNo)
  146. {
  147. OdbcReturn ret = OdbcReturn.Error;
  148. short bufLength=256, txtLength=0;
  149. int nativeError = 1;
  150. string sqlState = "", sqlMsg = "";
  151. byte [] msgtxtBuffer = new byte [bufLength];
  152. byte [] sqlStateBuffer = new byte [bufLength];
  153. ret = libodbc.SQLGetDiagRec (OdbcHandleType.Stmt, hstmt, recNo,
  154. sqlStateBuffer, ref nativeError, msgtxtBuffer,
  155. bufLength, ref txtLength);
  156. sqlState = Encoding.Default.GetString (sqlStateBuffer).Replace (
  157. (char) 0, ' ').Trim ();
  158. return sqlState;
  159. }
  160. public void Close ()
  161. {
  162. // libodbc.SQLFreeHandle((ushort) OdbcHandleType.Stmt, hstmt);
  163. OdbcReturn ret=libodbc.SQLCloseCursor(hstmt);
  164. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  165. throw new OdbcException(new OdbcError("SQLCloseCursor",OdbcHandleType.Stmt,hstmt));
  166. open = false;
  167. currentRow = -1;
  168. if ((behavior & CommandBehavior.CloseConnection)==CommandBehavior.CloseConnection)
  169. this.command.Connection.Close();
  170. }
  171. ~OdbcDataReader ()
  172. {
  173. if (open)
  174. Close ();
  175. }
  176. public bool GetBoolean (int ordinal)
  177. {
  178. return (bool) GetValue(ordinal);
  179. }
  180. public byte GetByte (int ordinal)
  181. {
  182. return (byte) Convert.ToByte(GetValue(ordinal));
  183. }
  184. public long GetBytes (int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
  185. {
  186. OdbcReturn ret = OdbcReturn.Error;
  187. bool copyBuffer = false;
  188. int returnVal = 0, outsize = 0;
  189. byte [] tbuff = new byte [length+1];
  190. length = buffer == null ? 0 : length;
  191. ret=libodbc.SQLGetData (hstmt, (ushort) (ordinal+1), OdbcType.Binary, tbuff, length,
  192. ref outsize);
  193. if (ret == OdbcReturn.NoData)
  194. return 0;
  195. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  196. throw new OdbcException (new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt));
  197. if (buffer == null)
  198. return outsize; //if buffer is null,return length of the field
  199. if (ret == OdbcReturn.SuccessWithInfo) {
  200. if (outsize == (int) OdbcLengthIndicator.NoTotal)
  201. copyBuffer = true;
  202. else if (outsize == (int) OdbcLengthIndicator.NullData) {
  203. copyBuffer = false;
  204. returnVal = -1;
  205. } else {
  206. string sqlstate = GetSQLState (hstmt, 1);
  207. //SQLState: String Data, Right truncated
  208. if (sqlstate != libodbc.SQLSTATE_RIGHT_TRUNC)
  209. throw new OdbcException (new OdbcError ("SQLGetData",
  210. OdbcHandleType.Stmt, hstmt));
  211. copyBuffer = true;
  212. }
  213. } else {
  214. copyBuffer = outsize == -1 ? false : true;
  215. returnVal = outsize;
  216. }
  217. if (copyBuffer) {
  218. int i = 0;
  219. while (tbuff [i] != libodbc.C_NULL) {
  220. buffer [bufferIndex + i] = tbuff [i];
  221. i++;
  222. }
  223. returnVal = i;
  224. }
  225. return returnVal;
  226. }
  227. [MonoTODO]
  228. public char GetChar (int ordinal)
  229. {
  230. throw new NotImplementedException ();
  231. }
  232. [MonoTODO]
  233. public long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length)
  234. {
  235. throw new NotImplementedException ();
  236. }
  237. [MonoTODO]
  238. [EditorBrowsableAttribute (EditorBrowsableState.Never)]
  239. public IDataReader GetData (int ordinal)
  240. {
  241. throw new NotImplementedException ();
  242. }
  243. public string GetDataTypeName (int index)
  244. {
  245. return GetColumn(index).OdbcType.ToString();
  246. }
  247. public DateTime GetDate(int ordinal) {
  248. return GetDateTime(ordinal);
  249. }
  250. public DateTime GetDateTime (int ordinal)
  251. {
  252. return (DateTime) GetValue(ordinal);
  253. }
  254. [MonoTODO]
  255. public decimal GetDecimal (int ordinal)
  256. {
  257. throw new NotImplementedException ();
  258. }
  259. public double GetDouble (int ordinal)
  260. {
  261. return (double) GetValue(ordinal);
  262. }
  263. public Type GetFieldType (int index)
  264. {
  265. return GetColumn(index).DataType;
  266. }
  267. public float GetFloat (int ordinal)
  268. {
  269. return (float) GetValue(ordinal);
  270. }
  271. [MonoTODO]
  272. public Guid GetGuid (int ordinal)
  273. {
  274. throw new NotImplementedException ();
  275. }
  276. public short GetInt16 (int ordinal)
  277. {
  278. return (short) GetValue(ordinal);
  279. }
  280. public int GetInt32 (int ordinal)
  281. {
  282. return (int) GetValue(ordinal);
  283. }
  284. public long GetInt64 (int ordinal)
  285. {
  286. return (long) GetValue(ordinal);
  287. }
  288. public string GetName (int index)
  289. {
  290. return GetColumn(index).ColumnName;
  291. }
  292. public int GetOrdinal (string name)
  293. {
  294. if (currentRow == -1)
  295. throw new IndexOutOfRangeException ();
  296. int i=ColIndex(name);
  297. if (i==-1)
  298. throw new IndexOutOfRangeException ();
  299. else
  300. return i;
  301. }
  302. [MonoTODO]
  303. public DataTable GetSchemaTable()
  304. {
  305. DataTable dataTableSchema = null;
  306. // Only Results from SQL SELECT Queries
  307. // get a DataTable for schema of the result
  308. // otherwise, DataTable is null reference
  309. if(cols.Length > 0)
  310. {
  311. dataTableSchema = new DataTable ();
  312. dataTableSchema.Columns.Add ("ColumnName", typeof (string));
  313. dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
  314. dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
  315. dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
  316. dataTableSchema.Columns.Add ("NumericScale", typeof (int));
  317. dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
  318. dataTableSchema.Columns.Add ("IsKey", typeof (bool));
  319. DataColumn dc = dataTableSchema.Columns["IsKey"];
  320. dc.AllowDBNull = true; // IsKey can have a DBNull
  321. dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
  322. dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
  323. dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
  324. dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
  325. dataTableSchema.Columns.Add ("DataType", typeof(Type));
  326. dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
  327. dataTableSchema.Columns.Add ("ProviderType", typeof (int));
  328. dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
  329. dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
  330. dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
  331. dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
  332. dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
  333. dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
  334. dataTableSchema.Columns.Add ("IsLong", typeof (bool));
  335. dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
  336. DataRow schemaRow;
  337. for (int i = 0; i < cols.Length; i += 1 )
  338. {
  339. OdbcColumn col=GetColumn(i);
  340. //Console.WriteLine("{0}:{1}:{2}",col.ColumnName,col.DataType,col.OdbcType);
  341. schemaRow = dataTableSchema.NewRow ();
  342. dataTableSchema.Rows.Add (schemaRow);
  343. schemaRow["ColumnName"] = col.ColumnName;
  344. schemaRow["ColumnOrdinal"] = i + 1;
  345. schemaRow["ColumnSize"] = col.MaxLength;
  346. schemaRow["NumericPrecision"] = 0;
  347. schemaRow["NumericScale"] = 0;
  348. // TODO: need to get KeyInfo
  349. schemaRow["IsUnique"] = false;
  350. schemaRow["IsKey"] = DBNull.Value;
  351. schemaRow["BaseCatalogName"] = "";
  352. schemaRow["BaseColumnName"] = col.ColumnName;
  353. schemaRow["BaseSchemaName"] = "";
  354. schemaRow["BaseTableName"] = "";
  355. schemaRow["DataType"] = col.DataType;
  356. schemaRow["AllowDBNull"] = col.AllowDBNull;
  357. schemaRow["ProviderType"] = (int) col.OdbcType;
  358. // TODO: all of these
  359. schemaRow["IsAliased"] = false;
  360. schemaRow["IsExpression"] = false;
  361. schemaRow["IsIdentity"] = false;
  362. schemaRow["IsAutoIncrement"] = false;
  363. schemaRow["IsRowVersion"] = false;
  364. schemaRow["IsHidden"] = false;
  365. schemaRow["IsLong"] = false;
  366. schemaRow["IsReadOnly"] = false;
  367. // FIXME: according to Brian,
  368. // this does not work on MS .NET
  369. // however, we need it for Mono
  370. // for now
  371. schemaRow.AcceptChanges();
  372. }
  373. }
  374. dataTableSchema.AcceptChanges();
  375. return dataTableSchema;
  376. }
  377. public string GetString (int ordinal)
  378. {
  379. return (string) GetValue(ordinal);
  380. }
  381. [MonoTODO]
  382. public TimeSpan GetTime (int ordinal)
  383. {
  384. throw new NotImplementedException ();
  385. }
  386. public object GetValue (int ordinal)
  387. {
  388. if (currentRow == -1)
  389. throw new IndexOutOfRangeException ();
  390. if (ordinal>cols.Length-1 || ordinal<0)
  391. throw new IndexOutOfRangeException ();
  392. OdbcReturn ret;
  393. int outsize=0, bufsize;
  394. byte[] buffer;
  395. OdbcColumn col=GetColumn(ordinal);
  396. object DataValue=null;
  397. ushort ColIndex=Convert.ToUInt16(ordinal+1);
  398. // Check cached values
  399. if (col.Value==null)
  400. {
  401. // odbc help file
  402. // mk:@MSITStore:C:\program%20files\Microsoft%20Data%20Access%20SDK\Docs\odbc.chm::/htm/odbcc_data_types.htm
  403. switch (col.OdbcType)
  404. {
  405. case OdbcType.Decimal:
  406. bufsize=50;
  407. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for decimal
  408. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  409. if (outsize!=-1)
  410. DataValue=Decimal.Parse(System.Text.Encoding.Default.GetString(buffer));
  411. break;
  412. case OdbcType.TinyInt:
  413. short short_data=0;
  414. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.TinyInt, ref short_data, 0, ref outsize);
  415. DataValue=short_data;
  416. break;
  417. case OdbcType.Int:
  418. int int_data=0;
  419. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Int, ref int_data, 0, ref outsize);
  420. DataValue=int_data;
  421. break;
  422. case OdbcType.BigInt:
  423. long long_data=0;
  424. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.BigInt, ref long_data, 0, ref outsize);
  425. DataValue=long_data;
  426. break;
  427. case OdbcType.NVarChar:
  428. bufsize=col.MaxLength*2+1; // Unicode is double byte
  429. buffer=new byte[bufsize];
  430. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.NVarChar, buffer, bufsize, ref outsize);
  431. if (outsize!=-1)
  432. DataValue=System.Text.Encoding.Unicode.GetString(buffer,0,outsize);
  433. break;
  434. case OdbcType.VarChar:
  435. bufsize=col.MaxLength+1;
  436. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  437. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  438. if (outsize!=-1)
  439. DataValue=System.Text.Encoding.Default.GetString(buffer,0,outsize);
  440. break;
  441. case OdbcType.Real:
  442. float float_data=0;
  443. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Real, ref float_data, 0, ref outsize);
  444. DataValue=float_data;
  445. break;
  446. case OdbcType.Timestamp:
  447. case OdbcType.DateTime:
  448. OdbcTimestamp ts_data=new OdbcTimestamp();
  449. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.DateTime, ref ts_data, 0, ref outsize);
  450. if (outsize!=-1) // This means SQL_NULL_DATA
  451. DataValue=new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  452. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  453. break;
  454. case OdbcType.Binary :
  455. case OdbcType.Image :
  456. bufsize = col.MaxLength + 1;
  457. buffer = new byte [bufsize];
  458. long read = GetBytes (ColIndex, 0, buffer, 0, bufsize);
  459. ret = OdbcReturn.Success;
  460. DataValue = buffer;
  461. break;
  462. default:
  463. //Console.WriteLine("Fetching unsupported data type as string: "+col.OdbcType.ToString());
  464. bufsize=255;
  465. buffer=new byte[bufsize];
  466. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  467. DataValue=System.Text.Encoding.Default.GetString(buffer);
  468. break;
  469. }
  470. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  471. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  472. if (outsize==-1) // This means SQL_NULL_DATA
  473. col.Value=DBNull.Value;
  474. else
  475. col.Value=DataValue;
  476. }
  477. return col.Value;
  478. }
  479. public int GetValues (object[] values)
  480. {
  481. int numValues = 0;
  482. // copy values
  483. for (int i = 0; i < values.Length; i++) {
  484. if (i < FieldCount) {
  485. values[i] = GetValue(i);
  486. }
  487. else {
  488. values[i] = null;
  489. }
  490. }
  491. // get number of object instances in array
  492. if (values.Length < FieldCount)
  493. numValues = values.Length;
  494. else if (values.Length == FieldCount)
  495. numValues = FieldCount;
  496. else
  497. numValues = FieldCount;
  498. return numValues;
  499. }
  500. [MonoTODO]
  501. IDataReader IDataRecord.GetData (int ordinal)
  502. {
  503. throw new NotImplementedException ();
  504. }
  505. [MonoTODO]
  506. void IDisposable.Dispose ()
  507. {
  508. }
  509. [MonoTODO]
  510. IEnumerator IEnumerable.GetEnumerator ()
  511. {
  512. return new DbEnumerator (this);
  513. }
  514. public bool IsDBNull (int ordinal)
  515. {
  516. return (GetValue(ordinal) is DBNull);
  517. }
  518. public bool NextResult ()
  519. {
  520. OdbcReturn ret=libodbc.SQLFetch(hstmt);
  521. if (ret!=OdbcReturn.Success)
  522. currentRow=-1;
  523. else
  524. currentRow++;
  525. // Clear cached values from last record
  526. foreach (OdbcColumn col in cols)
  527. {
  528. if (col!=null)
  529. col.Value=null;
  530. }
  531. return (ret==OdbcReturn.Success);
  532. }
  533. public bool Read ()
  534. {
  535. return NextResult();
  536. }
  537. #endregion
  538. }
  539. }