OdbcDataReader.cs 30 KB

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