OdbcDataReader.cs 13 KB

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