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