Merge pull request #1685 from esdrubal/touint64
[mono.git] / mcs / class / System.Data / System.Data.Odbc / OdbcConnection.cs
1 //
2 // System.Data.Odbc.OdbcConnection
3 //
4 // Authors:
5 //  Brian Ritchie (brianlritchie@hotmail.com) 
6 //
7 // Copyright (C) Brian Ritchie, 2002
8 //
9
10 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System.Collections;
34 using System.ComponentModel;
35 using System.Data;
36 using System.Data.Common;
37 using System.EnterpriseServices;
38 using System.Runtime.InteropServices;
39 using System.Text;
40 using System.Transactions;
41
42 namespace System.Data.Odbc
43 {
44         [DefaultEvent ("InfoMessage")]
45         public sealed class OdbcConnection : DbConnection, ICloneable
46         {
47                 #region Fields
48
49                 string connectionString;
50                 int connectionTimeout;
51                 internal OdbcTransaction transaction;
52                 IntPtr henv = IntPtr.Zero;
53                 IntPtr hdbc = IntPtr.Zero;
54                 bool disposed;
55                 ArrayList linkedCommands;
56
57                 #endregion
58
59                 #region Constructors
60                 
61                 public OdbcConnection () : this (String.Empty)
62                 {
63                 }
64
65                 public OdbcConnection (string connectionString)
66                 {
67                         connectionTimeout = 15;
68                         ConnectionString = connectionString;
69                 }
70
71                 #endregion // Constructors
72
73                 #region Properties
74
75                 internal IntPtr hDbc {
76                         get { return hdbc; }
77                 }
78
79                 internal object Generation {
80                         // We use the linkedCommands array as a generation indicator for statement
81                         // handles allocated in our subsiduary OdbcCommands.  The rule is that the
82                         // statement handles are only valid if the generation matches the one
83                         // returned when the command was linked to the connection.
84                         get { return linkedCommands; }
85                 }
86
87                 [OdbcCategoryAttribute ("DataCategory_Data")]
88                 [DefaultValue ("")]
89                 [OdbcDescriptionAttribute ("Information used to connect to a Data Source")]
90                 [RefreshPropertiesAttribute (RefreshProperties.All)]
91                 [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
92                 [RecommendedAsConfigurableAttribute (true)]
93                 public
94                 override
95                 string ConnectionString {
96                         get {
97                                 if (connectionString == null)
98                                         return string.Empty;
99                                 return connectionString;
100                         }
101                         set { connectionString = value; }
102                 }
103                 
104                 [OdbcDescriptionAttribute ("Current connection timeout value, not settable  in the ConnectionString")]
105                 [DefaultValue (15)]
106                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
107                 public
108                 new
109                 int ConnectionTimeout {
110                         get {
111                                 return connectionTimeout;
112                         }
113                         set {
114                                 if (value < 0)
115                                         throw new ArgumentException("Timout should not be less than zero.");
116                                 connectionTimeout = value;
117                         }
118                 }
119
120                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
121                 [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
122                 public
123                 override
124                 string Database {
125                         get {
126                                 if (State == ConnectionState.Closed)
127                                         return string.Empty;
128                                 return GetInfo (OdbcInfo.DatabaseName);
129                         }
130                 }
131
132                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
133                 [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
134                 [BrowsableAttribute (false)]
135                 public
136                 override
137                 ConnectionState State {
138                         get {
139                                 if (hdbc != IntPtr.Zero)
140                                         return ConnectionState.Open;
141                                 return ConnectionState.Closed;
142                         }
143                 }
144
145                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
146                 [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
147                 [Browsable (false)]
148                 public
149                 override
150                 string DataSource {
151                         get {
152                                 if (State == ConnectionState.Closed)
153                                         return string.Empty;
154                                 return GetInfo (OdbcInfo.DataSourceName);
155                         }
156                 }
157
158                 [Browsable (false)]
159                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
160                 [OdbcDescriptionAttribute ("Current ODBC Driver")]
161                 public string Driver {
162                         get {
163                                 if (State == ConnectionState.Closed)
164                                         return string.Empty;
165
166                                 return GetInfo (OdbcInfo.DriverName);
167                         }
168                 }
169                 
170                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
171                 [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
172                 [BrowsableAttribute (false)]
173                 public
174                 override
175                 string ServerVersion {
176                         get {
177                                 return GetInfo (OdbcInfo.DbmsVersion);
178                         }
179                 }
180
181                 internal string SafeDriver {
182                         get {
183                                 string driver_name = GetSafeInfo (OdbcInfo.DriverName);
184                                 if (driver_name == null)
185                                         return string.Empty;
186                                 return driver_name;
187                         }
188                 }
189
190                 #endregion // Properties
191         
192                 #region Methods
193         
194                 public
195                 new
196                 OdbcTransaction BeginTransaction ()
197                 {
198                         return BeginTransaction (IsolationLevel.Unspecified);
199                 }
200
201
202                 protected override DbTransaction BeginDbTransaction (IsolationLevel isolationLevel)
203                 {
204                         return BeginTransaction (isolationLevel);
205                 }
206
207                 public
208                 new
209                 OdbcTransaction BeginTransaction (IsolationLevel isolevel)
210                 {
211                         if (State == ConnectionState.Closed)
212                                 throw ExceptionHelper.ConnectionClosed ();
213
214                         if (transaction == null) {
215                                 transaction = new OdbcTransaction (this, isolevel);
216                                 return transaction;
217                         } else
218                                 throw new InvalidOperationException ();
219                 }
220
221
222                 public
223                 override
224                 void Close ()
225                 {
226                         OdbcReturn ret = OdbcReturn.Error;
227                         if (State == ConnectionState.Open) {
228                                 lock(this) {
229                                         // close any associated commands
230                                         // NOTE: we may 'miss' some if the garbage collector has
231                                         // already started to destroy them.
232                                         if (linkedCommands != null) {
233                                                 for (int i = 0; i < linkedCommands.Count; i++) {
234                                                         WeakReference wr = (WeakReference) linkedCommands [i];
235                                                         if (wr == null)
236                                                                 continue;
237                                                         OdbcCommand c = (OdbcCommand) wr.Target;
238                                                         if (c != null)
239                                                                 c.Unlink ();
240                                                 }
241                                                 linkedCommands = null;
242                                         }
243
244                                         // disconnect
245                                         ret = libodbc.SQLDisconnect (hdbc);
246
247                                 }
248                                 // There could be OdbcCommands outstanding (see NOTE above); their
249                                 // hstmts will have been freed and therefore will be invalid.
250                                 // However, they will find that their definition of Generation
251                                 // does not match the connection's, so they won't try and free
252                                 // those hstmt.
253                                 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
254                                         throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
255
256                                 FreeHandles ();
257                                 transaction = null;
258                                 RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
259                         }
260                 }
261
262                 public
263                 new
264                 OdbcCommand CreateCommand ()
265                 {
266                         return new OdbcCommand (string.Empty, this, transaction);
267                 }
268
269                 public
270                 override
271                 void ChangeDatabase (string value)
272                 {
273                         IntPtr ptr = IntPtr.Zero;
274                         OdbcReturn ret = OdbcReturn.Error;
275
276                         try {
277                                 ptr = Marshal.StringToHGlobalUni (value);
278                                 ret = libodbc.SQLSetConnectAttr (hdbc, OdbcConnectionAttribute.CurrentCatalog, ptr, value.Length * 2);
279
280                                 if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
281                                         throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
282                         } finally {
283                                 if (ptr != IntPtr.Zero)
284                                         Marshal.FreeCoTaskMem (ptr);
285                         }
286                 }
287
288                 protected override void Dispose (bool disposing)
289                 {
290                         if (!this.disposed) {
291                                 try {
292                                         // release the native unmananged resources
293                                         this.Close ();
294                                         this.disposed = true;
295                                 } finally {
296                                         // call Dispose on the base class
297                                         base.Dispose (disposing);
298                                 }
299                         }
300                 }
301
302                 [MonoTODO]
303                 object ICloneable.Clone ()
304                 {
305                         throw new NotImplementedException ();
306                 }
307
308
309                 protected override DbCommand CreateDbCommand ()
310                 {
311                         return CreateCommand ();
312                 }
313
314                 public
315                 override
316                 void Open ()
317                 {
318                         if (State == ConnectionState.Open)
319                                 throw new InvalidOperationException ();
320
321                         OdbcReturn ret = OdbcReturn.Error;
322                         OdbcException e = null;
323                 
324                         try {
325                                 // allocate Environment handle
326                                 ret = libodbc.SQLAllocHandle (OdbcHandleType.Env, IntPtr.Zero, ref henv);
327                                 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) {
328                                         OdbcErrorCollection errors = new OdbcErrorCollection ();
329                                         errors.Add (new OdbcError (SafeDriver, "Error in " + SafeDriver, "", 1));
330                                         e = new OdbcException (errors);
331                                         MessageHandler (e);
332                                         throw e;
333                                 }
334
335                                 ret = libodbc.SQLSetEnvAttr (henv, OdbcEnv.OdbcVersion, (IntPtr) libodbc.SQL_OV_ODBC3 , 0); 
336                                 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
337                                         throw CreateOdbcException (OdbcHandleType.Env, henv);
338
339                                 // allocate connection handle
340                                 ret = libodbc.SQLAllocHandle (OdbcHandleType.Dbc, henv, ref hdbc);
341                                 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
342                                         throw CreateOdbcException (OdbcHandleType.Env, henv);
343
344                                 // DSN connection
345                                 if (ConnectionString.ToLower ().IndexOf ("dsn=") >= 0) {
346                                         string _uid = string.Empty, _pwd = string.Empty, _dsn = string.Empty;
347                                         string [] items = ConnectionString.Split (new char[1] {';'});
348                                         foreach (string item in items)
349                                         {
350                                                 string [] parts = item.Split (new char[1] {'='});
351                                                 switch (parts [0].Trim ().ToLower ()) {
352                                                 case "dsn":
353                                                         _dsn = parts [1].Trim ();
354                                                         break;
355                                                 case "uid":
356                                                         _uid = parts [1].Trim ();
357                                                         break;
358                                                 case "pwd":
359                                                         _pwd = parts [1].Trim ();
360                                                         break;
361                                                 }
362                                         }
363                                         ret = libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3);
364                                         if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
365                                                 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
366                                 } else {
367                                         // DSN-less Connection
368                                         string OutConnectionString = new String (' ',1024);
369                                         short OutLen = 0;
370                                         ret = libodbc.SQLDriverConnect (hdbc, IntPtr.Zero, ConnectionString, -3, 
371                                                 OutConnectionString, (short) OutConnectionString.Length, ref OutLen, 0);
372                                         if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
373                                                 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
374                                 }
375
376                                 RaiseStateChange (ConnectionState.Closed, ConnectionState.Open);
377                         } catch {
378                                 // free handles if any.
379                                 FreeHandles ();
380                                 throw;
381                         }
382                         disposed = false;
383                 }
384
385                 [MonoTODO]
386                 public static void ReleaseObjectPool ()
387                 {
388                         throw new NotImplementedException ();
389                 }
390
391                 private void FreeHandles ()
392                 {
393                         OdbcReturn ret = OdbcReturn.Error;
394                         if (hdbc != IntPtr.Zero) {
395                                 ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Dbc, hdbc);
396                                 if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
397                                         throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
398                         }
399                         hdbc = IntPtr.Zero;
400
401                         if (henv != IntPtr.Zero) {
402                                 ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Env, henv);
403                                 if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
404                                         throw CreateOdbcException (OdbcHandleType.Env, henv);
405                         }
406                         henv = IntPtr.Zero;
407                 }
408
409                 public override DataTable GetSchema ()
410                 {
411                         if (State == ConnectionState.Closed)
412                                 throw ExceptionHelper.ConnectionClosed ();
413                         return MetaDataCollections.Instance;
414                 }
415
416                 public override DataTable GetSchema (string collectionName)
417                 {
418                         return GetSchema (collectionName, null);
419                 }
420
421                 public override DataTable GetSchema (string collectionName, string [] restrictionValues)
422                 {
423                         if (State == ConnectionState.Closed)
424                                 throw ExceptionHelper.ConnectionClosed ();
425                         return GetSchema (collectionName, null);
426                 }
427
428                 [MonoTODO]
429                 public override void EnlistTransaction (Transaction transaction)
430                 {
431                         throw new NotImplementedException ();
432                 }
433
434                 [MonoTODO]
435                 public void EnlistDistributedTransaction (ITransaction transaction)
436                 {
437                         throw new NotImplementedException ();
438                 }
439
440                 internal string GetInfo (OdbcInfo info)
441                 {
442                         if (State == ConnectionState.Closed)
443                                 throw new InvalidOperationException ("The connection is closed.");
444
445                         OdbcReturn ret = OdbcReturn.Error;
446                         short max_length = 512;
447                         byte [] buffer = new byte [512];
448                         short actualLength = 0;
449
450                         ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
451                         if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
452                                 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
453                         return Encoding.Unicode.GetString (buffer, 0, actualLength);
454                 }
455
456                 string GetSafeInfo (OdbcInfo info)
457                 {
458                         if (State == ConnectionState.Closed)
459                                 return null;
460
461                         OdbcReturn ret = OdbcReturn.Error;
462                         short max_length = 512;
463                         byte [] buffer = new byte [512];
464                         short actualLength = 0;
465
466                         ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
467                         if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
468                                 return null;
469                         return Encoding.Unicode.GetString (buffer, 0, actualLength);
470                 }
471
472                 private void RaiseStateChange (ConnectionState from, ConnectionState to)
473                 {
474                         base.OnStateChange (new StateChangeEventArgs (from, to));
475                 }
476
477                 private OdbcInfoMessageEventArgs CreateOdbcInfoMessageEvent (OdbcErrorCollection errors)
478                 {
479                         return new OdbcInfoMessageEventArgs (errors);
480                 }
481
482                 private void OnOdbcInfoMessage (OdbcInfoMessageEventArgs e)
483                 {
484                         if (InfoMessage != null)
485                                 InfoMessage (this, e);
486                 }
487
488                 internal OdbcException CreateOdbcException (OdbcHandleType HandleType, IntPtr Handle)
489                 {
490                         short buflen = 256;
491                         short txtlen = 0;
492                         int nativeerror = 0;
493                         OdbcReturn ret = OdbcReturn.Success;
494
495                         OdbcErrorCollection errors = new OdbcErrorCollection ();
496
497                         while (true) {
498                                 byte [] buf_MsgText = new byte [buflen * 2];
499                                 byte [] buf_SqlState = new byte [buflen * 2];
500
501                                 switch (HandleType) {
502                                 case OdbcHandleType.Dbc:
503                                         ret = libodbc.SQLError (IntPtr.Zero, Handle, IntPtr.Zero, buf_SqlState,
504                                                 ref nativeerror, buf_MsgText, buflen, ref txtlen);
505                                         break;
506                                 case OdbcHandleType.Stmt:
507                                         ret = libodbc.SQLError (IntPtr.Zero, IntPtr.Zero, Handle, buf_SqlState,
508                                                 ref nativeerror, buf_MsgText, buflen, ref txtlen);
509                                         break;
510                                 case OdbcHandleType.Env:
511                                         ret = libodbc.SQLError (Handle, IntPtr.Zero, IntPtr.Zero, buf_SqlState,
512                                                 ref nativeerror, buf_MsgText, buflen, ref txtlen);
513                                         break;
514                                 }
515
516                                 if (ret != OdbcReturn.Success)
517                                         break;
518
519                                 string state = RemoveTrailingNullChar (Encoding.Unicode.GetString (buf_SqlState));
520                                 string message = Encoding.Unicode.GetString (buf_MsgText, 0, txtlen * 2);
521
522                                 errors.Add (new OdbcError (SafeDriver, message, state, nativeerror));
523                         }
524
525                         string source = SafeDriver;
526                         foreach (OdbcError error in errors)
527                                 error.SetSource (source);
528                         return new OdbcException (errors);
529                 }
530
531                 static string RemoveTrailingNullChar (string value)
532                 {
533                         return value.TrimEnd ('\0');
534                 }
535
536                 internal object Link (OdbcCommand cmd)
537                 {
538                         lock(this) {
539                                 if (linkedCommands == null)
540                                         linkedCommands = new ArrayList ();
541                                 linkedCommands.Add (new WeakReference (cmd));
542                                 return linkedCommands;
543                         }
544                 }
545
546                 internal object Unlink (OdbcCommand cmd)
547                 {
548                         lock(this) {
549                                 if (linkedCommands == null)
550                                         return null;
551
552                                 for (int i = 0; i < linkedCommands.Count; i++) {
553                                         WeakReference wr = (WeakReference) linkedCommands [i];
554                                         if (wr == null)
555                                                 continue;
556                                         OdbcCommand c = (OdbcCommand) wr.Target;
557                                         if (c == cmd) {
558                                                 linkedCommands [i] = null;
559                                                 break;
560                                         }
561                                 }
562                                 return linkedCommands;
563                         }
564                 }
565
566                 #endregion
567
568                 #region Events and Delegates
569
570
571                 [OdbcDescription ("DbConnection_InfoMessage")]
572                 [OdbcCategory ("DataCategory_InfoMessage")]
573                 public event OdbcInfoMessageEventHandler InfoMessage;
574
575                 private void MessageHandler (OdbcException e)
576                 {
577                         OnOdbcInfoMessage (CreateOdbcInfoMessageEvent (e.Errors));
578                 }
579
580                 #endregion
581         }
582 }