OdbcDataReader.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. ~OdbcDataReader ()
  210. {
  211. this.Dispose (false);
  212. }
  213. public
  214. #if NET_2_0
  215. override
  216. #endif // NET_2_0
  217. bool GetBoolean (int ordinal)
  218. {
  219. return (bool) GetValue(ordinal);
  220. }
  221. public
  222. #if NET_2_0
  223. override
  224. #endif // NET_2_0
  225. byte GetByte (int ordinal)
  226. {
  227. return (byte) Convert.ToByte(GetValue(ordinal));
  228. }
  229. public
  230. #if NET_2_0
  231. override
  232. #endif // NET_2_0
  233. long GetBytes (int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
  234. {
  235. OdbcReturn ret = OdbcReturn.Error;
  236. bool copyBuffer = false;
  237. int returnVal = 0, outsize = 0;
  238. byte [] tbuff = new byte [length+1];
  239. length = buffer == null ? 0 : length;
  240. ret=libodbc.SQLGetData (hstmt, (ushort) (ordinal+1), SQL_C_TYPE.BINARY, tbuff, length,
  241. ref outsize);
  242. if (ret == OdbcReturn.NoData)
  243. return 0;
  244. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  245. throw new OdbcException (new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt));
  246. OdbcError odbcErr = null;
  247. if ( (ret == OdbcReturn.SuccessWithInfo))
  248. odbcErr = new OdbcError ("SQLGetData", OdbcHandleType.Stmt, hstmt);
  249. if (buffer == null)
  250. return outsize; //if buffer is null,return length of the field
  251. if (ret == OdbcReturn.SuccessWithInfo) {
  252. if (outsize == (int) OdbcLengthIndicator.NoTotal)
  253. copyBuffer = true;
  254. else if (outsize == (int) OdbcLengthIndicator.NullData) {
  255. copyBuffer = false;
  256. returnVal = -1;
  257. } else {
  258. string sqlstate = odbcErr.SQLState;
  259. //SQLState: String Data, Right truncated
  260. if (sqlstate != libodbc.SQLSTATE_RIGHT_TRUNC)
  261. throw new OdbcException ( odbcErr);
  262. copyBuffer = true;
  263. }
  264. } else {
  265. copyBuffer = outsize == -1 ? false : true;
  266. returnVal = outsize;
  267. }
  268. if (copyBuffer) {
  269. int i = 0;
  270. while (tbuff [i] != libodbc.C_NULL) {
  271. buffer [bufferIndex + i] = tbuff [i];
  272. i++;
  273. }
  274. returnVal = i;
  275. }
  276. return returnVal;
  277. }
  278. [MonoTODO]
  279. public
  280. #if NET_2_0
  281. override
  282. #endif // NET_2_0
  283. char GetChar (int ordinal)
  284. {
  285. throw new NotImplementedException ();
  286. }
  287. [MonoTODO]
  288. public
  289. #if NET_2_0
  290. override
  291. #endif // NET_2_0
  292. long GetChars (int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length)
  293. {
  294. throw new NotImplementedException ();
  295. }
  296. [MonoTODO]
  297. [EditorBrowsableAttribute (EditorBrowsableState.Never)]
  298. public
  299. #if NET_2_0
  300. new
  301. #endif // NET_2_0
  302. IDataReader GetData (int ordinal)
  303. {
  304. throw new NotImplementedException ();
  305. }
  306. public
  307. #if NET_2_0
  308. override
  309. #endif // NET_2_0
  310. string GetDataTypeName (int index)
  311. {
  312. return GetColumn (index).OdbcType.ToString ();
  313. }
  314. public DateTime GetDate (int ordinal) {
  315. return GetDateTime (ordinal);
  316. }
  317. public
  318. #if NET_2_0
  319. override
  320. #endif // NET_2_0
  321. DateTime GetDateTime (int ordinal)
  322. {
  323. return (DateTime) GetValue (ordinal);
  324. }
  325. public
  326. #if NET_2_0
  327. override
  328. #endif // NET_2_0
  329. decimal GetDecimal (int ordinal)
  330. {
  331. return (decimal) GetValue (ordinal);
  332. }
  333. public
  334. #if NET_2_0
  335. override
  336. #endif // NET_2_0
  337. double GetDouble (int ordinal)
  338. {
  339. return (double) GetValue (ordinal);
  340. }
  341. public
  342. #if NET_2_0
  343. override
  344. #endif // NET_2_0
  345. Type GetFieldType (int index)
  346. {
  347. return GetColumn(index).DataType;
  348. }
  349. public
  350. #if NET_2_0
  351. override
  352. #endif // NET_2_0
  353. float GetFloat (int ordinal)
  354. {
  355. return (float) GetValue (ordinal);
  356. }
  357. [MonoTODO]
  358. public
  359. #if NET_2_0
  360. override
  361. #endif // NET_2_0
  362. Guid GetGuid (int ordinal)
  363. {
  364. throw new NotImplementedException ();
  365. }
  366. public
  367. #if NET_2_0
  368. override
  369. #endif // NET_2_0
  370. short GetInt16 (int ordinal)
  371. {
  372. return (short) GetValue (ordinal);
  373. }
  374. public
  375. #if NET_2_0
  376. override
  377. #endif // NET_2_0
  378. int GetInt32 (int ordinal)
  379. {
  380. return (int) GetValue (ordinal);
  381. }
  382. public
  383. #if NET_2_0
  384. override
  385. #endif // NET_2_0
  386. long GetInt64 (int ordinal)
  387. {
  388. return (long) GetValue (ordinal);
  389. }
  390. public
  391. #if NET_2_0
  392. override
  393. #endif // NET_2_0
  394. string GetName (int index)
  395. {
  396. return GetColumn(index).ColumnName;
  397. }
  398. public
  399. #if NET_2_0
  400. override
  401. #endif // NET_2_0
  402. int GetOrdinal (string name)
  403. {
  404. int i=ColIndex(name);
  405. if (i==-1)
  406. throw new IndexOutOfRangeException ();
  407. else
  408. return i;
  409. }
  410. [MonoTODO]
  411. public
  412. #if NET_2_0
  413. override
  414. #endif // NET_2_0
  415. DataTable GetSchemaTable()
  416. {
  417. // FIXME :
  418. // * Map OdbcType to System.Type and assign to DataType.
  419. // This will eliminate the need for IsStringType in
  420. // OdbcColumn.
  421. if (_dataTableSchema != null)
  422. return _dataTableSchema;
  423. DataTable dataTableSchema = null;
  424. // Only Results from SQL SELECT Queries
  425. // get a DataTable for schema of the result
  426. // otherwise, DataTable is null reference
  427. if(cols.Length > 0)
  428. {
  429. dataTableSchema = new DataTable ();
  430. dataTableSchema.Columns.Add ("ColumnName", typeof (string));
  431. dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
  432. dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
  433. dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
  434. dataTableSchema.Columns.Add ("NumericScale", typeof (int));
  435. dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
  436. dataTableSchema.Columns.Add ("IsKey", typeof (bool));
  437. DataColumn dc = dataTableSchema.Columns["IsKey"];
  438. dc.AllowDBNull = true; // IsKey can have a DBNull
  439. dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
  440. dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
  441. dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
  442. dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
  443. dataTableSchema.Columns.Add ("DataType", typeof(Type));
  444. dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
  445. dataTableSchema.Columns.Add ("ProviderType", typeof (int));
  446. dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
  447. dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
  448. dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
  449. dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
  450. dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
  451. dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
  452. dataTableSchema.Columns.Add ("IsLong", typeof (bool));
  453. dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
  454. DataRow schemaRow;
  455. for (int i = 0; i < cols.Length; i += 1 )
  456. {
  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 ordinal)
  526. {
  527. return (string) GetValue (ordinal);
  528. }
  529. [MonoTODO]
  530. public TimeSpan GetTime (int ordinal)
  531. {
  532. throw new NotImplementedException ();
  533. }
  534. public
  535. #if NET_2_0
  536. override
  537. #endif // NET_2_0
  538. object GetValue (int ordinal)
  539. {
  540. if (currentRow == -1)
  541. throw new IndexOutOfRangeException ();
  542. if (ordinal > cols.Length-1 || ordinal < 0)
  543. throw new IndexOutOfRangeException ();
  544. OdbcReturn ret;
  545. int outsize = 0, bufsize;
  546. byte[] buffer;
  547. OdbcColumn col = GetColumn (ordinal);
  548. object DataValue = null;
  549. ushort ColIndex = Convert.ToUInt16 (ordinal+1);
  550. // Check cached values
  551. if (col.Value == null) {
  552. // odbc help file
  553. // mk:@MSITStore:C:\program%20files\Microsoft%20Data%20Access%20SDK\Docs\odbc.chm::/htm/odbcc_data_types.htm
  554. switch (col.OdbcType) {
  555. case OdbcType.Bit:
  556. short bit_data = 0;
  557. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref bit_data, 0, ref outsize);
  558. if (outsize != (int) OdbcLengthIndicator.NullData)
  559. DataValue = bit_data == 0 ? "False" : "True";
  560. break;
  561. case OdbcType.Numeric:
  562. case OdbcType.Decimal:
  563. bufsize = 50;
  564. buffer = new byte [bufsize]; // According to sqlext.h, use SQL_CHAR for decimal.
  565. // FIXME : use Numeric.
  566. ret = libodbc.SQLGetData (hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  567. if (outsize!=-1) {
  568. byte [] temp = new byte [outsize];
  569. for (int i = 0;i<outsize;i++)
  570. temp[i] = buffer[i];
  571. DataValue = Decimal.Parse(System.Text.Encoding.Default.GetString(temp));
  572. }
  573. break;
  574. case OdbcType.TinyInt:
  575. short short_data = 0;
  576. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref short_data, 0, ref outsize);
  577. DataValue = System.Convert.ToByte(short_data);
  578. break;
  579. case OdbcType.Int:
  580. int int_data = 0;
  581. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref int_data, 0, ref outsize);
  582. DataValue = int_data;
  583. break;
  584. case OdbcType.SmallInt:
  585. short sint_data = 0;
  586. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref sint_data, 0, ref outsize);
  587. DataValue = sint_data;
  588. break;
  589. case OdbcType.BigInt:
  590. long long_data = 0;
  591. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref long_data, 0, ref outsize);
  592. DataValue = long_data;
  593. break;
  594. case OdbcType.NText:
  595. case OdbcType.NVarChar:
  596. bufsize = (col.MaxLength < 127 ? (col.MaxLength*2+1) : 255);
  597. buffer = new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  598. StringBuilder sb = new StringBuilder ();
  599. do {
  600. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  601. if (ret == OdbcReturn.Error)
  602. break;
  603. if (ret != OdbcReturn.NoData && outsize!=-1) {
  604. if (outsize < bufsize)
  605. sb.Append (System.Text.Encoding.Unicode.GetString(buffer,0,outsize));
  606. else
  607. sb.Append (System.Text.Encoding.Unicode.GetString(buffer,0,bufsize));
  608. }
  609. } while (ret != OdbcReturn.NoData);
  610. DataValue = sb.ToString ();
  611. break;
  612. case OdbcType.Text:
  613. case OdbcType.VarChar:
  614. bufsize = (col.MaxLength < 255 ? (col.MaxLength+1) : 255);
  615. buffer = new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  616. StringBuilder sb1 = new StringBuilder ();
  617. do {
  618. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  619. if (ret == OdbcReturn.Error)
  620. break;
  621. if (ret != OdbcReturn.NoData && outsize!=-1) {
  622. if (outsize < bufsize)
  623. sb1.Append (System.Text.Encoding.Default.GetString(buffer,0,outsize));
  624. else
  625. sb1.Append (System.Text.Encoding.Default.GetString(buffer,0,bufsize));
  626. }
  627. } while (ret != OdbcReturn.NoData);
  628. DataValue = sb1.ToString ();
  629. break;
  630. case OdbcType.Real:
  631. float float_data = 0;
  632. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref float_data, 0, ref outsize);
  633. DataValue = float_data;
  634. break;
  635. case OdbcType.Double:
  636. double double_data = 0;
  637. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref double_data, 0, ref outsize);
  638. DataValue = double_data;
  639. break;
  640. case OdbcType.Timestamp:
  641. case OdbcType.DateTime:
  642. case OdbcType.Date:
  643. case OdbcType.Time:
  644. OdbcTimestamp ts_data = new OdbcTimestamp();
  645. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref ts_data, 0, ref outsize);
  646. if (outsize!=-1) // This means SQL_NULL_DATA
  647. DataValue = new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  648. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  649. break;
  650. case OdbcType.VarBinary :
  651. case OdbcType.Image :
  652. bufsize = (col.MaxLength < 255 ? col.MaxLength : 255);
  653. buffer= new byte [bufsize];
  654. ArrayList al = new ArrayList ();
  655. do {
  656. ret = libodbc.SQLGetData (hstmt, ColIndex, SQL_C_TYPE.BINARY, buffer, bufsize, ref outsize);
  657. if (ret == OdbcReturn.Error)
  658. break;
  659. if (ret != OdbcReturn.NoData && outsize!=-1) {
  660. if (outsize < bufsize) {
  661. byte[] tmparr = new byte [outsize];
  662. Array.Copy (buffer, 0, tmparr, 0, outsize);
  663. al.AddRange (tmparr);
  664. } else
  665. al.AddRange (buffer);
  666. }
  667. } while (ret != OdbcReturn.NoData);
  668. DataValue = al.ToArray (typeof (byte));
  669. break;
  670. case OdbcType.Binary :
  671. bufsize = col.MaxLength;
  672. buffer = new byte [bufsize];
  673. long read = GetBytes (ordinal, 0, buffer, 0, bufsize);
  674. ret = OdbcReturn.Success;
  675. DataValue = buffer;
  676. break;
  677. default:
  678. bufsize = 255;
  679. buffer = new byte[bufsize];
  680. ret = libodbc.SQLGetData (hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  681. if (outsize != (int) OdbcLengthIndicator.NullData)
  682. if (! (ret == OdbcReturn.SuccessWithInfo
  683. && outsize == (int) OdbcLengthIndicator.NoTotal))
  684. DataValue = System.Text.Encoding.Default.GetString(buffer, 0, outsize);
  685. break;
  686. }
  687. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo) && (ret!=OdbcReturn.NoData))
  688. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  689. if (outsize==-1) // This means SQL_NULL_DATA
  690. col.Value = DBNull.Value;
  691. else
  692. col.Value = DataValue;
  693. }
  694. return col.Value;
  695. }
  696. public
  697. #if NET_2_0
  698. override
  699. #endif // NET_2_0
  700. int GetValues (object[] values)
  701. {
  702. int numValues = 0;
  703. // copy values
  704. for (int i = 0; i < values.Length; i++) {
  705. if (i < FieldCount) {
  706. values[i] = GetValue (i);
  707. }
  708. else {
  709. values[i] = null;
  710. }
  711. }
  712. // get number of object instances in array
  713. if (values.Length < FieldCount)
  714. numValues = values.Length;
  715. else if (values.Length == FieldCount)
  716. numValues = FieldCount;
  717. else
  718. numValues = FieldCount;
  719. return numValues;
  720. }
  721. #if ONLY_1_1
  722. void IDisposable.Dispose ()
  723. {
  724. Dispose (true);
  725. GC.SuppressFinalize (this);
  726. }
  727. IEnumerator IEnumerable.GetEnumerator ()
  728. {
  729. return new DbEnumerator (this);
  730. }
  731. #endif // ONLY_1_1
  732. #if NET_2_0
  733. public override IEnumerator GetEnumerator ()
  734. {
  735. return new DbEnumerator (this);
  736. }
  737. #endif
  738. #if NET_2_0
  739. protected override
  740. #endif
  741. void Dispose (bool disposing)
  742. {
  743. if (disposed)
  744. return;
  745. if (disposing) {
  746. // dispose managed resources
  747. Close ();
  748. }
  749. command = null;
  750. cols = null;
  751. _dataTableSchema = null;
  752. disposed = true;
  753. }
  754. public
  755. #if NET_2_0
  756. override
  757. #endif // NET_2_0
  758. bool IsDBNull (int ordinal)
  759. {
  760. return (GetValue (ordinal) is DBNull);
  761. }
  762. /// <remarks>
  763. /// Move to the next result set.
  764. /// </remarks>
  765. public
  766. #if NET_2_0
  767. override
  768. #endif // NET_2_0
  769. bool NextResult ()
  770. {
  771. OdbcReturn ret = OdbcReturn.Success;
  772. ret = libodbc.SQLMoreResults (hstmt);
  773. if (ret == OdbcReturn.Success) {
  774. short colcount = 0;
  775. libodbc.SQLNumResultCols (hstmt, ref colcount);
  776. cols = new OdbcColumn [colcount];
  777. _dataTableSchema = null; // force fresh creation
  778. GetSchemaTable ();
  779. }
  780. return (ret==OdbcReturn.Success);
  781. }
  782. /// <remarks>
  783. /// Load the next row in the current result set.
  784. /// </remarks>
  785. private bool NextRow ()
  786. {
  787. OdbcReturn ret=libodbc.SQLFetch (hstmt);
  788. if (ret != OdbcReturn.Success)
  789. currentRow = -1;
  790. else
  791. currentRow++;
  792. // Clear cached values from last record
  793. foreach (OdbcColumn col in cols)
  794. {
  795. if (col != null)
  796. col.Value = null;
  797. }
  798. return (ret == OdbcReturn.Success);
  799. }
  800. private int GetColumnAttribute (int column, FieldIdentifier fieldId)
  801. {
  802. OdbcReturn ret = OdbcReturn.Error;
  803. byte [] buffer = new byte [255];
  804. int outsize = 0;
  805. int val = 0;
  806. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  807. buffer, buffer.Length,
  808. ref outsize, ref val);
  809. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  810. throw new OdbcException (new OdbcError ("SQLColAttribute",
  811. OdbcHandleType.Stmt,
  812. hstmt)
  813. );
  814. return val;
  815. }
  816. private string GetColumnAttributeStr (int column, FieldIdentifier fieldId)
  817. {
  818. OdbcReturn ret = OdbcReturn.Error;
  819. byte [] buffer = new byte [255];
  820. int outsize = 0;
  821. int val = 0;
  822. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  823. buffer, buffer.Length,
  824. ref outsize, ref val);
  825. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  826. throw new OdbcException (new OdbcError ("SQLColAttribute",
  827. OdbcHandleType.Stmt,
  828. hstmt)
  829. );
  830. string value = "";
  831. if (outsize > 0)
  832. value = Encoding.Default.GetString (buffer, 0, outsize);
  833. return value;
  834. }
  835. private string [] GetPrimaryKeys (string catalog, string schema, string table)
  836. {
  837. if (cols.Length <= 0)
  838. return new string [0];
  839. ArrayList keys = null;
  840. try {
  841. keys = GetPrimaryKeysBySQLPrimaryKey (catalog, schema, table);
  842. } catch (OdbcException){
  843. try {
  844. keys = GetPrimaryKeysBySQLStatistics (catalog, schema, table);
  845. } catch (OdbcException) {
  846. }
  847. }
  848. keys.Sort ();
  849. return (string []) keys.ToArray (typeof (string));
  850. }
  851. private ArrayList GetPrimaryKeysBySQLPrimaryKey (string catalog, string schema, string table)
  852. {
  853. ArrayList keys = new ArrayList ();
  854. IntPtr handle = IntPtr.Zero;
  855. OdbcReturn ret;
  856. try {
  857. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  858. command.Connection.hDbc, ref handle);
  859. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  860. throw new OdbcException(new OdbcError("SQLAllocHandle",
  861. OdbcHandleType.Dbc,
  862. command.Connection.hDbc));
  863. ret = libodbc.SQLPrimaryKeys (handle, catalog, -3,
  864. schema, -3,
  865. table, -3);
  866. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  867. throw new OdbcException (new OdbcError ("SQLPrimaryKeys", OdbcHandleType.Stmt, handle));
  868. int length = 0;
  869. byte [] primaryKey = new byte [255];
  870. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.CHAR, primaryKey, primaryKey.Length, ref length);
  871. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  872. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  873. int i = 0;
  874. while (true) {
  875. ret = libodbc.SQLFetch (handle);
  876. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  877. break;
  878. string pkey = Encoding.Default.GetString (primaryKey, 0, length);
  879. keys.Add (pkey);
  880. }
  881. } finally {
  882. if (handle != IntPtr.Zero) {
  883. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  884. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  885. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  886. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  887. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  888. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  889. }
  890. }
  891. return keys;
  892. }
  893. private unsafe ArrayList GetPrimaryKeysBySQLStatistics (string catalog, string schema, string table)
  894. {
  895. ArrayList keys = new ArrayList ();
  896. IntPtr handle = IntPtr.Zero;
  897. OdbcReturn ret;
  898. try {
  899. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  900. command.Connection.hDbc, ref handle);
  901. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  902. throw new OdbcException(new OdbcError("SQLAllocHandle",
  903. OdbcHandleType.Dbc,
  904. command.Connection.hDbc));
  905. ret = libodbc.SQLStatistics (handle, catalog, -3,
  906. schema, -3,
  907. table, -3,
  908. libodbc.SQL_INDEX_UNIQUE,
  909. libodbc.SQL_QUICK);
  910. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  911. throw new OdbcException (new OdbcError ("SQLStatistics", OdbcHandleType.Stmt, handle));
  912. // NON_UNIQUE
  913. int nonUniqueLength = 0;
  914. short nonUnique = libodbc.SQL_FALSE;
  915. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.SHORT, ref (short) nonUnique, sizeof (short), ref nonUniqueLength);
  916. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  917. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  918. // COLUMN_NAME
  919. int length = 0;
  920. byte [] colName = new byte [255];
  921. ret = libodbc.SQLBindCol (handle, 9, SQL_C_TYPE.CHAR, colName, colName.Length, ref length);
  922. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  923. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  924. int i = 0;
  925. while (true) {
  926. ret = libodbc.SQLFetch (handle);
  927. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  928. break;
  929. if (nonUnique == libodbc.SQL_TRUE) {
  930. string pkey = Encoding.Default.GetString (colName, 0, length);
  931. keys.Add (pkey);
  932. break;
  933. }
  934. }
  935. } finally {
  936. if (handle != IntPtr.Zero) {
  937. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  938. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  939. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  940. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  941. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  942. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  943. }
  944. }
  945. return keys;
  946. }
  947. public
  948. #if NET_2_0
  949. override
  950. #endif // NET_2_0
  951. bool Read ()
  952. {
  953. return NextRow ();
  954. }
  955. #if NET_2_0
  956. [MonoTODO]
  957. public override object GetProviderSpecificValue (int i)
  958. {
  959. throw new NotImplementedException ();
  960. }
  961. [MonoTODO]
  962. public override int GetProviderSpecificValues (object[] values)
  963. {
  964. throw new NotImplementedException ();
  965. }
  966. [MonoTODO]
  967. public override Type GetProviderSpecificFieldType (int i)
  968. {
  969. throw new NotImplementedException ();
  970. }
  971. #endif // NET_2_0
  972. #endregion
  973. }
  974. }