OdbcDataReader.cs 13 KB

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