OdbcDataReader.cs 33 KB

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