OdbcDataReader.cs 13 KB

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