2 // System.Data.Odbc.OdbcConnection
5 // Brian Ritchie (brianlritchie@hotmail.com)
7 // Copyright (C) Brian Ritchie, 2002
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
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.
33 using System.Collections;
34 using System.ComponentModel;
36 using System.Data.Common;
37 using System.EnterpriseServices;
38 using System.Runtime.InteropServices;
40 #if NET_2_0 && !TARGET_JVM
41 using System.Transactions;
44 namespace System.Data.Odbc
46 [DefaultEvent ("InfoMessage")]
48 public sealed class OdbcConnection : DbConnection, ICloneable
50 public sealed class OdbcConnection : Component, ICloneable, IDbConnection
55 string connectionString;
56 int connectionTimeout;
57 internal OdbcTransaction transaction;
58 IntPtr henv = IntPtr.Zero;
59 IntPtr hdbc = IntPtr.Zero;
61 ArrayList linkedCommands;
67 public OdbcConnection () : this (String.Empty)
71 public OdbcConnection (string connectionString)
73 connectionTimeout = 15;
74 ConnectionString = connectionString;
77 #endregion // Constructors
81 internal IntPtr hDbc {
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; }
93 [OdbcCategoryAttribute ("DataCategory_Data")]
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)]
103 string ConnectionString {
105 if (connectionString == null)
107 return connectionString;
109 set { connectionString = value; }
112 [OdbcDescriptionAttribute ("Current connection timeout value, not settable in the ConnectionString")]
115 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
121 int ConnectionTimeout {
123 return connectionTimeout;
127 throw new ArgumentException("Timout should not be less than zero.");
128 connectionTimeout = value;
132 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
133 [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
140 if (State == ConnectionState.Closed)
142 return GetInfo (OdbcInfo.DatabaseName);
146 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
147 [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
148 [BrowsableAttribute (false)]
153 ConnectionState State {
155 if (hdbc != IntPtr.Zero)
156 return ConnectionState.Open;
157 return ConnectionState.Closed;
161 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
162 [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
172 if (State == ConnectionState.Closed)
174 return GetInfo (OdbcInfo.DataSourceName);
181 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
182 [OdbcDescriptionAttribute ("Current ODBC Driver")]
183 public string Driver {
185 if (State == ConnectionState.Closed)
188 return GetInfo (OdbcInfo.DriverName);
192 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
193 [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
194 [BrowsableAttribute (false)]
199 string ServerVersion {
201 return GetInfo (OdbcInfo.DbmsVersion);
205 internal string SafeDriver {
207 string driver_name = GetSafeInfo (OdbcInfo.DriverName);
208 if (driver_name == null)
214 #endregion // Properties
222 OdbcTransaction BeginTransaction ()
224 return BeginTransaction (IsolationLevel.Unspecified);
228 IDbTransaction IDbConnection.BeginTransaction ()
230 return (IDbTransaction) BeginTransaction ();
235 protected override DbTransaction BeginDbTransaction (IsolationLevel isolationLevel)
237 return BeginTransaction (isolationLevel);
245 OdbcTransaction BeginTransaction (IsolationLevel isolevel)
247 if (State == ConnectionState.Closed)
248 throw ExceptionHelper.ConnectionClosed ();
250 if (transaction == null) {
251 transaction = new OdbcTransaction (this, isolevel);
254 throw new InvalidOperationException ();
258 IDbTransaction IDbConnection.BeginTransaction (IsolationLevel isolevel)
260 return (IDbTransaction) BeginTransaction (isolevel);
270 OdbcReturn ret = OdbcReturn.Error;
271 if (State == ConnectionState.Open) {
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];
281 OdbcCommand c = (OdbcCommand) wr.Target;
285 linkedCommands = null;
289 ret = libodbc.SQLDisconnect (hdbc);
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
297 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
298 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
302 RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
310 OdbcCommand CreateCommand ()
312 return new OdbcCommand (string.Empty, this, transaction);
319 void ChangeDatabase (string value)
321 IntPtr ptr = IntPtr.Zero;
322 OdbcReturn ret = OdbcReturn.Error;
325 ptr = Marshal.StringToHGlobalUni (value);
326 ret = libodbc.SQLSetConnectAttr (hdbc, OdbcConnectionAttribute.CurrentCatalog, ptr, value.Length * 2);
328 if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
329 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
331 if (ptr != IntPtr.Zero)
332 Marshal.FreeCoTaskMem (ptr);
336 protected override void Dispose (bool disposing)
338 if (!this.disposed) {
340 // release the native unmananged resources
342 this.disposed = true;
344 // call Dispose on the base class
345 base.Dispose (disposing);
351 object ICloneable.Clone ()
353 throw new NotImplementedException ();
357 IDbCommand IDbConnection.CreateCommand ()
359 return (IDbCommand) CreateCommand ();
364 protected override DbCommand CreateDbCommand ()
366 return CreateCommand ();
376 if (State == ConnectionState.Open)
377 throw new InvalidOperationException ();
379 OdbcReturn ret = OdbcReturn.Error;
380 OdbcException e = null;
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);
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);
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);
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)
408 string [] parts = item.Split (new char[1] {'='});
409 switch (parts [0].Trim ().ToLower ()) {
411 _dsn = parts [1].Trim ();
414 _uid = parts [1].Trim ();
417 _pwd = parts [1].Trim ();
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);
425 // DSN-less Connection
426 string OutConnectionString = new String (' ',1024);
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);
434 RaiseStateChange (ConnectionState.Closed, ConnectionState.Open);
436 // free handles if any.
444 public static void ReleaseObjectPool ()
446 throw new NotImplementedException ();
449 private void FreeHandles ()
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);
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);
468 public override DataTable GetSchema ()
470 if (State == ConnectionState.Closed)
471 throw ExceptionHelper.ConnectionClosed ();
472 return MetaDataCollections.Instance;
475 public override DataTable GetSchema (string collectionName)
477 return GetSchema (collectionName, null);
480 public override DataTable GetSchema (string collectionName, string [] restrictionValues)
482 if (State == ConnectionState.Closed)
483 throw ExceptionHelper.ConnectionClosed ();
484 return GetSchema (collectionName, null);
488 public override void EnlistTransaction (Transaction transaction)
490 throw new NotImplementedException ();
495 public void EnlistDistributedTransaction (ITransaction transaction)
497 throw new NotImplementedException ();
500 internal string GetInfo (OdbcInfo info)
502 if (State == ConnectionState.Closed)
503 throw new InvalidOperationException ("The connection is closed.");
505 OdbcReturn ret = OdbcReturn.Error;
506 short max_length = 512;
507 byte [] buffer = new byte [512];
508 short actualLength = 0;
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);
516 string GetSafeInfo (OdbcInfo info)
518 if (State == ConnectionState.Closed)
521 OdbcReturn ret = OdbcReturn.Error;
522 short max_length = 512;
523 byte [] buffer = new byte [512];
524 short actualLength = 0;
526 ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
527 if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
529 return Encoding.Unicode.GetString (buffer, 0, actualLength);
532 private void RaiseStateChange (ConnectionState from, ConnectionState to)
535 if (StateChange != null)
536 StateChange (this, new StateChangeEventArgs (from, to));
538 base.OnStateChange (new StateChangeEventArgs (from, to));
542 private OdbcInfoMessageEventArgs CreateOdbcInfoMessageEvent (OdbcErrorCollection errors)
544 return new OdbcInfoMessageEventArgs (errors);
547 private void OnOdbcInfoMessage (OdbcInfoMessageEventArgs e)
549 if (InfoMessage != null)
550 InfoMessage (this, e);
553 internal OdbcException CreateOdbcException (OdbcHandleType HandleType, IntPtr Handle)
558 OdbcReturn ret = OdbcReturn.Success;
560 OdbcErrorCollection errors = new OdbcErrorCollection ();
563 byte [] buf_MsgText = new byte [buflen * 2];
564 byte [] buf_SqlState = new byte [buflen * 2];
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);
571 case OdbcHandleType.Stmt:
572 ret = libodbc.SQLError (IntPtr.Zero, IntPtr.Zero, Handle, buf_SqlState,
573 ref nativeerror, buf_MsgText, buflen, ref txtlen);
575 case OdbcHandleType.Env:
576 ret = libodbc.SQLError (Handle, IntPtr.Zero, IntPtr.Zero, buf_SqlState,
577 ref nativeerror, buf_MsgText, buflen, ref txtlen);
581 if (ret != OdbcReturn.Success)
584 string state = RemoveTrailingNullChar (Encoding.Unicode.GetString (buf_SqlState));
585 string message = Encoding.Unicode.GetString (buf_MsgText, 0, txtlen * 2);
587 errors.Add (new OdbcError (message, state, nativeerror));
590 string source = SafeDriver;
591 foreach (OdbcError error in errors)
592 error.SetSource (source);
593 return new OdbcException (errors);
596 static string RemoveTrailingNullChar (string value)
598 return value.TrimEnd ('\0');
601 internal object Link (OdbcCommand cmd)
604 if (linkedCommands == null)
605 linkedCommands = new ArrayList ();
606 linkedCommands.Add (new WeakReference (cmd));
607 return linkedCommands;
611 internal object Unlink (OdbcCommand cmd)
614 if (linkedCommands == null)
617 for (int i = 0; i < linkedCommands.Count; i++) {
618 WeakReference wr = (WeakReference) linkedCommands [i];
621 OdbcCommand c = (OdbcCommand) wr.Target;
623 linkedCommands [i] = null;
627 return linkedCommands;
633 #region Events and Delegates
636 [OdbcDescription ("DbConnection_StateChange")]
637 [OdbcCategory ("DataCategory_StateChange")]
638 public event StateChangeEventHandler StateChange;
641 [OdbcDescription ("DbConnection_InfoMessage")]
642 [OdbcCategory ("DataCategory_InfoMessage")]
643 public event OdbcInfoMessageEventHandler InfoMessage;
645 private void MessageHandler (OdbcException e)
647 OnOdbcInfoMessage (CreateOdbcInfoMessageEvent (e.Errors));