OdbcDataReader.cs 33 KB

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