OdbcDataReader.cs 32 KB

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