OdbcDataReader.cs 33 KB

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