OdbcDataReader.cs 29 KB

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