OdbcDataReader.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. public OdbcDataReader GetData (int ordinal)
  164. {
  165. throw new NotImplementedException ();
  166. }
  167. public string GetDataTypeName (int index)
  168. {
  169. return GetColumn(index).OdbcType.ToString();
  170. }
  171. public DateTime GetDate(int ordinal) {
  172. return GetDateTime(ordinal);
  173. }
  174. public DateTime GetDateTime (int ordinal)
  175. {
  176. return (DateTime) GetValue(ordinal);
  177. }
  178. [MonoTODO]
  179. public decimal GetDecimal (int ordinal)
  180. {
  181. throw new NotImplementedException ();
  182. }
  183. public double GetDouble (int ordinal)
  184. {
  185. return (double) GetValue(ordinal);
  186. }
  187. public Type GetFieldType (int index)
  188. {
  189. return GetColumn(index).DataType;
  190. }
  191. public float GetFloat (int ordinal)
  192. {
  193. return (float) GetValue(ordinal);
  194. }
  195. [MonoTODO]
  196. public Guid GetGuid (int ordinal)
  197. {
  198. throw new NotImplementedException ();
  199. }
  200. public short GetInt16 (int ordinal)
  201. {
  202. return (short) GetValue(ordinal);
  203. }
  204. public int GetInt32 (int ordinal)
  205. {
  206. return (int) GetValue(ordinal);
  207. }
  208. public long GetInt64 (int ordinal)
  209. {
  210. return (long) GetValue(ordinal);
  211. }
  212. public string GetName (int index)
  213. {
  214. if (currentRow == -1)
  215. return null;
  216. return GetColumn(index).ColumnName;
  217. }
  218. public int GetOrdinal (string name)
  219. {
  220. if (currentRow == -1)
  221. throw new IndexOutOfRangeException ();
  222. int i=ColIndex(name);
  223. if (i==-1)
  224. throw new IndexOutOfRangeException ();
  225. else
  226. return i;
  227. }
  228. [MonoTODO]
  229. public DataTable GetSchemaTable()
  230. {
  231. DataTable dataTableSchema = null;
  232. // Only Results from SQL SELECT Queries
  233. // get a DataTable for schema of the result
  234. // otherwise, DataTable is null reference
  235. if(cols.Length > 0)
  236. {
  237. dataTableSchema = new DataTable ();
  238. dataTableSchema.Columns.Add ("ColumnName", typeof (string));
  239. dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
  240. dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
  241. dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
  242. dataTableSchema.Columns.Add ("NumericScale", typeof (int));
  243. dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
  244. dataTableSchema.Columns.Add ("IsKey", typeof (bool));
  245. DataColumn dc = dataTableSchema.Columns["IsKey"];
  246. dc.AllowDBNull = true; // IsKey can have a DBNull
  247. dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
  248. dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
  249. dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
  250. dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
  251. dataTableSchema.Columns.Add ("DataType", typeof(Type));
  252. dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
  253. dataTableSchema.Columns.Add ("ProviderType", typeof (int));
  254. dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
  255. dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
  256. dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
  257. dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
  258. dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
  259. dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
  260. dataTableSchema.Columns.Add ("IsLong", typeof (bool));
  261. dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
  262. DataRow schemaRow;
  263. for (int i = 0; i < cols.Length; i += 1 )
  264. {
  265. OdbcColumn col=GetColumn(i);
  266. //Console.WriteLine("{0}:{1}:{2}",col.ColumnName,col.DataType,col.OdbcType);
  267. schemaRow = dataTableSchema.NewRow ();
  268. dataTableSchema.Rows.Add (schemaRow);
  269. schemaRow["ColumnName"] = col.ColumnName;
  270. schemaRow["ColumnOrdinal"] = i + 1;
  271. schemaRow["ColumnSize"] = col.MaxLength;
  272. schemaRow["NumericPrecision"] = 0;
  273. schemaRow["NumericScale"] = 0;
  274. // TODO: need to get KeyInfo
  275. schemaRow["IsUnique"] = false;
  276. schemaRow["IsKey"] = DBNull.Value;
  277. schemaRow["BaseCatalogName"] = "";
  278. schemaRow["BaseColumnName"] = col.ColumnName;
  279. schemaRow["BaseSchemaName"] = "";
  280. schemaRow["BaseTableName"] = "";
  281. schemaRow["DataType"] = col.DataType;
  282. schemaRow["AllowDBNull"] = col.AllowDBNull;
  283. schemaRow["ProviderType"] = (int) col.OdbcType;
  284. // TODO: all of these
  285. schemaRow["IsAliased"] = false;
  286. schemaRow["IsExpression"] = false;
  287. schemaRow["IsIdentity"] = false;
  288. schemaRow["IsAutoIncrement"] = false;
  289. schemaRow["IsRowVersion"] = false;
  290. schemaRow["IsHidden"] = false;
  291. schemaRow["IsLong"] = false;
  292. schemaRow["IsReadOnly"] = false;
  293. // FIXME: according to Brian,
  294. // this does not work on MS .NET
  295. // however, we need it for Mono
  296. // for now
  297. schemaRow.AcceptChanges();
  298. }
  299. }
  300. dataTableSchema.AcceptChanges();
  301. return dataTableSchema;
  302. }
  303. public string GetString (int ordinal)
  304. {
  305. return (string) GetValue(ordinal);
  306. }
  307. [MonoTODO]
  308. public TimeSpan GetTime (int ordinal)
  309. {
  310. throw new NotImplementedException ();
  311. }
  312. public object GetValue (int ordinal)
  313. {
  314. if (currentRow == -1)
  315. throw new IndexOutOfRangeException ();
  316. if (ordinal>cols.Length-1 || ordinal<0)
  317. throw new IndexOutOfRangeException ();
  318. OdbcReturn ret;
  319. int outsize=0, bufsize;
  320. byte[] buffer;
  321. OdbcColumn col=GetColumn(ordinal);
  322. object DataValue=null;
  323. ushort ColIndex=Convert.ToUInt16(ordinal+1);
  324. // Check cached values
  325. if (col.Value==null)
  326. {
  327. // odbc help file
  328. // mk:@MSITStore:C:\program%20files\Microsoft%20Data%20Access%20SDK\Docs\odbc.chm::/htm/odbcc_data_types.htm
  329. switch (col.OdbcType)
  330. {
  331. case OdbcType.Decimal:
  332. bufsize=50;
  333. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for decimal
  334. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  335. if (outsize!=-1)
  336. DataValue=Decimal.Parse(System.Text.Encoding.Default.GetString(buffer));
  337. break;
  338. case OdbcType.TinyInt:
  339. short short_data=0;
  340. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.TinyInt, ref short_data, 0, ref outsize);
  341. DataValue=short_data;
  342. break;
  343. case OdbcType.Int:
  344. int int_data=0;
  345. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Int, ref int_data, 0, ref outsize);
  346. DataValue=int_data;
  347. break;
  348. case OdbcType.BigInt:
  349. long long_data=0;
  350. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.BigInt, ref long_data, 0, ref outsize);
  351. DataValue=long_data;
  352. break;
  353. case OdbcType.NVarChar:
  354. bufsize=col.MaxLength*2+1; // Unicode is double byte
  355. buffer=new byte[bufsize];
  356. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.NVarChar, buffer, bufsize, ref outsize);
  357. if (outsize!=-1)
  358. DataValue=System.Text.Encoding.Unicode.GetString(buffer,0,outsize);
  359. break;
  360. case OdbcType.VarChar:
  361. bufsize=col.MaxLength+1;
  362. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  363. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  364. if (outsize!=-1)
  365. DataValue=System.Text.Encoding.Default.GetString(buffer,0,outsize);
  366. break;
  367. case OdbcType.Real:
  368. float float_data=0;
  369. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Real, ref float_data, 0, ref outsize);
  370. DataValue=float_data;
  371. break;
  372. case OdbcType.Timestamp:
  373. case OdbcType.DateTime:
  374. OdbcTimestamp ts_data=new OdbcTimestamp();
  375. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.DateTime, ref ts_data, 0, ref outsize);
  376. if (outsize!=-1) // This means SQL_NULL_DATA
  377. DataValue=new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  378. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  379. break;
  380. default:
  381. //Console.WriteLine("Fetching unsupported data type as string: "+col.OdbcType.ToString());
  382. bufsize=255;
  383. buffer=new byte[bufsize];
  384. ret=libodbc.SQLGetData(hstmt, ColIndex, OdbcType.Char, buffer, bufsize, ref outsize);
  385. DataValue=System.Text.Encoding.Default.GetString(buffer);
  386. break;
  387. }
  388. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  389. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  390. if (outsize==-1) // This means SQL_NULL_DATA
  391. col.Value=DBNull.Value;
  392. else
  393. col.Value=DataValue;
  394. }
  395. return col.Value;
  396. }
  397. public int GetValues (object[] values)
  398. {
  399. int numValues = 0;
  400. // copy values
  401. for (int i = 0; i < values.Length; i++) {
  402. if (i < FieldCount) {
  403. values[i] = GetValue(i);
  404. }
  405. else {
  406. values[i] = null;
  407. }
  408. }
  409. // get number of object instances in array
  410. if (values.Length < FieldCount)
  411. numValues = values.Length;
  412. else if (values.Length == FieldCount)
  413. numValues = FieldCount;
  414. else
  415. numValues = FieldCount;
  416. return numValues;
  417. }
  418. [MonoTODO]
  419. IDataReader IDataRecord.GetData (int ordinal)
  420. {
  421. throw new NotImplementedException ();
  422. }
  423. [MonoTODO]
  424. void IDisposable.Dispose ()
  425. {
  426. }
  427. [MonoTODO]
  428. IEnumerator IEnumerable.GetEnumerator ()
  429. {
  430. return new DbEnumerator (this);
  431. }
  432. public bool IsDBNull (int ordinal)
  433. {
  434. return (GetValue(ordinal) is DBNull);
  435. }
  436. public bool NextResult ()
  437. {
  438. OdbcReturn ret=libodbc.SQLFetch(hstmt);
  439. if (ret!=OdbcReturn.Success)
  440. currentRow=-1;
  441. else
  442. currentRow++;
  443. // Clear cached values from last record
  444. foreach (OdbcColumn col in cols)
  445. {
  446. if (col!=null)
  447. col.Value=null;
  448. }
  449. return (ret==OdbcReturn.Success);
  450. }
  451. public bool Read ()
  452. {
  453. return NextResult();
  454. }
  455. #endregion
  456. }
  457. }