OdbcDataReader.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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.IsVariableSizeType)
  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 < 127 ? (col.MaxLength*2+1) : 255);
  619. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  620. StringBuilder sb = new StringBuilder ();
  621. do {
  622. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  623. if (ret == OdbcReturn.Error)
  624. break;
  625. if (ret != OdbcReturn.NoData && outsize!=-1) {
  626. if (outsize < bufsize)
  627. sb.Append (System.Text.Encoding.Unicode.GetString(buffer,0,outsize));
  628. else
  629. sb.Append (System.Text.Encoding.Unicode.GetString(buffer,0,bufsize));
  630. }
  631. } while (ret != OdbcReturn.NoData);
  632. DataValue = sb.ToString ();
  633. break;
  634. case OdbcType.Text:
  635. case OdbcType.VarChar:
  636. bufsize=(col.MaxLength < 255 ? (col.MaxLength+1) : 255);
  637. buffer=new byte[bufsize]; // According to sqlext.h, use SQL_CHAR for both char and varchar
  638. StringBuilder sb1 = new StringBuilder ();
  639. do {
  640. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, buffer, bufsize, ref outsize);
  641. if (ret == OdbcReturn.Error)
  642. break;
  643. if (ret != OdbcReturn.NoData && outsize!=-1) {
  644. if (outsize < bufsize)
  645. sb1.Append (System.Text.Encoding.Default.GetString(buffer,0,outsize));
  646. else
  647. sb1.Append (System.Text.Encoding.Default.GetString(buffer,0,bufsize));
  648. }
  649. } while (ret != OdbcReturn.NoData);
  650. DataValue = sb1.ToString ();
  651. break;
  652. case OdbcType.Real:
  653. float float_data=0;
  654. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref float_data, 0, ref outsize);
  655. DataValue=float_data;
  656. break;
  657. case OdbcType.Double:
  658. double double_data=0;
  659. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref double_data, 0, ref outsize);
  660. DataValue=double_data;
  661. break;
  662. case OdbcType.Timestamp:
  663. case OdbcType.DateTime:
  664. case OdbcType.Date:
  665. case OdbcType.Time:
  666. OdbcTimestamp ts_data=new OdbcTimestamp();
  667. ret=libodbc.SQLGetData(hstmt, ColIndex, col.SqlCType, ref ts_data, 0, ref outsize);
  668. if (outsize!=-1) // This means SQL_NULL_DATA
  669. DataValue=new DateTime(ts_data.year,ts_data.month,ts_data.day,ts_data.hour,
  670. ts_data.minute,ts_data.second,Convert.ToInt32(ts_data.fraction));
  671. break;
  672. case OdbcType.VarBinary :
  673. case OdbcType.Image :
  674. bufsize= (col.MaxLength < 255 ? col.MaxLength : 255);
  675. buffer= new byte [bufsize];
  676. ArrayList al = new ArrayList ();
  677. do {
  678. ret=libodbc.SQLGetData (hstmt, ColIndex, SQL_C_TYPE.BINARY, buffer, bufsize, ref outsize);
  679. if (ret == OdbcReturn.Error)
  680. break;
  681. if (ret != OdbcReturn.NoData && outsize!=-1) {
  682. if (outsize < bufsize) {
  683. byte[] tmparr = new byte [outsize];
  684. Array.Copy (buffer, 0, tmparr, 0, outsize);
  685. al.AddRange (tmparr);
  686. } else
  687. al.AddRange (buffer);
  688. }
  689. } while (ret != OdbcReturn.NoData);
  690. DataValue = al.ToArray (typeof (byte));
  691. break;
  692. case OdbcType.Binary :
  693. bufsize = col.MaxLength;
  694. buffer = new byte [bufsize];
  695. long read = GetBytes (ordinal, 0, buffer, 0, bufsize);
  696. ret = OdbcReturn.Success;
  697. DataValue = buffer;
  698. break;
  699. default:
  700. bufsize=255;
  701. buffer=new byte[bufsize];
  702. ret=libodbc.SQLGetData(hstmt, ColIndex, SQL_C_TYPE.CHAR, buffer, bufsize, ref outsize);
  703. if (outsize != (int) OdbcLengthIndicator.NullData)
  704. if (! (ret == OdbcReturn.SuccessWithInfo
  705. && outsize == (int) OdbcLengthIndicator.NoTotal))
  706. DataValue=System.Text.Encoding.Default.GetString(buffer, 0, outsize);
  707. break;
  708. }
  709. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo) && (ret!=OdbcReturn.NoData))
  710. throw new OdbcException(new OdbcError("SQLGetData",OdbcHandleType.Stmt,hstmt));
  711. if (outsize==-1) // This means SQL_NULL_DATA
  712. col.Value=DBNull.Value;
  713. else
  714. col.Value=DataValue;
  715. }
  716. return col.Value;
  717. }
  718. public
  719. #if NET_2_0
  720. override
  721. #endif // NET_2_0
  722. int GetValues (object[] values)
  723. {
  724. int numValues = 0;
  725. // copy values
  726. for (int i = 0; i < values.Length; i++) {
  727. if (i < FieldCount) {
  728. values[i] = GetValue(i);
  729. }
  730. else {
  731. values[i] = null;
  732. }
  733. }
  734. // get number of object instances in array
  735. if (values.Length < FieldCount)
  736. numValues = values.Length;
  737. else if (values.Length == FieldCount)
  738. numValues = FieldCount;
  739. else
  740. numValues = FieldCount;
  741. return numValues;
  742. }
  743. #if ONLY_1_1
  744. void IDisposable.Dispose ()
  745. {
  746. Dispose (true);
  747. GC.SuppressFinalize (this);
  748. }
  749. IEnumerator IEnumerable.GetEnumerator ()
  750. {
  751. return new DbEnumerator (this);
  752. }
  753. #endif // ONLY_1_1
  754. #if NET_2_0
  755. protected override
  756. #endif
  757. void Dispose (bool disposing)
  758. {
  759. if (disposed)
  760. return;
  761. if (disposing) {
  762. // dispose managed resources
  763. Close ();
  764. }
  765. command = null;
  766. cols = null;
  767. _dataTableSchema = null;
  768. disposed = true;
  769. }
  770. public
  771. #if NET_2_0
  772. override
  773. #endif // NET_2_0
  774. bool IsDBNull (int ordinal)
  775. {
  776. return (GetValue(ordinal) is DBNull);
  777. }
  778. /// <remarks>
  779. /// Move to the next result set.
  780. /// </remarks>
  781. public
  782. #if NET_2_0
  783. override
  784. #endif // NET_2_0
  785. bool NextResult ()
  786. {
  787. OdbcReturn ret = OdbcReturn.Success;
  788. ret = libodbc.SQLMoreResults (hstmt);
  789. if (ret == OdbcReturn.Success) {
  790. short colcount = 0;
  791. libodbc.SQLNumResultCols (hstmt, ref colcount);
  792. cols = new OdbcColumn [colcount];
  793. _dataTableSchema = null; // force fresh creation
  794. GetSchemaTable ();
  795. }
  796. return (ret==OdbcReturn.Success);
  797. }
  798. /// <remarks>
  799. /// Load the next row in the current result set.
  800. /// </remarks>
  801. private bool NextRow ()
  802. {
  803. OdbcReturn ret=libodbc.SQLFetch (hstmt);
  804. if (ret != OdbcReturn.Success)
  805. currentRow = -1;
  806. else
  807. currentRow++;
  808. // Clear cached values from last record
  809. foreach (OdbcColumn col in cols)
  810. {
  811. if (col != null)
  812. col.Value = null;
  813. }
  814. return (ret == OdbcReturn.Success);
  815. }
  816. private int GetColumnAttribute (int column, FieldIdentifier fieldId)
  817. {
  818. OdbcReturn ret = OdbcReturn.Error;
  819. byte [] buffer = new byte [255];
  820. int outsize = 0;
  821. int val = 0;
  822. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  823. buffer, buffer.Length,
  824. ref outsize, ref val);
  825. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  826. throw new OdbcException (new OdbcError ("SQLColAttribute",
  827. OdbcHandleType.Stmt,
  828. hstmt)
  829. );
  830. return val;
  831. }
  832. private string GetColumnAttributeStr (int column, FieldIdentifier fieldId)
  833. {
  834. OdbcReturn ret = OdbcReturn.Error;
  835. byte [] buffer = new byte [255];
  836. int outsize = 0;
  837. int val = 0;
  838. ret = libodbc.SQLColAttribute (hstmt, column, fieldId,
  839. buffer, buffer.Length,
  840. ref outsize, ref val);
  841. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  842. throw new OdbcException (new OdbcError ("SQLColAttribute",
  843. OdbcHandleType.Stmt,
  844. hstmt)
  845. );
  846. string value = "";
  847. if (outsize > 0)
  848. value = Encoding.Default.GetString (buffer, 0, outsize);
  849. return value;
  850. }
  851. private string [] GetPrimaryKeys (string catalog, string schema, string table)
  852. {
  853. if (cols.Length <= 0)
  854. return new string [0];
  855. ArrayList keys = null;
  856. try {
  857. keys = GetPrimaryKeysBySQLPrimaryKey (catalog, schema, table);
  858. } catch (OdbcException){
  859. try {
  860. keys = GetPrimaryKeysBySQLStatistics (catalog, schema, table);
  861. } catch (OdbcException) {
  862. }
  863. }
  864. keys.Sort ();
  865. return (string []) keys.ToArray (typeof (string));
  866. }
  867. private ArrayList GetPrimaryKeysBySQLPrimaryKey (string catalog, string schema, string table)
  868. {
  869. ArrayList keys = new ArrayList ();
  870. IntPtr handle = IntPtr.Zero;
  871. OdbcReturn ret;
  872. try {
  873. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  874. command.Connection.hDbc, ref handle);
  875. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  876. throw new OdbcException(new OdbcError("SQLAllocHandle",
  877. OdbcHandleType.Dbc,
  878. command.Connection.hDbc));
  879. ret = libodbc.SQLPrimaryKeys (handle, catalog, -3,
  880. schema, -3,
  881. table, -3);
  882. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  883. throw new OdbcException (new OdbcError ("SQLPrimaryKeys", OdbcHandleType.Stmt, handle));
  884. int length = 0;
  885. byte [] primaryKey = new byte [255];
  886. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.CHAR, primaryKey, primaryKey.Length, ref length);
  887. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  888. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  889. int i = 0;
  890. while (true) {
  891. ret = libodbc.SQLFetch (handle);
  892. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  893. break;
  894. string pkey = Encoding.Default.GetString (primaryKey, 0, length);
  895. keys.Add (pkey);
  896. }
  897. } finally {
  898. if (handle != IntPtr.Zero) {
  899. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  900. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  901. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  902. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  903. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  904. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  905. }
  906. }
  907. return keys;
  908. }
  909. private unsafe ArrayList GetPrimaryKeysBySQLStatistics (string catalog, string schema, string table)
  910. {
  911. ArrayList keys = new ArrayList ();
  912. IntPtr handle = IntPtr.Zero;
  913. OdbcReturn ret;
  914. try {
  915. ret=libodbc.SQLAllocHandle(OdbcHandleType.Stmt,
  916. command.Connection.hDbc, ref handle);
  917. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  918. throw new OdbcException(new OdbcError("SQLAllocHandle",
  919. OdbcHandleType.Dbc,
  920. command.Connection.hDbc));
  921. ret = libodbc.SQLStatistics (handle, catalog, -3,
  922. schema, -3,
  923. table, -3,
  924. libodbc.SQL_INDEX_UNIQUE,
  925. libodbc.SQL_QUICK);
  926. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  927. throw new OdbcException (new OdbcError ("SQLStatistics", OdbcHandleType.Stmt, handle));
  928. // NON_UNIQUE
  929. int nonUniqueLength = 0;
  930. short nonUnique = libodbc.SQL_FALSE;
  931. ret = libodbc.SQLBindCol (handle, 4, SQL_C_TYPE.SHORT, ref (short) nonUnique, sizeof (short), ref nonUniqueLength);
  932. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  933. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  934. // COLUMN_NAME
  935. int length = 0;
  936. byte [] colName = new byte [255];
  937. ret = libodbc.SQLBindCol (handle, 9, SQL_C_TYPE.CHAR, colName, colName.Length, ref length);
  938. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  939. throw new OdbcException (new OdbcError ("SQLBindCol", OdbcHandleType.Stmt, handle));
  940. int i = 0;
  941. while (true) {
  942. ret = libodbc.SQLFetch (handle);
  943. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  944. break;
  945. if (nonUnique == libodbc.SQL_TRUE) {
  946. string pkey = Encoding.Default.GetString (colName, 0, length);
  947. keys.Add (pkey);
  948. break;
  949. }
  950. }
  951. } finally {
  952. if (handle != IntPtr.Zero) {
  953. ret = libodbc.SQLFreeStmt (handle, libodbc.SQLFreeStmtOptions.Close);
  954. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  955. throw new OdbcException(new OdbcError("SQLFreeStmt",OdbcHandleType.Stmt,handle));
  956. ret = libodbc.SQLFreeHandle( (ushort) OdbcHandleType.Stmt, handle);
  957. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  958. throw new OdbcException(new OdbcError("SQLFreeHandle",OdbcHandleType.Stmt,handle));
  959. }
  960. }
  961. return keys;
  962. }
  963. public
  964. #if NET_2_0
  965. override
  966. #endif // NET_2_0
  967. bool Read ()
  968. {
  969. return NextRow ();
  970. }
  971. #if NET_2_0
  972. [MonoTODO]
  973. public override object GetProviderSpecificValue (int i)
  974. {
  975. throw new NotImplementedException ();
  976. }
  977. [MonoTODO]
  978. public override int GetProviderSpecificValues (object[] values)
  979. {
  980. throw new NotImplementedException ();
  981. }
  982. [MonoTODO]
  983. public override Type GetProviderSpecificFieldType (int i)
  984. {
  985. throw new NotImplementedException ();
  986. }
  987. #endif // NET_2_0
  988. #endregion
  989. }
  990. }