OdbcDataReader.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. using System.Collections;
  12. using System.ComponentModel;
  13. using System.Data;
  14. using System.Data.Common;
  15. namespace System.Data.Odbc
  16. {
  17. public sealed class OdbcDataReader : MarshalByRefObject, IDataReader, IDisposable, IDataRecord, IEnumerable
  18. {
  19. #region Fields
  20. private OdbcCommand command;
  21. private bool open;
  22. private int currentRow;
  23. private OdbcColumn[] cols;
  24. private IntPtr hstmt;
  25. private CommandBehavior behavior;
  26. #endregion
  27. #region Constructors
  28. internal OdbcDataReader (OdbcCommand command, CommandBehavior behavior)
  29. {
  30. this.command = command;
  31. this.behavior=behavior;
  32. open = true;
  33. currentRow = -1;
  34. hstmt=command.hStmt;
  35. // Init columns array;
  36. short colcount=0;
  37. libodbc.SQLNumResultCols(hstmt, ref colcount);
  38. cols=new OdbcColumn[colcount];
  39. }
  40. #endregion
  41. #region Properties
  42. public int Depth {
  43. get {
  44. return 0; // no nested selects supported
  45. }
  46. }
  47. public int FieldCount {
  48. get {
  49. return cols.Length;
  50. }
  51. }
  52. public bool IsClosed {
  53. get {
  54. return !open;
  55. }
  56. }
  57. public object this[string name] {
  58. get {
  59. int pos;
  60. if (currentRow == -1)
  61. throw new InvalidOperationException ();
  62. pos = ColIndex(name);
  63. if (pos == -1)
  64. throw new IndexOutOfRangeException ();
  65. return this[pos];
  66. }
  67. }
  68. public object this[int index] {
  69. get {
  70. return (object) GetValue (index);
  71. }
  72. }
  73. public int RecordsAffected {
  74. get {
  75. return -1;
  76. }
  77. }
  78. [MonoTODO]
  79. public bool HasRows {
  80. get { throw new NotImplementedException(); }
  81. }
  82. #endregion
  83. #region Methods
  84. private int ColIndex(string colname)
  85. {
  86. int i=0;
  87. foreach (OdbcColumn col in cols)
  88. {
  89. if (col.ColumnName==colname)
  90. return i;
  91. i++;
  92. }
  93. return 0;
  94. }
  95. // Dynamically load column descriptions as needed.
  96. private OdbcColumn GetColumn(int ordinal)
  97. {
  98. if (cols[ordinal]==null)
  99. {
  100. short bufsize=255;
  101. byte[] colname_buffer=new byte[bufsize];
  102. string colname;
  103. short colname_size=0;
  104. uint ColSize=0;
  105. short DecDigits=0, Nullable=0, dt=0;
  106. OdbcReturn ret=libodbc.SQLDescribeCol(hstmt, Convert.ToUInt16(ordinal+1),
  107. colname_buffer, bufsize, ref colname_size, ref dt, ref ColSize,
  108. ref DecDigits, ref Nullable);
  109. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  110. throw new OdbcException(new OdbcError("SQLDescribeCol",OdbcHandleType.Stmt,hstmt));
  111. colname=System.Text.Encoding.Default.GetString(colname_buffer);
  112. colname=colname.Replace((char) 0,' ').Trim();
  113. OdbcColumn c=new OdbcColumn(colname, (OdbcType) dt);
  114. c.AllowDBNull=(Nullable!=0);
  115. c.Digits=DecDigits;
  116. if (c.IsStringType)
  117. c.MaxLength=(int)ColSize;
  118. cols[ordinal]=c;
  119. }
  120. return cols[ordinal];
  121. }
  122. public void Close ()
  123. {
  124. // libodbc.SQLFreeHandle((ushort) OdbcHandleType.Stmt, hstmt);
  125. OdbcReturn ret=libodbc.SQLCloseCursor(hstmt);
  126. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  127. throw new OdbcException(new OdbcError("SQLCloseCursor",OdbcHandleType.Stmt,hstmt));
  128. open = false;
  129. currentRow = -1;
  130. if ((behavior & CommandBehavior.CloseConnection)==CommandBehavior.CloseConnection)
  131. this.command.Connection.Close();
  132. }
  133. ~OdbcDataReader ()
  134. {
  135. if (open)
  136. Close ();
  137. }
  138. public bool GetBoolean (int ordinal)
  139. {
  140. return (bool) GetValue(ordinal);
  141. }
  142. [MonoTODO]
  143. public byte GetByte (int ordinal)
  144. {
  145. throw new NotImplementedException ();
  146. }
  147. [MonoTODO]
  148. public long GetBytes (int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
  149. {
  150. throw new NotImplementedException ();
  151. }
  152. [MonoTODO]
  153. public char GetChar (int ordinal)
  154. {
  155. throw new NotImplementedException ();
  156. }
  157. [MonoTODO]
  158. public long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length)
  159. {
  160. throw new NotImplementedException ();
  161. }
  162. [MonoTODO]
  163. [EditorBrowsableAttribute (EditorBrowsableState.Never)]
  164. public OdbcDataReader GetData (int ordinal)
  165. {
  166. throw new NotImplementedException ();
  167. }
  168. public string GetDataTypeName (int index)
  169. {
  170. return GetColumn(index).OdbcType.ToString();
  171. }
  172. public DateTime GetDate(int ordinal) {
  173. return GetDateTime(ordinal);
  174. }
  175. public DateTime GetDateTime (int ordinal)
  176. {
  177. return (DateTime) GetValue(ordinal);
  178. }
  179. [MonoTODO]
  180. public decimal GetDecimal (int ordinal)
  181. {
  182. throw new NotImplementedException ();
  183. }
  184. public double GetDouble (int ordinal)
  185. {
  186. return (double) GetValue(ordinal);
  187. }
  188. public Type GetFieldType (int index)
  189. {
  190. return GetColumn(index).DataType;
  191. }
  192. public float GetFloat (int ordinal)
  193. {
  194. return (float) GetValue(ordinal);
  195. }
  196. [MonoTODO]
  197. public Guid GetGuid (int ordinal)
  198. {
  199. throw new NotImplementedException ();
  200. }
  201. public short GetInt16 (int ordinal)
  202. {
  203. return (short) GetValue(ordinal);
  204. }
  205. public int GetInt32 (int ordinal)
  206. {
  207. return (int) GetValue(ordinal);
  208. }
  209. public long GetInt64 (int ordinal)
  210. {
  211. return (long) GetValue(ordinal);
  212. }
  213. public string GetName (int index)
  214. {
  215. if (currentRow == -1)
  216. return null;
  217. return GetColumn(index).ColumnName;
  218. }
  219. public int GetOrdinal (string name)
  220. {
  221. if (currentRow == -1)
  222. throw new IndexOutOfRangeException ();
  223. int i=ColIndex(name);
  224. if (i==-1)
  225. throw new IndexOutOfRangeException ();
  226. else
  227. return i;
  228. }
  229. [MonoTODO]
  230. public DataTable GetSchemaTable()
  231. {
  232. DataTable dataTableSchema = null;
  233. // Only Results from SQL SELECT Queries
  234. // get a DataTable for schema of the result
  235. // otherwise, DataTable is null reference
  236. if(cols.Length > 0)
  237. {
  238. dataTableSchema = new DataTable ();
  239. dataTableSchema.Columns.Add ("ColumnName", typeof (string));
  240. dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
  241. dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
  242. dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
  243. dataTableSchema.Columns.Add ("NumericScale", typeof (int));
  244. dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
  245. dataTableSchema.Columns.Add ("IsKey", typeof (bool));
  246. DataColumn dc = dataTableSchema.Columns["IsKey"];
  247. dc.AllowDBNull = true; // IsKey can have a DBNull
  248. dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
  249. dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
  250. dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
  251. dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
  252. dataTableSchema.Columns.Add ("DataType", typeof(Type));
  253. dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
  254. dataTableSchema.Columns.Add ("ProviderType", typeof (int));
  255. dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
  256. dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
  257. dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
  258. dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
  259. dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
  260. dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
  261. dataTableSchema.Columns.Add ("IsLong", typeof (bool));
  262. dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
  263. DataRow schemaRow;
  264. for (int i = 0; i < cols.Length; i += 1 )
  265. {
  266. OdbcColumn col=GetColumn(i);
  267. //Console.WriteLine("{0}:{1}:{2}",col.ColumnName,col.DataType,col.OdbcType);
  268. schemaRow = dataTableSchema.NewRow ();
  269. dataTableSchema.Rows.Add (schemaRow);
  270. schemaRow["ColumnName"] = col.ColumnName;
  271. schemaRow["ColumnOrdinal"] = i + 1;
  272. schemaRow["ColumnSize"] = col.MaxLength;
  273. schemaRow["NumericPrecision"] = 0;
  274. schemaRow["NumericScale"] = 0;
  275. // TODO: need to get KeyInfo
  276. schemaRow["IsUnique"] = false;
  277. schemaRow["IsKey"] = DBNull.Value;
  278. schemaRow["BaseCatalogName"] = "";
  279. schemaRow["BaseColumnName"] = col.ColumnName;
  280. schemaRow["BaseSchemaName"] = "";
  281. schemaRow["BaseTableName"] = "";
  282. schemaRow["DataType"] = col.DataType;
  283. schemaRow["AllowDBNull"] = col.AllowDBNull;
  284. schemaRow["ProviderType"] = (int) col.OdbcType;
  285. // TODO: all of these
  286. schemaRow["IsAliased"] = false;
  287. schemaRow["IsExpression"] = false;
  288. schemaRow["IsIdentity"] = false;
  289. schemaRow["IsAutoIncrement"] = false;
  290. schemaRow["IsRowVersion"] = false;
  291. schemaRow["IsHidden"] = false;
  292. schemaRow["IsLong"] = false;
  293. schemaRow["IsReadOnly"] = false;
  294. // FIXME: according to Brian,
  295. // this does not work on MS .NET
  296. // however, we need it for Mono
  297. // for now
  298. schemaRow.AcceptChanges();
  299. }
  300. }
  301. dataTableSchema.AcceptChanges();
  302. return dataTableSchema;
  303. }
  304. public string GetString (int ordinal)
  305. {
  306. return (string) GetValue(ordinal);
  307. }
  308. [MonoTODO]
  309. public TimeSpan GetTime (int ordinal)
  310. {
  311. throw new NotImplementedException ();
  312. }
  313. public object GetValue (int ordinal)
  314. {
  315. if (currentRow == -1)
  316. throw new IndexOutOfRangeException ();
  317. if (ordinal>cols.Length-1 || ordinal<0)
  318. throw new IndexOutOfRangeException ();
  319. OdbcReturn ret;
  320. int outsize=0, bufsize;
  321. byte[] buffer;
  322. OdbcColumn col=GetColumn(ordinal);
  323. object DataValue=null;
  324. ushort ColIndex=Convert.ToUInt16(ordinal+1);
  325. // Check cached values
  326. if (col.Value==null)
  327. {
  328. // odbc help file
  329. // mk:@MSITStore:C:\program%20files\Microsoft%20Data%20Access%20SDK\Docs\odbc.chm::/htm/odbcc_data_types.htm
  330. switch (col.OdbcType)
  331. {
  332. case OdbcType.Decimal:
  333. bufsize=50;
  334. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for decimal
  335. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  336. if (outsize!=-1)
  337. DataValue=Decimal.Parse(System.Text.Encoding.Default.GetString(buffer));
  338. break;
  339. case OdbcType.TinyInt:
  340. short short_data=0;
  341. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.TinyInt, ref short_data, 0, ref outsize);
  342. DataValue=short_data;
  343. break;
  344. case OdbcType.Int:
  345. int int_data=0;
  346. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Int, ref int_data, 0, ref outsize);
  347. DataValue=int_data;
  348. break;
  349. case OdbcType.BigInt:
  350. long long_data=0;
  351. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.BigInt, ref long_data, 0, ref outsize);
  352. DataValue=long_data;
  353. break;
  354. case OdbcType.NVarChar:
  355. bufsize=col.MaxLength*2+1; // Unicode is double byte
  356. buffer=new byte[bufsize];
  357. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.NVarChar, buffer, bufsize, ref outsize);
  358. if (outsize!=-1)
  359. DataValue=System.Text.Encoding.Unicode.GetString(buffer,0,outsize);
  360. break;
  361. case OdbcType.VarChar:
  362. bufsize=col.MaxLength+1;
  363. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  364. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  365. if (outsize!=-1)
  366. DataValue=System.Text.Encoding.Default.GetString(buffer,0,outsize);
  367. break;
  368. case OdbcType.Real:
  369. float float_data=0;
  370. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Real, ref float_data, 0, ref outsize);
  371. DataValue=float_data;
  372. break;
  373. case OdbcType.Timestamp:
  374. case OdbcType.DateTime:
  375. OdbcTimestamp ts_data=new OdbcTimestamp();
  376. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.DateTime, ref ts_data, 0, ref outsize);
  377. if (outsize!=-1) // This means SQL_NULL_DATA
  378. DataValue=new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  379. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  380. break;
  381. default:
  382. //Console.WriteLine("Fetching unsupported data type as string: "+col.OdbcType.ToString());
  383. bufsize=255;
  384. buffer=new byte[bufsize];
  385. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  386. DataValue=System.Text.Encoding.Default.GetString(buffer);
  387. break;
  388. }
  389. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  390. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  391. if (outsize==-1) // This means SQL_NULL_DATA
  392. col.Value=DBNull.Value;
  393. else
  394. col.Value=DataValue;
  395. }
  396. return col.Value;
  397. }
  398. public int GetValues (object[] values)
  399. {
  400. int numValues = 0;
  401. // copy values
  402. for (int i = 0; i < values.Length; i++) {
  403. if (i < FieldCount) {
  404. values[i] = GetValue(i);
  405. }
  406. else {
  407. values[i] = null;
  408. }
  409. }
  410. // get number of object instances in array
  411. if (values.Length < FieldCount)
  412. numValues = values.Length;
  413. else if (values.Length == FieldCount)
  414. numValues = FieldCount;
  415. else
  416. numValues = FieldCount;
  417. return numValues;
  418. }
  419. [MonoTODO]
  420. IDataReader IDataRecord.GetData (int ordinal)
  421. {
  422. throw new NotImplementedException ();
  423. }
  424. [MonoTODO]
  425. void IDisposable.Dispose ()
  426. {
  427. }
  428. [MonoTODO]
  429. IEnumerator IEnumerable.GetEnumerator ()
  430. {
  431. return new DbEnumerator (this);
  432. }
  433. public bool IsDBNull (int ordinal)
  434. {
  435. return (GetValue(ordinal) is DBNull);
  436. }
  437. public bool NextResult ()
  438. {
  439. OdbcReturn ret=libodbc.SQLFetch(hstmt);
  440. if (ret!=OdbcReturn.Success)
  441. currentRow=-1;
  442. else
  443. currentRow++;
  444. // Clear cached values from last record
  445. foreach (OdbcColumn col in cols)
  446. {
  447. if (col!=null)
  448. col.Value=null;
  449. }
  450. return (ret==OdbcReturn.Success);
  451. }
  452. public bool Read ()
  453. {
  454. return NextResult();
  455. }
  456. #endregion
  457. }
  458. }