OdbcDataReader.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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 (i+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 (i+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. // FIXME : use Numeric.
  593. ret=libodbc.SQLGetData(hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  594. if (outsize!=-1) {
  595. byte[] temp = new byte[outsize];
  596. for (int i=0;i<outsize;i++)
  597. temp[i]=buffer[i];
  598. DataValue=Decimal.Parse(System.Text.Encoding.Default.GetString(temp));
  599. }
  600. break;
  601. case OdbcType.TinyInt:
  602. short short_data=0;
  603. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref short_data, 0, ref outsize);
  604. DataValue=System.Convert.ToByte(short_data);
  605. break;
  606. case OdbcType.Int:
  607. int int_data=0;
  608. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref int_data, 0, ref outsize);
  609. DataValue=int_data;
  610. break;
  611. case OdbcType.SmallInt:
  612. short sint_data=0;
  613. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref sint_data, 0, ref outsize);
  614. DataValue=sint_data;
  615. break;
  616. case OdbcType.BigInt:
  617. long long_data=0;
  618. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref long_data, 0, ref outsize);
  619. DataValue=long_data;
  620. break;
  621. case OdbcType.NText:
  622. case OdbcType.NVarChar:
  623. bufsize=col.MaxLength*2+1; // Unicode is double byte
  624. buffer=new byte[bufsize];
  625. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  626. if (outsize!=-1)
  627. DataValue=System.Text.Encoding.Unicode.GetString(buffer,0,outsize);
  628. break;
  629. case OdbcType.Text:
  630. case OdbcType.VarChar:
  631. bufsize=col.MaxLength+1;
  632. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  633. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  634. if (outsize!=-1)
  635. DataValue=System.Text.Encoding.Default.GetString(buffer,0,outsize);
  636. break;
  637. case OdbcType.Real:
  638. float float_data=0;
  639. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref float_data, 0, ref outsize);
  640. DataValue=float_data;
  641. break;
  642. case OdbcType.Double:
  643. double double_data=0;
  644. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref double_data, 0, ref outsize);
  645. DataValue=double_data;
  646. break;
  647. case OdbcType.Timestamp:
  648. case OdbcType.DateTime:
  649. case OdbcType.Date:
  650. case OdbcType.Time:
  651. OdbcTimestamp ts_data=new OdbcTimestamp();
  652. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref ts_data, 0, ref outsize);
  653. if (outsize!=-1) // This means SQL_NULL_DATA
  654. DataValue=new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  655. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  656. break;
  657. case OdbcType.Binary :
  658. case OdbcType.Image :
  659. bufsize = col.MaxLength + 1;
  660. buffer = new byte [bufsize];
  661. long read = GetBytes (ordinal, 0, buffer, 0, bufsize);
  662. ret = OdbcReturn.Success;
  663. DataValue = buffer;
  664. break;
  665. default:
  666. bufsize=255;
  667. buffer=new byte[bufsize];
  668. ret=libodbc.SQLGetData(hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  669. if (outsize != (int) OdbcLengthIndicator.NullData)
  670. if (! (ret == OdbcReturn.SuccessWithInfo
  671. && outsize == (int) OdbcLengthIndicator.NoTotal))
  672. DataValue=System.Text.Encoding.Default.GetString(buffer, 0, outsize);
  673. break;
  674. }
  675. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  676. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  677. if (outsize==-1) // This means SQL_NULL_DATA
  678. col.Value=DBNull.Value;
  679. else
  680. col.Value=DataValue;
  681. }
  682. return col.Value;
  683. }
  684. public
  685. #if NET_2_0
  686. override
  687. #endif // NET_2_0
  688. int GetValues (object[] values)
  689. {
  690. int numValues = 0;
  691. // copy values
  692. for (int i = 0; i < values.Length; i++) {
  693. if (i < FieldCount) {
  694. values[i] = GetValue(i);
  695. }
  696. else {
  697. values[i] = null;
  698. }
  699. }
  700. // get number of object instances in array
  701. if (values.Length < FieldCount)
  702. numValues = values.Length;
  703. else if (values.Length == FieldCount)
  704. numValues = FieldCount;
  705. else
  706. numValues = FieldCount;
  707. return numValues;
  708. }
  709. #if ONLY_1_1
  710. [MonoTODO]
  711. IDataReader IDataRecord.GetData (int ordinal)
  712. {
  713. throw new NotImplementedException ();
  714. }
  715. #if ONLY_1_1
  716. void IDisposable.Dispose ()
  717. {
  718. Dispose (true);
  719. GC.SuppressFinalize (this);
  720. }
  721. #else
  722. public override void Dispose ()
  723. {
  724. Dispose (true);
  725. GC.SuppressFinalize (this);
  726. }
  727. #endif
  728. IEnumerator IEnumerable.GetEnumerator ()
  729. {
  730. return new DbEnumerator (this);
  731. }
  732. #endif // ONLY_1_1
  733. private void Dispose (bool disposing)
  734. {
  735. if (disposed)
  736. return;
  737. if (disposing) {
  738. // dispose managed resources
  739. Close ();
  740. }
  741. command = null;
  742. cols = null;
  743. _dataTableSchema = null;
  744. disposed = true;
  745. }
  746. public
  747. #if NET_2_0
  748. override
  749. #endif // NET_2_0
  750. bool IsDBNull (int ordinal)
  751. {
  752. return (GetValue(ordinal) is DBNull);
  753. }
  754. /// <remarks>
  755. /// Move to the next result set.
  756. /// </remarks>
  757. public
  758. #if NET_2_0
  759. override
  760. #endif // NET_2_0
  761. bool NextResult ()
  762. {
  763. OdbcReturn ret = OdbcReturn.Success;
  764. ret = libodbc.SQLMoreResults (hstmt);
  765. if (ret == OdbcReturn.Success) {
  766. short colcount = 0;
  767. libodbc.SQLNumResultCols (hstmt, ref colcount);
  768. cols = new OdbcColumn [colcount];
  769. _dataTableSchema = null; // force fresh creation
  770. GetSchemaTable ();
  771. }
  772. return (ret==OdbcReturn.Success);
  773. }
  774. /// <remarks>
  775. /// Load the next row in the current result set.
  776. /// </remarks>
  777. private bool NextRow ()
  778. {
  779. OdbcReturn ret=libodbc.SQLFetch (hstmt);
  780. if (ret != OdbcReturn.Success)
  781. currentRow = -1;
  782. else
  783. currentRow++;
  784. // Clear cached values from last record
  785. foreach (OdbcColumn col in cols)
  786. {
  787. if (col != null)
  788. col.Value = null;
  789. }
  790. return (ret == OdbcReturn.Success);
  791. }
  792. private int GetColumnAttribute (int column, FieldIdentifier fieldId)
  793. {
  794. OdbcReturn ret = OdbcReturn.Error;
  795. byte [] buffer = new byte [255];
  796. int outsize = 0;
  797. int val = 0;
  798. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  799. buffer, buffer.Length,
  800. ref outsize, ref val);
  801. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  802. throw new OdbcException (new OdbcError ("SQLColAttribute",
  803. OdbcHandleType.Stmt,
  804. hstmt)
  805. );
  806. return val;
  807. }
  808. private string GetColumnAttributeStr (int column, FieldIdentifier fieldId)
  809. {
  810. OdbcReturn ret = OdbcReturn.Error;
  811. byte [] buffer = new byte [255];
  812. int outsize = 0;
  813. int val = 0;
  814. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  815. buffer, buffer.Length,
  816. ref outsize, ref val);
  817. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  818. throw new OdbcException (new OdbcError ("SQLColAttribute",
  819. OdbcHandleType.Stmt,
  820. hstmt)
  821. );
  822. string value = "";
  823. if (outsize > 0)
  824. value = Encoding.Default.GetString (buffer, 0, outsize);
  825. return value;
  826. }
  827. private string [] GetPrimaryKeys (string catalog, string schema, string table)
  828. {
  829. if (cols.Length <= 0)
  830. return new string [0];
  831. ArrayList keys = null;
  832. try {
  833. keys = GetPrimaryKeysBySQLPrimaryKey (catalog, schema, table);
  834. } catch (OdbcException){
  835. try {
  836. keys = GetPrimaryKeysBySQLStatistics (catalog, schema, table);
  837. } catch (OdbcException) {
  838. }
  839. }
  840. keys.Sort ();
  841. return (string []) keys.ToArray (typeof (string));
  842. }
  843. private ArrayList GetPrimaryKeysBySQLPrimaryKey (string catalog, string schema, string table)
  844. {
  845. ArrayList keys = new ArrayList ();
  846. IntPtr handle = IntPtr.Zero;
  847. OdbcReturn ret;
  848. try {
  849. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  850. command.Connection.hDbc, ref handle);
  851. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  852. throw new OdbcException(new OdbcError("SQLAllocHandle",
  853. OdbcHandleType.Dbc,
  854. command.Connection.hDbc));
  855. ret = libodbc.SQLPrimaryKeys (handle, catalog, -3,
  856. schema, -3,
  857. table, -3);
  858. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  859. throw new OdbcException (new OdbcError ("SQLPrimaryKeys", OdbcHandleType.Stmt, handle));
  860. int length = 0;
  861. byte [] primaryKey = new byte [255];
  862. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.CHAR, primaryKey, primaryKey.Length, ref length);
  863. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  864. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  865. int i = 0;
  866. while (true) {
  867. ret = libodbc.SQLFetch (handle);
  868. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  869. break;
  870. string pkey = Encoding.Default.GetString (primaryKey, 0, length);
  871. keys.Add (pkey);
  872. }
  873. } finally {
  874. if (handle != IntPtr.Zero) {
  875. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  876. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  877. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  878. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  879. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  880. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  881. }
  882. }
  883. return keys;
  884. }
  885. private unsafe ArrayList GetPrimaryKeysBySQLStatistics (string catalog, string schema, string table)
  886. {
  887. ArrayList keys = new ArrayList ();
  888. IntPtr handle = IntPtr.Zero;
  889. OdbcReturn ret;
  890. try {
  891. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  892. command.Connection.hDbc, ref handle);
  893. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  894. throw new OdbcException(new OdbcError("SQLAllocHandle",
  895. OdbcHandleType.Dbc,
  896. command.Connection.hDbc));
  897. ret = libodbc.SQLStatistics (handle, catalog, -3,
  898. schema, -3,
  899. table, -3,
  900. libodbc.SQL_INDEX_UNIQUE,
  901. libodbc.SQL_QUICK);
  902. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  903. throw new OdbcException (new OdbcError ("SQLStatistics", OdbcHandleType.Stmt, handle));
  904. // NON_UNIQUE
  905. int nonUniqueLength = 0;
  906. short nonUnique = libodbc.SQL_FALSE;
  907. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.SHORT, ref (short) nonUnique, sizeof (short), ref nonUniqueLength);
  908. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  909. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  910. // COLUMN_NAME
  911. int length = 0;
  912. byte [] colName = new byte [255];
  913. ret = libodbc.SQLBindCol (handle, 9, SQL_C_TYPE.CHAR, colName, colName.Length, ref length);
  914. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  915. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  916. int i = 0;
  917. while (true) {
  918. ret = libodbc.SQLFetch (handle);
  919. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  920. break;
  921. if (nonUnique == libodbc.SQL_TRUE) {
  922. string pkey = Encoding.Default.GetString (colName, 0, length);
  923. keys.Add (pkey);
  924. break;
  925. }
  926. }
  927. } finally {
  928. if (handle != IntPtr.Zero) {
  929. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  930. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  931. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  932. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  933. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  934. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  935. }
  936. }
  937. return keys;
  938. }
  939. public
  940. #if NET_2_0
  941. override
  942. #endif // NET_2_0
  943. bool Read ()
  944. {
  945. return NextRow ();
  946. }
  947. #if NET_2_0
  948. [MonoTODO]
  949. public override object GetProviderSpecificValue (int i)
  950. {
  951. throw new NotImplementedException ();
  952. }
  953. [MonoTODO]
  954. public override int GetProviderSpecificValues (object[] values)
  955. {
  956. throw new NotImplementedException ();
  957. }
  958. [MonoTODO]
  959. public override Type GetFieldProviderSpecificType (int i)
  960. {
  961. throw new NotImplementedException ();
  962. }
  963. #endif // NET_2_0
  964. #endregion
  965. }
  966. }