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