OdbcDataReader.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. //
  2. // System.Data.Odbc.OdbcDataReader
  3. //
  4. // Author:
  5. // Brian Ritchie ([email protected])
  6. // Daniel Morgan <[email protected]>
  7. // Sureshkumar T <[email protected]> (2004)
  8. //
  9. // Copyright (C) Brian Ritchie, 2002
  10. // Copyright (C) Daniel Morgan, 2002
  11. //
  12. //
  13. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  14. //
  15. // Permission is hereby granted, free of charge, to any person obtaining
  16. // a copy of this software and associated documentation files (the
  17. // "Software"), to deal in the Software without restriction, including
  18. // without limitation the rights to use, copy, modify, merge, publish,
  19. // distribute, sublicense, and/or sell copies of the Software, and to
  20. // permit persons to whom the Software is furnished to do so, subject to
  21. // the following conditions:
  22. //
  23. // The above copyright notice and this permission notice shall be
  24. // included in all copies or substantial portions of the Software.
  25. //
  26. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  27. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  29. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  30. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  31. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  32. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  33. //
  34. using System.Collections;
  35. using System.ComponentModel;
  36. using System.Data;
  37. using System.Data.Common;
  38. #if NET_2_0
  39. using System.Data.ProviderBase;
  40. #endif // NET_2_0
  41. using System.Text;
  42. namespace System.Data.Odbc
  43. {
  44. #if NET_2_0
  45. public sealed class OdbcDataReader : DbDataReaderBase
  46. #else
  47. public sealed class OdbcDataReader : MarshalByRefObject, IDataReader, IDisposable, IDataRecord, IEnumerable
  48. #endif
  49. {
  50. #region Fields
  51. private OdbcCommand command;
  52. private bool open;
  53. private int currentRow;
  54. private OdbcColumn[] cols;
  55. private IntPtr hstmt;
  56. private int _recordsAffected = -1;
  57. bool disposed = false;
  58. private DataTable _dataTableSchema;
  59. #if ONLY_1_1
  60. private CommandBehavior behavior;
  61. #endif // ONLY_1_1
  62. #endregion
  63. #region Constructors
  64. internal OdbcDataReader (OdbcCommand command, CommandBehavior behavior)
  65. #if NET_2_0
  66. : base (behavior)
  67. #endif // NET_2_0
  68. {
  69. this.command = command;
  70. #if ONLY_1_1
  71. this.CommandBehavior=behavior;
  72. #endif // ONLY_1_1
  73. open = true;
  74. currentRow = -1;
  75. hstmt=command.hStmt;
  76. // Init columns array;
  77. short colcount=0;
  78. libodbc.SQLNumResultCols(hstmt, ref colcount);
  79. cols=new OdbcColumn[colcount];
  80. GetSchemaTable ();
  81. }
  82. internal OdbcDataReader (OdbcCommand command, CommandBehavior behavior,
  83. int recordAffected) : this (command, behavior)
  84. {
  85. _recordsAffected = recordAffected;
  86. }
  87. #endregion
  88. #region Properties
  89. #if ONLY_1_1
  90. private CommandBehavior CommandBehavior
  91. {
  92. get { return behavior; }
  93. set { value = behavior; }
  94. }
  95. #endif // ONLY_1_1
  96. #if NET_2_0
  97. [MonoTODO]
  98. public override int VisibleFieldCount
  99. {
  100. get { throw new NotImplementedException (); }
  101. }
  102. [MonoTODO]
  103. protected override bool IsValidRow
  104. {
  105. get { throw new NotImplementedException (); }
  106. }
  107. #endif // NET_2_0
  108. public
  109. #if NET_2_0
  110. override
  111. #endif // NET_2_0
  112. int Depth {
  113. get {
  114. return 0; // no nested selects supported
  115. }
  116. }
  117. public
  118. #if NET_2_0
  119. override
  120. #endif // NET_2_0
  121. int FieldCount {
  122. get {
  123. return cols.Length;
  124. }
  125. }
  126. public
  127. #if NET_2_0
  128. override
  129. #endif // NET_2_0
  130. bool IsClosed {
  131. get {
  132. return !open;
  133. }
  134. }
  135. public
  136. #if NET_2_0
  137. override
  138. #endif // NET_2_0
  139. object this[string name] {
  140. get {
  141. int pos;
  142. if (currentRow == -1)
  143. throw new InvalidOperationException ();
  144. pos = ColIndex(name);
  145. if (pos == -1)
  146. throw new IndexOutOfRangeException ();
  147. return this[pos];
  148. }
  149. }
  150. public
  151. #if NET_2_0
  152. override
  153. #endif // NET_2_0
  154. object this[int index] {
  155. get {
  156. return (object) GetValue (index);
  157. }
  158. }
  159. [MonoTODO]
  160. public
  161. #if NET_2_0
  162. override
  163. #endif // NET_2_0
  164. int RecordsAffected {
  165. get {
  166. return _recordsAffected;
  167. }
  168. }
  169. [MonoTODO]
  170. public
  171. #if NET_2_0
  172. override
  173. #endif // NET_2_0
  174. bool HasRows {
  175. get { throw new NotImplementedException(); }
  176. }
  177. #endregion
  178. #region Methods
  179. private int ColIndex(string colname)
  180. {
  181. int i=0;
  182. foreach (OdbcColumn col in cols)
  183. {
  184. if (col != null) {
  185. if (col.ColumnName == colname)
  186. return i;
  187. if (String.Compare (col.ColumnName, colname, true) == 0)
  188. return i;
  189. }
  190. i++;
  191. }
  192. return -1;
  193. }
  194. // Dynamically load column descriptions as needed.
  195. private OdbcColumn GetColumn(int ordinal)
  196. {
  197. if (cols[ordinal]==null)
  198. {
  199. short bufsize=255;
  200. byte[] colname_buffer=new byte[bufsize];
  201. string colname;
  202. short colname_size=0;
  203. uint ColSize=0;
  204. short DecDigits=0, Nullable=0, dt=0;
  205. OdbcReturn ret=libodbc.SQLDescribeCol(hstmt, Convert.ToUInt16(ordinal+1),
  206. colname_buffer, bufsize, ref colname_size, ref dt, ref ColSize,
  207. ref DecDigits, ref Nullable);
  208. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  209. throw new OdbcException(new OdbcError("SQLDescribeCol",OdbcHandleType.Stmt,hstmt));
  210. colname=System.Text.Encoding.Default.GetString(colname_buffer);
  211. colname=colname.Replace((char) 0,' ').Trim();
  212. OdbcColumn c=new OdbcColumn(colname, (SQL_TYPE) dt);
  213. c.AllowDBNull=(Nullable!=0);
  214. c.Digits=DecDigits;
  215. if (c.IsStringType)
  216. c.MaxLength=(int)ColSize;
  217. cols[ordinal]=c;
  218. }
  219. return cols[ordinal];
  220. }
  221. public
  222. #if NET_2_0
  223. override
  224. #endif // NET_2_0
  225. void Close ()
  226. {
  227. // FIXME : have to implement output parameter binding
  228. open = false;
  229. currentRow = -1;
  230. this.command.FreeIfNotPrepared ();
  231. if ((this.CommandBehavior & CommandBehavior.CloseConnection)==CommandBehavior.CloseConnection) {
  232. this.command.Connection.Close();
  233. }
  234. }
  235. ~OdbcDataReader ()
  236. {
  237. this.Dispose (false);
  238. }
  239. public
  240. #if NET_2_0
  241. override
  242. #endif // NET_2_0
  243. bool GetBoolean (int ordinal)
  244. {
  245. return (bool) GetValue(ordinal);
  246. }
  247. public
  248. #if NET_2_0
  249. override
  250. #endif // NET_2_0
  251. byte GetByte (int ordinal)
  252. {
  253. return (byte) Convert.ToByte(GetValue(ordinal));
  254. }
  255. public
  256. #if NET_2_0
  257. override
  258. #endif // NET_2_0
  259. long GetBytes (int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
  260. {
  261. OdbcReturn ret = OdbcReturn.Error;
  262. bool copyBuffer = false;
  263. int returnVal = 0, outsize = 0;
  264. byte [] tbuff = new byte [length+1];
  265. length = buffer == null ? 0 : length;
  266. ret=libodbc.SQLGetData (hstmt, (ushort) (ordinal+1), SQL_C_TYPE.BINARY, tbuff, length,
  267. ref outsize);
  268. if (ret == OdbcReturn.NoData)
  269. return 0;
  270. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  271. throw new OdbcException (new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt));
  272. OdbcError odbcErr = null;
  273. if ( (ret == OdbcReturn.SuccessWithInfo))
  274. odbcErr = new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt);
  275. if (buffer == null)
  276. return outsize; //if buffer is null,return length of the field
  277. if (ret == OdbcReturn.SuccessWithInfo) {
  278. if (outsize == (int) OdbcLengthIndicator.NoTotal)
  279. copyBuffer = true;
  280. else if (outsize == (int) OdbcLengthIndicator.NullData) {
  281. copyBuffer = false;
  282. returnVal = -1;
  283. } else {
  284. string sqlstate = odbcErr.SQLState;
  285. //SQLState: String Data, Right truncated
  286. if (sqlstate != libodbc.SQLSTATE_RIGHT_TRUNC)
  287. throw new OdbcException ( odbcErr);
  288. copyBuffer = true;
  289. }
  290. } else {
  291. copyBuffer = outsize == -1 ? false : true;
  292. returnVal = outsize;
  293. }
  294. if (copyBuffer) {
  295. int i = 0;
  296. while (tbuff [i] != libodbc.C_NULL) {
  297. buffer [bufferIndex + i] = tbuff [i];
  298. i++;
  299. }
  300. returnVal = i;
  301. }
  302. return returnVal;
  303. }
  304. [MonoTODO]
  305. public
  306. #if NET_2_0
  307. override
  308. #endif // NET_2_0
  309. char GetChar (int ordinal)
  310. {
  311. throw new NotImplementedException ();
  312. }
  313. [MonoTODO]
  314. public
  315. #if NET_2_0
  316. override
  317. #endif // NET_2_0
  318. long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length)
  319. {
  320. throw new NotImplementedException ();
  321. }
  322. [MonoTODO]
  323. [EditorBrowsableAttribute (EditorBrowsableState.Never)]
  324. public
  325. #if NET_2_0
  326. new
  327. #endif // NET_2_0
  328. IDataReader GetData (int ordinal)
  329. {
  330. throw new NotImplementedException ();
  331. }
  332. public
  333. #if NET_2_0
  334. override
  335. #endif // NET_2_0
  336. string GetDataTypeName (int index)
  337. {
  338. return GetColumn(index).OdbcType.ToString();
  339. }
  340. public DateTime GetDate(int ordinal) {
  341. return GetDateTime(ordinal);
  342. }
  343. public
  344. #if NET_2_0
  345. override
  346. #endif // NET_2_0
  347. DateTime GetDateTime (int ordinal)
  348. {
  349. return (DateTime) GetValue(ordinal);
  350. }
  351. [MonoTODO]
  352. public
  353. #if NET_2_0
  354. override
  355. #endif // NET_2_0
  356. decimal GetDecimal (int ordinal)
  357. {
  358. throw new NotImplementedException ();
  359. }
  360. public
  361. #if NET_2_0
  362. override
  363. #endif // NET_2_0
  364. double GetDouble (int ordinal)
  365. {
  366. return (double) GetValue(ordinal);
  367. }
  368. public
  369. #if NET_2_0
  370. override
  371. #endif // NET_2_0
  372. Type GetFieldType (int index)
  373. {
  374. return GetColumn(index).DataType;
  375. }
  376. public
  377. #if NET_2_0
  378. override
  379. #endif // NET_2_0
  380. float GetFloat (int ordinal)
  381. {
  382. return (float) GetValue(ordinal);
  383. }
  384. [MonoTODO]
  385. public
  386. #if NET_2_0
  387. override
  388. #endif // NET_2_0
  389. Guid GetGuid (int ordinal)
  390. {
  391. throw new NotImplementedException ();
  392. }
  393. public
  394. #if NET_2_0
  395. override
  396. #endif // NET_2_0
  397. short GetInt16 (int ordinal)
  398. {
  399. return (short) GetValue(ordinal);
  400. }
  401. public
  402. #if NET_2_0
  403. override
  404. #endif // NET_2_0
  405. int GetInt32 (int ordinal)
  406. {
  407. return (int) GetValue(ordinal);
  408. }
  409. public
  410. #if NET_2_0
  411. override
  412. #endif // NET_2_0
  413. long GetInt64 (int ordinal)
  414. {
  415. return (long) GetValue(ordinal);
  416. }
  417. public
  418. #if NET_2_0
  419. override
  420. #endif // NET_2_0
  421. string GetName (int index)
  422. {
  423. return GetColumn(index).ColumnName;
  424. }
  425. public
  426. #if NET_2_0
  427. override
  428. #endif // NET_2_0
  429. int GetOrdinal (string name)
  430. {
  431. int i=ColIndex(name);
  432. if (i==-1)
  433. throw new IndexOutOfRangeException ();
  434. else
  435. return i;
  436. }
  437. [MonoTODO]
  438. public
  439. #if NET_2_0
  440. override
  441. #endif // NET_2_0
  442. DataTable GetSchemaTable()
  443. {
  444. // FIXME :
  445. // * Map OdbcType to System.Type and assign to DataType.
  446. // This will eliminate the need for IsStringType in
  447. // OdbcColumn.
  448. if (_dataTableSchema != null)
  449. return _dataTableSchema;
  450. DataTable dataTableSchema = null;
  451. // Only Results from SQL SELECT Queries
  452. // get a DataTable for schema of the result
  453. // otherwise, DataTable is null reference
  454. if(cols.Length > 0)
  455. {
  456. dataTableSchema = new DataTable ();
  457. dataTableSchema.Columns.Add ("ColumnName", typeof (string));
  458. dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
  459. dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
  460. dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
  461. dataTableSchema.Columns.Add ("NumericScale", typeof (int));
  462. dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
  463. dataTableSchema.Columns.Add ("IsKey", typeof (bool));
  464. DataColumn dc = dataTableSchema.Columns["IsKey"];
  465. dc.AllowDBNull = true; // IsKey can have a DBNull
  466. dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
  467. dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
  468. dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
  469. dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
  470. dataTableSchema.Columns.Add ("DataType", typeof(Type));
  471. dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
  472. dataTableSchema.Columns.Add ("ProviderType", typeof (int));
  473. dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
  474. dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
  475. dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
  476. dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
  477. dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
  478. dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
  479. dataTableSchema.Columns.Add ("IsLong", typeof (bool));
  480. dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
  481. DataRow schemaRow;
  482. for (int i = 0; i < cols.Length; i += 1 )
  483. {
  484. string baseTableName = String.Empty;
  485. bool isKey = false;
  486. OdbcColumn col=GetColumn(i);
  487. schemaRow = dataTableSchema.NewRow ();
  488. dataTableSchema.Rows.Add (schemaRow);
  489. schemaRow ["ColumnName"] = col.ColumnName;
  490. schemaRow ["ColumnOrdinal"] = i;
  491. schemaRow ["ColumnSize"] = col.MaxLength;
  492. schemaRow ["NumericPrecision"] = GetColumnAttribute (i+1, FieldIdentifier.Precision);
  493. schemaRow ["NumericScale"] = GetColumnAttribute (i+1, FieldIdentifier.Scale);
  494. schemaRow ["BaseTableName"] = GetColumnAttributeStr (i+1, FieldIdentifier.TableName);
  495. schemaRow ["BaseSchemaName"] = GetColumnAttributeStr (i+1, FieldIdentifier.SchemaName);
  496. schemaRow ["BaseCatalogName"] = GetColumnAttributeStr (1+1, FieldIdentifier.CatelogName);
  497. schemaRow ["BaseColumnName"] = GetColumnAttributeStr (i+1, FieldIdentifier.BaseColumnName);
  498. schemaRow ["DataType"] = col.DataType;
  499. schemaRow ["IsUnique"] = false;
  500. schemaRow ["IsKey"] = DBNull.Value;
  501. schemaRow ["AllowDBNull"] = GetColumnAttribute (1+1, FieldIdentifier.Nullable) != libodbc.SQL_NO_NULLS;
  502. schemaRow ["ProviderType"] = (int) col.OdbcType;
  503. schemaRow ["IsAutoIncrement"] = GetColumnAttribute (i+1, FieldIdentifier.AutoUniqueValue) == libodbc.SQL_TRUE;
  504. schemaRow ["IsExpression"] = schemaRow.IsNull ("BaseTableName") || (string) schemaRow ["BaseTableName"] == String.Empty;
  505. schemaRow ["IsAliased"] = (string) schemaRow ["BaseColumnName"] != (string) schemaRow ["ColumnName"];
  506. schemaRow ["IsReadOnly"] = ((bool) schemaRow ["IsExpression"]
  507. || GetColumnAttribute (i+1, FieldIdentifier.Updatable) == libodbc.SQL_ATTR_READONLY);
  508. // FIXME: all of these
  509. schemaRow ["IsIdentity"] = false;
  510. schemaRow ["IsRowVersion"] = false;
  511. schemaRow ["IsHidden"] = false;
  512. schemaRow ["IsLong"] = false;
  513. // FIXME: according to Brian,
  514. // this does not work on MS .NET
  515. // however, we need it for Mono
  516. // for now
  517. // schemaRow.AcceptChanges();
  518. }
  519. // set primary keys
  520. DataRow [] rows = dataTableSchema.Select ("BaseTableName <> ''",
  521. "BaseCatalogName, BaseSchemaName, BaseTableName ASC");
  522. string lastTableName = String.Empty,
  523. lastSchemaName = String.Empty,
  524. lastCatalogName = String.Empty;
  525. string [] keys = null; // assumed to be sorted.
  526. foreach (DataRow row in rows) {
  527. string tableName = (string) row ["BaseTableName"];
  528. string schemaName = (string) row ["BaseSchemaName"];
  529. string catalogName = (string) row ["BaseCatalogName"];
  530. if (tableName != lastTableName || schemaName != lastSchemaName
  531. || catalogName != lastCatalogName)
  532. keys = GetPrimaryKeys (catalogName, schemaName, tableName);
  533. if (keys != null &&
  534. Array.BinarySearch (keys, (string) row ["BaseColumnName"]) >= 0) {
  535. row ["IsKey"] = true;
  536. row ["IsUnique"] = true;
  537. row ["AllowDBNull"] = false;
  538. GetColumn ( ColIndex ( (string) row ["ColumnName"])).AllowDBNull = false;
  539. }
  540. lastTableName = tableName;
  541. lastSchemaName = schemaName;
  542. lastCatalogName = catalogName;
  543. }
  544. dataTableSchema.AcceptChanges();
  545. }
  546. return (_dataTableSchema = dataTableSchema);
  547. }
  548. public
  549. #if NET_2_0
  550. override
  551. #endif // NET_2_0
  552. string GetString (int ordinal)
  553. {
  554. return (string) GetValue(ordinal);
  555. }
  556. [MonoTODO]
  557. public TimeSpan GetTime (int ordinal)
  558. {
  559. throw new NotImplementedException ();
  560. }
  561. public
  562. #if NET_2_0
  563. override
  564. #endif // NET_2_0
  565. object GetValue (int ordinal)
  566. {
  567. if (currentRow == -1)
  568. throw new IndexOutOfRangeException ();
  569. if (ordinal>cols.Length-1 || ordinal<0)
  570. throw new IndexOutOfRangeException ();
  571. OdbcReturn ret;
  572. int outsize=0, bufsize;
  573. byte[] buffer;
  574. OdbcColumn col=GetColumn(ordinal);
  575. object DataValue=null;
  576. ushort ColIndex=Convert.ToUInt16(ordinal+1);
  577. // Check cached values
  578. if (col.Value==null) {
  579. // odbc help file
  580. // mk:@MSITStore:C:\program%20files\Microsoft%20Data%20Access%20SDK\Docs\odbc.chm::/htm/odbcc_data_types.htm
  581. switch (col.OdbcType) {
  582. case OdbcType.Bit:
  583. short bit_data = 0;
  584. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref bit_data, 0, ref outsize);
  585. if (outsize != (int) OdbcLengthIndicator.NullData)
  586. DataValue = bit_data == 0 ? "False" : "True";
  587. break;
  588. case OdbcType.Numeric:
  589. case OdbcType.Decimal:
  590. bufsize=50;
  591. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for decimal.
  592. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  593. if (outsize!=-1) {
  594. byte[] temp = new byte[outsize];
  595. for (int i=0;i<outsize;i++)
  596. temp[i]=buffer[i];
  597. DataValue=Decimal.Parse(System.Text.Encoding.Default.GetString(temp));
  598. }
  599. break;
  600. case OdbcType.TinyInt:
  601. short short_data=0;
  602. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref short_data, 0, ref outsize);
  603. DataValue=System.Convert.ToByte(short_data);
  604. break;
  605. case OdbcType.Int:
  606. int int_data=0;
  607. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref int_data, 0, ref outsize);
  608. DataValue=int_data;
  609. break;
  610. case OdbcType.SmallInt:
  611. short sint_data=0;
  612. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref sint_data, 0, ref outsize);
  613. DataValue=sint_data;
  614. break;
  615. case OdbcType.BigInt:
  616. long long_data=0;
  617. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref long_data, 0, ref outsize);
  618. DataValue=long_data;
  619. break;
  620. case OdbcType.NVarChar:
  621. bufsize=col.MaxLength*2+1; // Unicode is double byte
  622. buffer=new byte[bufsize];
  623. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  624. if (outsize!=-1)
  625. DataValue=System.Text.Encoding.Unicode.GetString(buffer,0,outsize);
  626. break;
  627. case OdbcType.VarChar:
  628. bufsize=col.MaxLength+1;
  629. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  630. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  631. if (outsize!=-1)
  632. DataValue=System.Text.Encoding.Default.GetString(buffer,0,outsize);
  633. break;
  634. case OdbcType.Real:
  635. float float_data=0;
  636. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref float_data, 0, ref outsize);
  637. DataValue=float_data;
  638. break;
  639. case OdbcType.Double:
  640. double double_data=0;
  641. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref double_data, 0, ref outsize);
  642. DataValue=double_data;
  643. break;
  644. case OdbcType.Timestamp:
  645. case OdbcType.DateTime:
  646. case OdbcType.Date:
  647. case OdbcType.Time:
  648. OdbcTimestamp ts_data=new OdbcTimestamp();
  649. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref ts_data, 0, ref outsize);
  650. if (outsize!=-1) // This means SQL_NULL_DATA
  651. DataValue=new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  652. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  653. break;
  654. case OdbcType.Binary :
  655. case OdbcType.Image :
  656. bufsize = col.MaxLength + 1;
  657. buffer = new byte [bufsize];
  658. long read = GetBytes (ordinal, 0, buffer, 0, bufsize);
  659. ret = OdbcReturn.Success;
  660. DataValue = buffer;
  661. break;
  662. default:
  663. bufsize=255;
  664. buffer=new byte[bufsize];
  665. ret=libodbc.SQLGetData(hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  666. if (outsize != (int) OdbcLengthIndicator.NullData)
  667. if (! (ret == OdbcReturn.SuccessWithInfo
  668. && outsize == (int) OdbcLengthIndicator.NoTotal))
  669. DataValue=System.Text.Encoding.Default.GetString(buffer, 0, outsize);
  670. break;
  671. }
  672. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  673. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  674. if (outsize==-1) // This means SQL_NULL_DATA
  675. col.Value=DBNull.Value;
  676. else
  677. col.Value=DataValue;
  678. }
  679. return col.Value;
  680. }
  681. public
  682. #if NET_2_0
  683. override
  684. #endif // NET_2_0
  685. int GetValues (object[] values)
  686. {
  687. int numValues = 0;
  688. // copy values
  689. for (int i = 0; i < values.Length; i++) {
  690. if (i < FieldCount) {
  691. values[i] = GetValue(i);
  692. }
  693. else {
  694. values[i] = null;
  695. }
  696. }
  697. // get number of object instances in array
  698. if (values.Length < FieldCount)
  699. numValues = values.Length;
  700. else if (values.Length == FieldCount)
  701. numValues = FieldCount;
  702. else
  703. numValues = FieldCount;
  704. return numValues;
  705. }
  706. #if ONLY_1_1
  707. [MonoTODO]
  708. IDataReader IDataRecord.GetData (int ordinal)
  709. {
  710. throw new NotImplementedException ();
  711. }
  712. #if ONLY_1_1
  713. void IDisposable.Dispose ()
  714. {
  715. Dispose (true);
  716. GC.SuppressFinalize (this);
  717. }
  718. #else
  719. public override void Dispose ()
  720. {
  721. Dispose (true);
  722. GC.SuppressFinalize (this);
  723. }
  724. #endif
  725. IEnumerator IEnumerable.GetEnumerator ()
  726. {
  727. return new DbEnumerator (this);
  728. }
  729. #endif // ONLY_1_1
  730. private void Dispose (bool disposing)
  731. {
  732. if (disposed)
  733. return;
  734. if (disposing) {
  735. // dispose managed resources
  736. Close ();
  737. }
  738. command = null;
  739. cols = null;
  740. _dataTableSchema = null;
  741. disposed = true;
  742. }
  743. public
  744. #if NET_2_0
  745. override
  746. #endif // NET_2_0
  747. bool IsDBNull (int ordinal)
  748. {
  749. return (GetValue(ordinal) is DBNull);
  750. }
  751. /// <remarks>
  752. /// Move to the next result set.
  753. /// </remarks>
  754. public
  755. #if NET_2_0
  756. override
  757. #endif // NET_2_0
  758. bool NextResult ()
  759. {
  760. OdbcReturn ret = OdbcReturn.Success;
  761. ret = libodbc.SQLMoreResults (hstmt);
  762. if (ret == OdbcReturn.Success) {
  763. short colcount = 0;
  764. libodbc.SQLNumResultCols (hstmt, ref colcount);
  765. cols = new OdbcColumn [colcount];
  766. _dataTableSchema = null; // force fresh creation
  767. GetSchemaTable ();
  768. }
  769. return (ret==OdbcReturn.Success);
  770. }
  771. /// <remarks>
  772. /// Load the next row in the current result set.
  773. /// </remarks>
  774. private bool NextRow ()
  775. {
  776. OdbcReturn ret=libodbc.SQLFetch (hstmt);
  777. if (ret != OdbcReturn.Success)
  778. currentRow = -1;
  779. else
  780. currentRow++;
  781. // Clear cached values from last record
  782. foreach (OdbcColumn col in cols)
  783. {
  784. if (col != null)
  785. col.Value = null;
  786. }
  787. return (ret == OdbcReturn.Success);
  788. }
  789. private int GetColumnAttribute (int column, FieldIdentifier fieldId)
  790. {
  791. OdbcReturn ret = OdbcReturn.Error;
  792. byte [] buffer = new byte [255];
  793. int outsize = 0;
  794. int val = 0;
  795. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  796. buffer, buffer.Length,
  797. ref outsize, ref val);
  798. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  799. throw new OdbcException (new OdbcError ("SQLColAttribute",
  800. OdbcHandleType.Stmt,
  801. hstmt)
  802. );
  803. return val;
  804. }
  805. private string GetColumnAttributeStr (int column, FieldIdentifier fieldId)
  806. {
  807. OdbcReturn ret = OdbcReturn.Error;
  808. byte [] buffer = new byte [255];
  809. int outsize = 0;
  810. int val = 0;
  811. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  812. buffer, buffer.Length,
  813. ref outsize, ref val);
  814. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  815. throw new OdbcException (new OdbcError ("SQLColAttribute",
  816. OdbcHandleType.Stmt,
  817. hstmt)
  818. );
  819. string value = "";
  820. if (outsize > 0)
  821. value = Encoding.Default.GetString (buffer, 0, outsize);
  822. return value;
  823. }
  824. private string [] GetPrimaryKeys (string catalog, string schema, string table)
  825. {
  826. if (cols.Length <= 0)
  827. return new string [0];
  828. ArrayList keys = null;
  829. try {
  830. keys = GetPrimaryKeysBySQLPrimaryKey (catalog, schema, table);
  831. } catch (OdbcException){
  832. try {
  833. keys = GetPrimaryKeysBySQLStatistics (catalog, schema, table);
  834. } catch (OdbcException) {
  835. }
  836. }
  837. keys.Sort ();
  838. return (string []) keys.ToArray (typeof (string));
  839. }
  840. private ArrayList GetPrimaryKeysBySQLPrimaryKey (string catalog, string schema, string table)
  841. {
  842. ArrayList keys = new ArrayList ();
  843. IntPtr handle = IntPtr.Zero;
  844. OdbcReturn ret;
  845. try {
  846. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  847. command.Connection.hDbc, ref handle);
  848. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  849. throw new OdbcException(new OdbcError("SQLAllocHandle",
  850. OdbcHandleType.Dbc,
  851. command.Connection.hDbc));
  852. ret = libodbc.SQLPrimaryKeys (handle, catalog, -3,
  853. schema, -3,
  854. table, -3);
  855. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  856. throw new OdbcException (new OdbcError ("SQLPrimaryKeys", OdbcHandleType.Stmt, handle));
  857. int length = 0;
  858. byte [] primaryKey = new byte [255];
  859. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.CHAR, primaryKey, primaryKey.Length, ref length);
  860. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  861. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  862. int i = 0;
  863. while (true) {
  864. ret = libodbc.SQLFetch (handle);
  865. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  866. break;
  867. string pkey = Encoding.Default.GetString (primaryKey, 0, length);
  868. keys.Add (pkey);
  869. }
  870. } finally {
  871. if (handle != IntPtr.Zero) {
  872. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  873. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  874. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  875. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  876. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  877. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  878. }
  879. }
  880. return keys;
  881. }
  882. private unsafe ArrayList GetPrimaryKeysBySQLStatistics (string catalog, string schema, string table)
  883. {
  884. ArrayList keys = new ArrayList ();
  885. IntPtr handle = IntPtr.Zero;
  886. OdbcReturn ret;
  887. try {
  888. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  889. command.Connection.hDbc, ref handle);
  890. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  891. throw new OdbcException(new OdbcError("SQLAllocHandle",
  892. OdbcHandleType.Dbc,
  893. command.Connection.hDbc));
  894. ret = libodbc.SQLStatistics (handle, catalog, -3,
  895. schema, -3,
  896. table, -3,
  897. libodbc.SQL_INDEX_UNIQUE,
  898. libodbc.SQL_QUICK);
  899. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  900. throw new OdbcException (new OdbcError ("SQLStatistics", OdbcHandleType.Stmt, handle));
  901. // NON_UNIQUE
  902. int nonUniqueLength = 0;
  903. short nonUnique = libodbc.SQL_FALSE;
  904. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.SHORT, ref (short) nonUnique, sizeof (short), ref nonUniqueLength);
  905. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  906. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  907. // COLUMN_NAME
  908. int length = 0;
  909. byte [] colName = new byte [255];
  910. ret = libodbc.SQLBindCol (handle, 9, SQL_C_TYPE.CHAR, colName, colName.Length, ref length);
  911. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  912. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  913. int i = 0;
  914. while (true) {
  915. ret = libodbc.SQLFetch (handle);
  916. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  917. break;
  918. if (nonUnique == libodbc.SQL_TRUE) {
  919. string pkey = Encoding.Default.GetString (colName, 0, length);
  920. keys.Add (pkey);
  921. break;
  922. }
  923. }
  924. } finally {
  925. if (handle != IntPtr.Zero) {
  926. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  927. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  928. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  929. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  930. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  931. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  932. }
  933. }
  934. return keys;
  935. }
  936. public
  937. #if NET_2_0
  938. override
  939. #endif // NET_2_0
  940. bool Read ()
  941. {
  942. return NextRow ();
  943. }
  944. #if NET_2_0
  945. [MonoTODO]
  946. public override object GetProviderSpecificValue (int i)
  947. {
  948. throw new NotImplementedException ();
  949. }
  950. [MonoTODO]
  951. public override int GetProviderSpecificValues (object[] values)
  952. {
  953. throw new NotImplementedException ();
  954. }
  955. [MonoTODO]
  956. public override Type GetFieldProviderSpecificType (int i)
  957. {
  958. throw new NotImplementedException ();
  959. }
  960. #endif // NET_2_0
  961. #endregion
  962. }
  963. }