OdbcDataReader.cs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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. #if ONLY_1_1
  299. public
  300. #endif
  301. #if NET_2_0
  302. new
  303. #endif
  304. IDataReader GetData (int ordinal)
  305. {
  306. throw new NotImplementedException ();
  307. }
  308. public
  309. #if NET_2_0
  310. override
  311. #endif // NET_2_0
  312. string GetDataTypeName (int index)
  313. {
  314. return GetColumn (index).OdbcType.ToString ();
  315. }
  316. public DateTime GetDate (int ordinal) {
  317. return GetDateTime (ordinal);
  318. }
  319. public
  320. #if NET_2_0
  321. override
  322. #endif // NET_2_0
  323. DateTime GetDateTime (int ordinal)
  324. {
  325. return (DateTime) GetValue (ordinal);
  326. }
  327. public
  328. #if NET_2_0
  329. override
  330. #endif // NET_2_0
  331. decimal GetDecimal (int ordinal)
  332. {
  333. return (decimal) GetValue (ordinal);
  334. }
  335. public
  336. #if NET_2_0
  337. override
  338. #endif // NET_2_0
  339. double GetDouble (int ordinal)
  340. {
  341. return (double) GetValue (ordinal);
  342. }
  343. public
  344. #if NET_2_0
  345. override
  346. #endif // NET_2_0
  347. Type GetFieldType (int index)
  348. {
  349. return GetColumn(index).DataType;
  350. }
  351. public
  352. #if NET_2_0
  353. override
  354. #endif // NET_2_0
  355. float GetFloat (int ordinal)
  356. {
  357. return (float) GetValue (ordinal);
  358. }
  359. [MonoTODO]
  360. public
  361. #if NET_2_0
  362. override
  363. #endif // NET_2_0
  364. Guid GetGuid (int ordinal)
  365. {
  366. throw new NotImplementedException ();
  367. }
  368. public
  369. #if NET_2_0
  370. override
  371. #endif // NET_2_0
  372. short GetInt16 (int ordinal)
  373. {
  374. return (short) GetValue (ordinal);
  375. }
  376. public
  377. #if NET_2_0
  378. override
  379. #endif // NET_2_0
  380. int GetInt32 (int ordinal)
  381. {
  382. return (int) GetValue (ordinal);
  383. }
  384. public
  385. #if NET_2_0
  386. override
  387. #endif // NET_2_0
  388. long GetInt64 (int ordinal)
  389. {
  390. return (long) GetValue (ordinal);
  391. }
  392. public
  393. #if NET_2_0
  394. override
  395. #endif // NET_2_0
  396. string GetName (int index)
  397. {
  398. return GetColumn(index).ColumnName;
  399. }
  400. public
  401. #if NET_2_0
  402. override
  403. #endif // NET_2_0
  404. int GetOrdinal (string name)
  405. {
  406. int i=ColIndex(name);
  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. {
  431. dataTableSchema = new DataTable ();
  432. dataTableSchema.Columns.Add ("ColumnName", typeof (string));
  433. dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (int));
  434. dataTableSchema.Columns.Add ("ColumnSize", typeof (int));
  435. dataTableSchema.Columns.Add ("NumericPrecision", typeof (int));
  436. dataTableSchema.Columns.Add ("NumericScale", typeof (int));
  437. dataTableSchema.Columns.Add ("IsUnique", typeof (bool));
  438. dataTableSchema.Columns.Add ("IsKey", typeof (bool));
  439. DataColumn dc = dataTableSchema.Columns["IsKey"];
  440. dc.AllowDBNull = true; // IsKey can have a DBNull
  441. dataTableSchema.Columns.Add ("BaseCatalogName", typeof (string));
  442. dataTableSchema.Columns.Add ("BaseColumnName", typeof (string));
  443. dataTableSchema.Columns.Add ("BaseSchemaName", typeof (string));
  444. dataTableSchema.Columns.Add ("BaseTableName", typeof (string));
  445. dataTableSchema.Columns.Add ("DataType", typeof(Type));
  446. dataTableSchema.Columns.Add ("AllowDBNull", typeof (bool));
  447. dataTableSchema.Columns.Add ("ProviderType", typeof (int));
  448. dataTableSchema.Columns.Add ("IsAliased", typeof (bool));
  449. dataTableSchema.Columns.Add ("IsExpression", typeof (bool));
  450. dataTableSchema.Columns.Add ("IsIdentity", typeof (bool));
  451. dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (bool));
  452. dataTableSchema.Columns.Add ("IsRowVersion", typeof (bool));
  453. dataTableSchema.Columns.Add ("IsHidden", typeof (bool));
  454. dataTableSchema.Columns.Add ("IsLong", typeof (bool));
  455. dataTableSchema.Columns.Add ("IsReadOnly", typeof (bool));
  456. DataRow schemaRow;
  457. for (int i = 0; i < cols.Length; i += 1 )
  458. {
  459. string baseTableName = String.Empty;
  460. bool isKey = false;
  461. OdbcColumn col=GetColumn(i);
  462. schemaRow = dataTableSchema.NewRow ();
  463. dataTableSchema.Rows.Add (schemaRow);
  464. schemaRow ["ColumnName"] = col.ColumnName;
  465. schemaRow ["ColumnOrdinal"] = i;
  466. schemaRow ["ColumnSize"] = col.MaxLength;
  467. schemaRow ["NumericPrecision"] = GetColumnAttribute (i+1, FieldIdentifier.Precision);
  468. schemaRow ["NumericScale"] = GetColumnAttribute (i+1, FieldIdentifier.Scale);
  469. schemaRow ["BaseTableName"] = GetColumnAttributeStr (i+1, FieldIdentifier.TableName);
  470. schemaRow ["BaseSchemaName"] = GetColumnAttributeStr (i+1, FieldIdentifier.SchemaName);
  471. schemaRow ["BaseCatalogName"] = GetColumnAttributeStr (i+1, FieldIdentifier.CatelogName);
  472. schemaRow ["BaseColumnName"] = GetColumnAttributeStr (i+1, FieldIdentifier.BaseColumnName);
  473. schemaRow ["DataType"] = col.DataType;
  474. schemaRow ["IsUnique"] = false;
  475. schemaRow ["IsKey"] = DBNull.Value;
  476. schemaRow ["AllowDBNull"] = GetColumnAttribute (i+1, FieldIdentifier.Nullable) != libodbc.SQL_NO_NULLS;
  477. schemaRow ["ProviderType"] = (int) col.OdbcType;
  478. schemaRow ["IsAutoIncrement"] = GetColumnAttribute (i+1, FieldIdentifier.AutoUniqueValue) == libodbc.SQL_TRUE;
  479. schemaRow ["IsExpression"] = schemaRow.IsNull ("BaseTableName") || (string) schemaRow ["BaseTableName"] == String.Empty;
  480. schemaRow ["IsAliased"] = (string) schemaRow ["BaseColumnName"] != (string) schemaRow ["ColumnName"];
  481. schemaRow ["IsReadOnly"] = ((bool) schemaRow ["IsExpression"]
  482. || GetColumnAttribute (i+1, FieldIdentifier.Updatable) == libodbc.SQL_ATTR_READONLY);
  483. // FIXME: all of these
  484. schemaRow ["IsIdentity"] = false;
  485. schemaRow ["IsRowVersion"] = false;
  486. schemaRow ["IsHidden"] = false;
  487. schemaRow ["IsLong"] = false;
  488. // FIXME: according to Brian,
  489. // this does not work on MS .NET
  490. // however, we need it for Mono
  491. // for now
  492. // schemaRow.AcceptChanges();
  493. }
  494. // set primary keys
  495. DataRow [] rows = dataTableSchema.Select ("BaseTableName <> ''",
  496. "BaseCatalogName, BaseSchemaName, BaseTableName ASC");
  497. string lastTableName = String.Empty,
  498. lastSchemaName = String.Empty,
  499. lastCatalogName = String.Empty;
  500. string [] keys = null; // assumed to be sorted.
  501. foreach (DataRow row in rows) {
  502. string tableName = (string) row ["BaseTableName"];
  503. string schemaName = (string) row ["BaseSchemaName"];
  504. string catalogName = (string) row ["BaseCatalogName"];
  505. if (tableName != lastTableName || schemaName != lastSchemaName
  506. || catalogName != lastCatalogName)
  507. keys = GetPrimaryKeys (catalogName, schemaName, tableName);
  508. if (keys != null &&
  509. Array.BinarySearch (keys, (string) row ["BaseColumnName"]) >= 0) {
  510. row ["IsKey"] = true;
  511. row ["IsUnique"] = true;
  512. row ["AllowDBNull"] = false;
  513. GetColumn ( ColIndex ( (string) row ["ColumnName"])).AllowDBNull = false;
  514. }
  515. lastTableName = tableName;
  516. lastSchemaName = schemaName;
  517. lastCatalogName = catalogName;
  518. }
  519. dataTableSchema.AcceptChanges();
  520. }
  521. return (_dataTableSchema = dataTableSchema);
  522. }
  523. public
  524. #if NET_2_0
  525. override
  526. #endif // NET_2_0
  527. string GetString (int ordinal)
  528. {
  529. return (string) GetValue (ordinal);
  530. }
  531. [MonoTODO]
  532. public TimeSpan GetTime (int ordinal)
  533. {
  534. throw new NotImplementedException ();
  535. }
  536. public
  537. #if NET_2_0
  538. override
  539. #endif // NET_2_0
  540. object GetValue (int ordinal)
  541. {
  542. if (currentRow == -1)
  543. throw new IndexOutOfRangeException ();
  544. if (ordinal > cols.Length-1 || ordinal < 0)
  545. throw new IndexOutOfRangeException ();
  546. OdbcReturn ret;
  547. int outsize = 0, bufsize;
  548. byte[] buffer;
  549. OdbcColumn col = GetColumn (ordinal);
  550. object DataValue = null;
  551. ushort ColIndex = Convert.ToUInt16 (ordinal+1);
  552. // Check cached values
  553. if (col.Value == null) {
  554. // odbc help file
  555. // mk:@MSITStore:C:\program%20files\Microsoft%20Data%20Access%20SDK\Docs\odbc.chm::/htm/odbcc_data_types.htm
  556. switch (col.OdbcType) {
  557. case OdbcType.Bit:
  558. short bit_data = 0;
  559. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref bit_data, 0, ref outsize);
  560. if (outsize != (int) OdbcLengthIndicator.NullData)
  561. DataValue = bit_data == 0 ? "False" : "True";
  562. break;
  563. case OdbcType.Numeric:
  564. case OdbcType.Decimal:
  565. bufsize = 50;
  566. buffer = new byte [bufsize]; // According to sqlext.h, use SQL_CHAR for decimal.
  567. // FIXME : use Numeric.
  568. ret = libodbc.SQLGetData (hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  569. if (outsize!=-1) {
  570. byte [] temp = new byte [outsize];
  571. for (int i = 0;i<outsize;i++)
  572. temp[i] = buffer[i];
  573. DataValue = Decimal.Parse(System.Text.Encoding.Default.GetString(temp));
  574. }
  575. break;
  576. case OdbcType.TinyInt:
  577. short short_data = 0;
  578. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref short_data, 0, ref outsize);
  579. DataValue = System.Convert.ToByte(short_data);
  580. break;
  581. case OdbcType.Int:
  582. int int_data = 0;
  583. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref int_data, 0, ref outsize);
  584. DataValue = int_data;
  585. break;
  586. case OdbcType.SmallInt:
  587. short sint_data = 0;
  588. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref sint_data, 0, ref outsize);
  589. DataValue = sint_data;
  590. break;
  591. case OdbcType.BigInt:
  592. long long_data = 0;
  593. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref long_data, 0, ref outsize);
  594. DataValue = long_data;
  595. break;
  596. case OdbcType.NText:
  597. case OdbcType.NVarChar:
  598. bufsize = (col.MaxLength < 127 ? (col.MaxLength*2+1) : 255);
  599. buffer = new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  600. StringBuilder sb = new StringBuilder ();
  601. do {
  602. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  603. if (ret == OdbcReturn.Error)
  604. break;
  605. if (ret != OdbcReturn.NoData && outsize!=-1) {
  606. if (outsize < bufsize)
  607. sb.Append (System.Text.Encoding.Unicode.GetString(buffer,0,outsize));
  608. else
  609. sb.Append (System.Text.Encoding.Unicode.GetString(buffer,0,bufsize));
  610. }
  611. } while (ret != OdbcReturn.NoData);
  612. DataValue = sb.ToString ();
  613. break;
  614. case OdbcType.Text:
  615. case OdbcType.VarChar:
  616. bufsize = (col.MaxLength < 255 ? (col.MaxLength+1) : 255);
  617. buffer = new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  618. StringBuilder sb1 = new StringBuilder ();
  619. do {
  620. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  621. if (ret == OdbcReturn.Error)
  622. break;
  623. if (ret != OdbcReturn.NoData && outsize!=-1) {
  624. if (outsize < bufsize)
  625. sb1.Append (System.Text.Encoding.Default.GetString(buffer,0,outsize));
  626. else
  627. sb1.Append (System.Text.Encoding.Default.GetString (buffer, 0, bufsize - 1));
  628. }
  629. } while (ret != OdbcReturn.NoData);
  630. DataValue = sb1.ToString ();
  631. break;
  632. case OdbcType.Real:
  633. float float_data = 0;
  634. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref float_data, 0, ref outsize);
  635. DataValue = float_data;
  636. break;
  637. case OdbcType.Double:
  638. double double_data = 0;
  639. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref double_data, 0, ref outsize);
  640. DataValue = double_data;
  641. break;
  642. case OdbcType.Timestamp:
  643. case OdbcType.DateTime:
  644. case OdbcType.Date:
  645. case OdbcType.Time:
  646. OdbcTimestamp ts_data = new OdbcTimestamp();
  647. ret = libodbc.SQLGetData (hstmt, ColIndex, col.SqlCType, ref ts_data, 0, ref outsize);
  648. if (outsize!=-1) {// This means SQL_NULL_DATA
  649. DataValue = new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  650. ts_data.minute,ts_data.second);
  651. if (ts_data.fraction != 0)
  652. DataValue = ((DateTime) DataValue).AddTicks ((long)ts_data.fraction / 100);
  653. }
  654. break;
  655. case OdbcType.VarBinary :
  656. case OdbcType.Image :
  657. bufsize = (col.MaxLength < 255 ? col.MaxLength : 255);
  658. buffer= new byte [bufsize];
  659. ArrayList al = new ArrayList ();
  660. do {
  661. ret = libodbc.SQLGetData (hstmt, ColIndex, SQL_C_TYPE.BINARY, buffer, bufsize, ref outsize);
  662. if (ret == OdbcReturn.Error)
  663. break;
  664. if (ret != OdbcReturn.NoData && outsize!=-1) {
  665. if (outsize < bufsize) {
  666. byte[] tmparr = new byte [outsize];
  667. Array.Copy (buffer, 0, tmparr, 0, outsize);
  668. al.AddRange (tmparr);
  669. } else
  670. al.AddRange (buffer);
  671. }
  672. } while (ret != OdbcReturn.NoData);
  673. DataValue = al.ToArray (typeof (byte));
  674. break;
  675. case OdbcType.Binary :
  676. bufsize = col.MaxLength;
  677. buffer = new byte [bufsize];
  678. long read = GetBytes (ordinal, 0, buffer, 0, bufsize);
  679. ret = OdbcReturn.Success;
  680. DataValue = buffer;
  681. break;
  682. default:
  683. bufsize = 255;
  684. buffer = new byte[bufsize];
  685. ret = libodbc.SQLGetData (hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  686. if (outsize != (int) OdbcLengthIndicator.NullData)
  687. if (! (ret == OdbcReturn.SuccessWithInfo
  688. && outsize == (int) OdbcLengthIndicator.NoTotal))
  689. DataValue = System.Text.Encoding.Default.GetString(buffer, 0, outsize);
  690. break;
  691. }
  692. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo) && (ret!=OdbcReturn.NoData))
  693. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  694. if (outsize==-1) // This means SQL_NULL_DATA
  695. col.Value = DBNull.Value;
  696. else
  697. col.Value = DataValue;
  698. }
  699. return col.Value;
  700. }
  701. public
  702. #if NET_2_0
  703. override
  704. #endif // NET_2_0
  705. int GetValues (object[] values)
  706. {
  707. int numValues = 0;
  708. // copy values
  709. for (int i = 0; i < values.Length; i++) {
  710. if (i < FieldCount) {
  711. values[i] = GetValue (i);
  712. }
  713. else {
  714. values[i] = null;
  715. }
  716. }
  717. // get number of object instances in array
  718. if (values.Length < FieldCount)
  719. numValues = values.Length;
  720. else if (values.Length == FieldCount)
  721. numValues = FieldCount;
  722. else
  723. numValues = FieldCount;
  724. return numValues;
  725. }
  726. #if ONLY_1_1
  727. void IDisposable.Dispose ()
  728. {
  729. Dispose (true);
  730. GC.SuppressFinalize (this);
  731. }
  732. IEnumerator IEnumerable.GetEnumerator ()
  733. {
  734. return new DbEnumerator (this);
  735. }
  736. #endif // ONLY_1_1
  737. #if NET_2_0
  738. public override IEnumerator GetEnumerator ()
  739. {
  740. return new DbEnumerator (this);
  741. }
  742. #endif
  743. #if NET_2_0
  744. protected override
  745. #endif
  746. void Dispose (bool disposing)
  747. {
  748. if (disposed)
  749. return;
  750. if (disposing) {
  751. // dispose managed resources
  752. Close ();
  753. }
  754. command = null;
  755. cols = null;
  756. _dataTableSchema = null;
  757. disposed = true;
  758. }
  759. public
  760. #if NET_2_0
  761. override
  762. #endif // NET_2_0
  763. bool IsDBNull (int ordinal)
  764. {
  765. return (GetValue (ordinal) is DBNull);
  766. }
  767. /// <remarks>
  768. /// Move to the next result set.
  769. /// </remarks>
  770. public
  771. #if NET_2_0
  772. override
  773. #endif // NET_2_0
  774. bool NextResult ()
  775. {
  776. OdbcReturn ret = OdbcReturn.Success;
  777. ret = libodbc.SQLMoreResults (hstmt);
  778. if (ret == OdbcReturn.Success) {
  779. short colcount = 0;
  780. libodbc.SQLNumResultCols (hstmt, ref colcount);
  781. cols = new OdbcColumn [colcount];
  782. _dataTableSchema = null; // force fresh creation
  783. GetSchemaTable ();
  784. }
  785. return (ret==OdbcReturn.Success);
  786. }
  787. /// <remarks>
  788. /// Load the next row in the current result set.
  789. /// </remarks>
  790. private bool NextRow ()
  791. {
  792. OdbcReturn ret=libodbc.SQLFetch (hstmt);
  793. if (ret != OdbcReturn.Success)
  794. currentRow = -1;
  795. else
  796. currentRow++;
  797. // Clear cached values from last record
  798. foreach (OdbcColumn col in cols)
  799. {
  800. if (col != null)
  801. col.Value = null;
  802. }
  803. return (ret == OdbcReturn.Success);
  804. }
  805. private int GetColumnAttribute (int column, FieldIdentifier fieldId)
  806. {
  807. OdbcReturn ret = OdbcReturn.Error;
  808. byte [] buffer = new byte [255];
  809. short outsize = 0;
  810. int val = 0;
  811. ret = libodbc.SQLColAttribute (hstmt, (short)column, fieldId,
  812. buffer, (short)buffer.Length,
  813. ref outsize, ref val);
  814. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  815. throw new OdbcException (new OdbcError ("SQLColAttribute",
  816. OdbcHandleType.Stmt,
  817. hstmt)
  818. );
  819. return val;
  820. }
  821. private string GetColumnAttributeStr (int column, FieldIdentifier fieldId)
  822. {
  823. OdbcReturn ret = OdbcReturn.Error;
  824. byte [] buffer = new byte [255];
  825. short outsize = 0;
  826. int val = 0;
  827. ret = libodbc.SQLColAttribute (hstmt, (short)column, fieldId,
  828. buffer, (short)buffer.Length,
  829. ref outsize, ref val);
  830. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  831. throw new OdbcException (new OdbcError ("SQLColAttribute",
  832. OdbcHandleType.Stmt,
  833. hstmt)
  834. );
  835. string value = "";
  836. if (outsize > 0)
  837. value = Encoding.Default.GetString (buffer, 0, outsize);
  838. return value;
  839. }
  840. private string [] GetPrimaryKeys (string catalog, string schema, string table)
  841. {
  842. if (cols.Length <= 0)
  843. return new string [0];
  844. ArrayList keys = null;
  845. try {
  846. keys = GetPrimaryKeysBySQLPrimaryKey (catalog, schema, table);
  847. } catch (OdbcException){
  848. try {
  849. keys = GetPrimaryKeysBySQLStatistics (catalog, schema, table);
  850. } catch (OdbcException) {
  851. }
  852. }
  853. if (keys == null)
  854. return null;
  855. keys.Sort ();
  856. return (string []) keys.ToArray (typeof (string));
  857. }
  858. private ArrayList GetPrimaryKeysBySQLPrimaryKey (string catalog, string schema, string table)
  859. {
  860. ArrayList keys = new ArrayList ();
  861. IntPtr handle = IntPtr.Zero;
  862. OdbcReturn ret;
  863. try {
  864. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  865. command.Connection.hDbc, ref handle);
  866. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  867. throw new OdbcException(new OdbcError("SQLAllocHandle",
  868. OdbcHandleType.Dbc,
  869. command.Connection.hDbc));
  870. ret = libodbc.SQLPrimaryKeys (handle, catalog, -3,
  871. schema, -3,
  872. table, -3);
  873. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  874. throw new OdbcException (new OdbcError ("SQLPrimaryKeys", OdbcHandleType.Stmt, handle));
  875. int length = 0;
  876. byte [] primaryKey = new byte [255];
  877. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.CHAR, primaryKey, primaryKey.Length, ref length);
  878. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  879. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  880. int i = 0;
  881. while (true) {
  882. ret = libodbc.SQLFetch (handle);
  883. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  884. break;
  885. string pkey = Encoding.Default.GetString (primaryKey, 0, length);
  886. keys.Add (pkey);
  887. }
  888. } finally {
  889. if (handle != IntPtr.Zero) {
  890. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  891. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  892. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  893. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  894. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  895. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  896. }
  897. }
  898. return keys;
  899. }
  900. private unsafe ArrayList GetPrimaryKeysBySQLStatistics (string catalog, string schema, string table)
  901. {
  902. ArrayList keys = new ArrayList ();
  903. IntPtr handle = IntPtr.Zero;
  904. OdbcReturn ret;
  905. try {
  906. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  907. command.Connection.hDbc, ref handle);
  908. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  909. throw new OdbcException(new OdbcError("SQLAllocHandle",
  910. OdbcHandleType.Dbc,
  911. command.Connection.hDbc));
  912. ret = libodbc.SQLStatistics (handle, catalog, -3,
  913. schema, -3,
  914. table, -3,
  915. libodbc.SQL_INDEX_UNIQUE,
  916. libodbc.SQL_QUICK);
  917. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  918. throw new OdbcException (new OdbcError ("SQLStatistics", OdbcHandleType.Stmt, handle));
  919. // NON_UNIQUE
  920. int nonUniqueLength = 0;
  921. short nonUnique = libodbc.SQL_FALSE;
  922. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.SHORT, ref (short) nonUnique, sizeof (short), ref nonUniqueLength);
  923. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  924. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  925. // COLUMN_NAME
  926. int length = 0;
  927. byte [] colName = new byte [255];
  928. ret = libodbc.SQLBindCol (handle, 9, SQL_C_TYPE.CHAR, colName, colName.Length, ref length);
  929. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  930. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  931. int i = 0;
  932. while (true) {
  933. ret = libodbc.SQLFetch (handle);
  934. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  935. break;
  936. if (nonUnique == libodbc.SQL_TRUE) {
  937. string pkey = Encoding.Default.GetString (colName, 0, length);
  938. keys.Add (pkey);
  939. break;
  940. }
  941. }
  942. } finally {
  943. if (handle != IntPtr.Zero) {
  944. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  945. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  946. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  947. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  948. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  949. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  950. }
  951. }
  952. return keys;
  953. }
  954. public
  955. #if NET_2_0
  956. override
  957. #endif // NET_2_0
  958. bool Read ()
  959. {
  960. return NextRow ();
  961. }
  962. #endregion
  963. }
  964. }