f738a187a8dc03c03f18067eaad96122f3e94a02
[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 #if NET_2_0 && !TARGET_JVM
41 using System.Transactions;
42 #endif
43
44 namespace System.Data.Odbc
45 {
46         [DefaultEvent ("InfoMessage")]
47 #if NET_2_0
48         public sealed class OdbcConnection : DbConnection, ICloneable
49 #else
50         public sealed class OdbcConnection : Component, ICloneable, IDbConnection
51 #endif //NET_2_0
52         {
53                 #region Fields
54
55                 string connectionString;
56                 int connectionTimeout;
57                 internal OdbcTransaction transaction;
58                 IntPtr henv = IntPtr.Zero;
59                 IntPtr hdbc = IntPtr.Zero;
60                 bool disposed;
61                 ArrayList linkedCommands;
62
63                 #endregion
64
65                 #region Constructors
66                 
67                 public OdbcConnection () : this (String.Empty)
68                 {
69                 }
70
71                 public OdbcConnection (string connectionString)
72                 {
73                         connectionTimeout = 15;
74                         ConnectionString = connectionString;
75                 }
76
77                 #endregion // Constructors
78
79                 #region Properties
80
81                 internal IntPtr hDbc {
82                         get { return hdbc; }
83                 }
84
85                 internal object Generation {
86                         // We use the linkedCommands array as a generation indicator for statement
87                         // handles allocated in our subsiduary OdbcCommands.  The rule is that the
88                         // statement handles are only valid if the generation matches the one
89                         // returned when the command was linked to the connection.
90                         get { return linkedCommands; }
91                 }
92
93                 [OdbcCategoryAttribute ("DataCategory_Data")]
94                 [DefaultValue ("")]
95                 [OdbcDescriptionAttribute ("Information used to connect to a Data Source")]
96                 [RefreshPropertiesAttribute (RefreshProperties.All)]
97                 [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
98                 [RecommendedAsConfigurableAttribute (true)]
99                 public
100 #if NET_2_0
101                 override
102 #endif
103                 string ConnectionString {
104                         get {
105                                 if (connectionString == null)
106                                         return string.Empty;
107                                 return connectionString;
108                         }
109                         set { connectionString = value; }
110                 }
111                 
112                 [OdbcDescriptionAttribute ("Current connection timeout value, not settable  in the ConnectionString")]
113                 [DefaultValue (15)]
114 #if NET_2_0
115                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
116 #endif
117                 public
118 #if NET_2_0
119                 new
120 #endif // NET_2_0
121                 int ConnectionTimeout {
122                         get {
123                                 return connectionTimeout;
124                         }
125                         set {
126                                 if (value < 0)
127                                         throw new ArgumentException("Timout should not be less than zero.");
128                                 connectionTimeout = value;
129                         }
130                 }
131
132                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
133                 [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
134                 public
135 #if NET_2_0
136                 override
137 #endif // NET_2_0
138                 string Database {
139                         get {
140                                 if (State == ConnectionState.Closed)
141                                         return string.Empty;
142                                 return GetInfo (OdbcInfo.DatabaseName);
143                         }
144                 }
145
146                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
147                 [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
148                 [BrowsableAttribute (false)]
149                 public
150 #if NET_2_0
151                 override
152 #endif // NET_2_0
153                 ConnectionState State {
154                         get {
155                                 if (hdbc != IntPtr.Zero)
156                                         return ConnectionState.Open;
157                                 return ConnectionState.Closed;
158                         }
159                 }
160
161                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
162                 [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
163 #if NET_2_0
164                 [Browsable (false)]
165 #endif
166                 public
167 #if NET_2_0
168                 override
169 #endif // NET_2_0
170                 string DataSource {
171                         get {
172                                 if (State == ConnectionState.Closed)
173                                         return string.Empty;
174                                 return GetInfo (OdbcInfo.DataSourceName);
175                         }
176                 }
177
178 #if NET_2_0
179                 [Browsable (false)]
180 #endif
181                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
182                 [OdbcDescriptionAttribute ("Current ODBC Driver")]
183                 public string Driver {
184                         get {
185                                 if (State == ConnectionState.Closed)
186                                         return string.Empty;
187
188                                 return GetInfo (OdbcInfo.DriverName);
189                         }
190                 }
191                 
192                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
193                 [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
194                 [BrowsableAttribute (false)]
195                 public
196 #if NET_2_0
197                 override
198 #endif // NET_2_0
199                 string ServerVersion {
200                         get {
201                                 return GetInfo (OdbcInfo.DbmsVersion);
202                         }
203                 }
204
205                 internal string SafeDriver {
206                         get {
207                                 string driver_name = GetSafeInfo (OdbcInfo.DriverName);
208                                 if (driver_name == null)
209                                         return string.Empty;
210                                 return driver_name;
211                         }
212                 }
213
214                 #endregion // Properties
215         
216                 #region Methods
217         
218                 public
219 #if NET_2_0
220                 new
221 #endif // NET_2_0
222                 OdbcTransaction BeginTransaction ()
223                 {
224                         return BeginTransaction (IsolationLevel.Unspecified);
225                 }
226
227 #if ONLY_1_1
228                 IDbTransaction IDbConnection.BeginTransaction ()
229                 {
230                         return (IDbTransaction) BeginTransaction ();
231                 }
232 #endif // ONLY_1_1
233
234 #if NET_2_0
235                 protected override DbTransaction BeginDbTransaction (IsolationLevel isolationLevel)
236                 {
237                         return BeginTransaction (isolationLevel);
238                 }
239 #endif
240
241                 public
242 #if NET_2_0
243                 new
244 #endif // NET_2_0
245                 OdbcTransaction BeginTransaction (IsolationLevel isolevel)
246                 {
247                         if (State == ConnectionState.Closed)
248                                 throw ExceptionHelper.ConnectionClosed ();
249
250                         if (transaction == null) {
251                                 transaction = new OdbcTransaction (this, isolevel);
252                                 return transaction;
253                         } else
254                                 throw new InvalidOperationException ();
255                 }
256
257 #if ONLY_1_1
258                 IDbTransaction IDbConnection.BeginTransaction (IsolationLevel isolevel)
259                 {
260                         return (IDbTransaction) BeginTransaction (isolevel);
261                 }
262 #endif // ONLY_1_1
263
264                 public
265 #if NET_2_0
266                 override
267 #endif // NET_2_0
268                 void Close ()
269                 {
270                         OdbcReturn ret = OdbcReturn.Error;
271                         if (State == ConnectionState.Open) {
272                                 lock(this) {
273                                         // close any associated commands
274                                         // NOTE: we may 'miss' some if the garbage collector has
275                                         // already started to destroy them.
276                                         if (linkedCommands != null) {
277                                                 for (int i = 0; i < linkedCommands.Count; i++) {
278                                                         WeakReference wr = (WeakReference) linkedCommands [i];
279                                                         if (wr == null)
280                                                                 continue;
281                                                         OdbcCommand c = (OdbcCommand) wr.Target;
282                                                         if (c != null)
283                                                                 c.Unlink ();
284                                                 }
285                                                 linkedCommands = null;
286                                         }
287
288                                         // disconnect
289                                         ret = libodbc.SQLDisconnect (hdbc);
290
291                                 }
292                                 // There could be OdbcCommands outstanding (see NOTE above); their
293                                 // hstmts will have been freed and therefore will be invalid.
294                                 // However, they will find that their definition of Generation
295                                 // does not match the connection's, so they won't try and free
296                                 // those hstmt.
297                                 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
298                                         throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
299
300                                 FreeHandles ();
301                                 transaction = null;
302                                 RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
303                         }
304                 }
305
306                 public
307 #if NET_2_0
308                 new
309 #endif // NET_2_0
310                 OdbcCommand CreateCommand ()
311                 {
312                         return new OdbcCommand (string.Empty, this, transaction);
313                 }
314
315                 public
316 #if NET_2_0
317                 override
318 #endif // NET_2_0
319                 void ChangeDatabase (string value)
320                 {
321                         IntPtr ptr = IntPtr.Zero;
322                         OdbcReturn ret = OdbcReturn.Error;
323
324                         try {
325                                 ptr = Marshal.StringToHGlobalUni (value);
326                                 ret = libodbc.SQLSetConnectAttr (hdbc, OdbcConnectionAttribute.CurrentCatalog, ptr, value.Length * 2);
327
328                                 if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
329                                         throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
330                         } finally {
331                                 if (ptr != IntPtr.Zero)
332                                         Marshal.FreeCoTaskMem (ptr);
333                         }
334                 }
335
336                 protected override void Dispose (bool disposing)
337                 {
338                         if (!this.disposed) {
339                                 try {
340                                         // release the native unmananged resources
341                                         this.Close ();
342                                         this.disposed = true;
343                                 } finally {
344                                         // call Dispose on the base class
345                                         base.Dispose (disposing);
346                                 }
347                         }
348                 }
349
350                 [MonoTODO]
351                 object ICloneable.Clone ()
352                 {
353                         throw new NotImplementedException ();
354                 }
355
356 #if ONLY_1_1
357                 IDbCommand IDbConnection.CreateCommand ()
358                 {
359                         return (IDbCommand) CreateCommand ();
360                 }
361 #endif //ONLY_1_1
362
363 #if NET_2_0
364                 protected override DbCommand CreateDbCommand ()
365                 {
366                         return CreateCommand ();
367                 }
368 #endif
369
370                 public
371 #if NET_2_0
372                 override
373 #endif // NET_2_0
374                 void Open ()
375                 {
376                         if (State == ConnectionState.Open)
377                                 throw new InvalidOperationException ();
378
379                         OdbcReturn ret = OdbcReturn.Error;
380                         OdbcException e = null;
381                 
382                         try {
383                                 // allocate Environment handle
384                                 ret = libodbc.SQLAllocHandle (OdbcHandleType.Env, IntPtr.Zero, ref henv);
385                                 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) {
386                                         OdbcErrorCollection errors = new OdbcErrorCollection ();
387                                         errors.Add (new OdbcError (this));
388                                         e = new OdbcException (errors);
389                                         MessageHandler (e);
390                                         throw e;
391                                 }
392
393                                 ret = libodbc.SQLSetEnvAttr (henv, OdbcEnv.OdbcVersion, (IntPtr) libodbc.SQL_OV_ODBC3 , 0); 
394                                 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
395                                         throw CreateOdbcException (OdbcHandleType.Env, henv);
396
397                                 // allocate connection handle
398                                 ret = libodbc.SQLAllocHandle (OdbcHandleType.Dbc, henv, ref hdbc);
399                                 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
400                                         throw CreateOdbcException (OdbcHandleType.Env, henv);
401
402                                 // DSN connection
403                                 if (ConnectionString.ToLower ().IndexOf ("dsn=") >= 0) {
404                                         string _uid = string.Empty, _pwd = string.Empty, _dsn = string.Empty;
405                                         string [] items = ConnectionString.Split (new char[1] {';'});
406                                         foreach (string item in items)
407                                         {
408                                                 string [] parts = item.Split (new char[1] {'='});
409                                                 switch (parts [0].Trim ().ToLower ()) {
410                                                 case "dsn":
411                                                         _dsn = parts [1].Trim ();
412                                                         break;
413                                                 case "uid":
414                                                         _uid = parts [1].Trim ();
415                                                         break;
416                                                 case "pwd":
417                                                         _pwd = parts [1].Trim ();
418                                                         break;
419                                                 }
420                                         }
421                                         ret = libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3);
422                                         if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
423                                                 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
424                                 } else {
425                                         // DSN-less Connection
426                                         string OutConnectionString = new String (' ',1024);
427                                         short OutLen = 0;
428                                         ret = libodbc.SQLDriverConnect (hdbc, IntPtr.Zero, ConnectionString, -3, 
429                                                 OutConnectionString, (short) OutConnectionString.Length, ref OutLen, 0);
430                                         if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
431                                                 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
432                                 }
433
434                                 RaiseStateChange (ConnectionState.Closed, ConnectionState.Open);
435                         } catch {
436                                 // free handles if any.
437                                 FreeHandles ();
438                                 throw;
439                         }
440                         disposed = false;
441                 }
442
443                 [MonoTODO]
444                 public static void ReleaseObjectPool ()
445                 {
446                         throw new NotImplementedException ();
447                 }
448
449                 private void FreeHandles ()
450                 {
451                         OdbcReturn ret = OdbcReturn.Error;
452                         if (hdbc != IntPtr.Zero) {
453                                 ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Dbc, hdbc);
454                                 if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
455                                         throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
456                         }
457                         hdbc = IntPtr.Zero;
458
459                         if (henv != IntPtr.Zero) {
460                                 ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Env, henv);
461                                 if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
462                                         throw CreateOdbcException (OdbcHandleType.Env, henv);
463                         }
464                         henv = IntPtr.Zero;
465                 }
466
467 #if NET_2_0
468                 public override DataTable GetSchema ()
469                 {
470                         if (State == ConnectionState.Closed)
471                                 throw ExceptionHelper.ConnectionClosed ();
472                         return MetaDataCollections.Instance;
473                 }
474
475                 public override DataTable GetSchema (string collectionName)
476                 {
477                         return GetSchema (collectionName, null);
478                 }
479
480                 public override DataTable GetSchema (string collectionName, string [] restrictionValues)
481                 {
482                         if (State == ConnectionState.Closed)
483                                 throw ExceptionHelper.ConnectionClosed ();
484                         return GetSchema (collectionName, null);
485                 }
486
487                 [MonoTODO]
488                 public override void EnlistTransaction (Transaction transaction)
489                 {
490                         throw new NotImplementedException ();
491                 }
492 #endif
493
494                 [MonoTODO]
495                 public void EnlistDistributedTransaction (ITransaction transaction)
496                 {
497                         throw new NotImplementedException ();
498                 }
499
500                 internal string GetInfo (OdbcInfo info)
501                 {
502                         if (State == ConnectionState.Closed)
503                                 throw new InvalidOperationException ("The connection is closed.");
504
505                         OdbcReturn ret = OdbcReturn.Error;
506                         short max_length = 512;
507                         byte [] buffer = new byte [512];
508                         short actualLength = 0;
509
510                         ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
511                         if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
512                                 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
513                         return Encoding.Unicode.GetString (buffer, 0, actualLength);
514                 }
515
516                 string GetSafeInfo (OdbcInfo info)
517                 {
518                         if (State == ConnectionState.Closed)
519                                 return null;
520
521                         OdbcReturn ret = OdbcReturn.Error;
522                         short max_length = 512;
523                         byte [] buffer = new byte [512];
524                         short actualLength = 0;
525
526                         ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
527                         if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
528                                 return null;
529                         return Encoding.Unicode.GetString (buffer, 0, actualLength);
530                 }
531
532                 private void RaiseStateChange (ConnectionState from, ConnectionState to)
533                 {
534 #if ONLY_1_1
535                         if (StateChange != null)
536                                 StateChange (this, new StateChangeEventArgs (from, to));
537 #else
538                         base.OnStateChange (new StateChangeEventArgs (from, to));
539 #endif
540                 }
541
542                 private OdbcInfoMessageEventArgs CreateOdbcInfoMessageEvent (OdbcErrorCollection errors)
543                 {
544                         return new OdbcInfoMessageEventArgs (errors);
545                 }
546
547                 private void OnOdbcInfoMessage (OdbcInfoMessageEventArgs e)
548                 {
549                         if (InfoMessage != null)
550                                 InfoMessage (this, e);
551                 }
552
553                 internal OdbcException CreateOdbcException (OdbcHandleType HandleType, IntPtr Handle)
554                 {
555                         short buflen = 256;
556                         short txtlen = 0;
557                         int nativeerror = 0;
558                         OdbcReturn ret = OdbcReturn.Success;
559
560                         OdbcErrorCollection errors = new OdbcErrorCollection ();
561
562                         while (true) {
563                                 byte [] buf_MsgText = new byte [buflen * 2];
564                                 byte [] buf_SqlState = new byte [buflen * 2];
565
566                                 switch (HandleType) {
567                                 case OdbcHandleType.Dbc:
568                                         ret = libodbc.SQLError (IntPtr.Zero, Handle, IntPtr.Zero, buf_SqlState,
569                                                 ref nativeerror, buf_MsgText, buflen, ref txtlen);
570                                         break;
571                                 case OdbcHandleType.Stmt:
572                                         ret = libodbc.SQLError (IntPtr.Zero, IntPtr.Zero, Handle, buf_SqlState,
573                                                 ref nativeerror, buf_MsgText, buflen, ref txtlen);
574                                         break;
575                                 case OdbcHandleType.Env:
576                                         ret = libodbc.SQLError (Handle, IntPtr.Zero, IntPtr.Zero, buf_SqlState,
577                                                 ref nativeerror, buf_MsgText, buflen, ref txtlen);
578                                         break;
579                                 }
580
581                                 if (ret != OdbcReturn.Success)
582                                         break;
583
584                                 string state = RemoveTrailingNullChar (Encoding.Unicode.GetString (buf_SqlState));
585                                 string message = Encoding.Unicode.GetString (buf_MsgText, 0, txtlen * 2);
586
587                                 errors.Add (new OdbcError (message, state, nativeerror));
588                         }
589
590                         string source = SafeDriver;
591                         foreach (OdbcError error in errors)
592                                 error.SetSource (source);
593                         return new OdbcException (errors);
594                 }
595
596                 static string RemoveTrailingNullChar (string value)
597                 {
598                         return value.TrimEnd ('\0');
599                 }
600
601                 internal object Link (OdbcCommand cmd)
602                 {
603                         lock(this) {
604                                 if (linkedCommands == null)
605                                         linkedCommands = new ArrayList ();
606                                 linkedCommands.Add (new WeakReference (cmd));
607                                 return linkedCommands;
608                         }
609                 }
610
611                 internal object Unlink (OdbcCommand cmd)
612                 {
613                         lock(this) {
614                                 if (linkedCommands == null)
615                                         return null;
616
617                                 for (int i = 0; i < linkedCommands.Count; i++) {
618                                         WeakReference wr = (WeakReference) linkedCommands [i];
619                                         if (wr == null)
620                                                 continue;
621                                         OdbcCommand c = (OdbcCommand) wr.Target;
622                                         if (c == cmd) {
623                                                 linkedCommands [i] = null;
624                                                 break;
625                                         }
626                                 }
627                                 return linkedCommands;
628                         }
629                 }
630
631                 #endregion
632
633                 #region Events and Delegates
634
635 #if ONLY_1_1
636                 [OdbcDescription ("DbConnection_StateChange")]
637                 [OdbcCategory ("DataCategory_StateChange")]
638                 public event StateChangeEventHandler StateChange;
639 #endif // ONLY_1_1
640
641                 [OdbcDescription ("DbConnection_InfoMessage")]
642                 [OdbcCategory ("DataCategory_InfoMessage")]
643                 public event OdbcInfoMessageEventHandler InfoMessage;
644
645                 private void MessageHandler (OdbcException e)
646                 {
647                         OnOdbcInfoMessage (CreateOdbcInfoMessageEvent (e.Errors));
648                 }
649
650                 #endregion
651         }
652 }