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 using System.Transactions;
42 namespace System.Data.Odbc
44 [DefaultEvent ("InfoMessage")]
45 public sealed class OdbcConnection : DbConnection, ICloneable
49 string connectionString;
50 int connectionTimeout;
51 internal OdbcTransaction transaction;
52 IntPtr henv = IntPtr.Zero;
53 IntPtr hdbc = IntPtr.Zero;
55 ArrayList linkedCommands;
61 public OdbcConnection () : this (String.Empty)
65 public OdbcConnection (string connectionString)
67 connectionTimeout = 15;
68 ConnectionString = connectionString;
71 #endregion // Constructors
75 internal IntPtr hDbc {
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; }
87 [OdbcCategoryAttribute ("DataCategory_Data")]
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)]
95 string ConnectionString {
97 if (connectionString == null)
99 return connectionString;
101 set { connectionString = value; }
104 [OdbcDescriptionAttribute ("Current connection timeout value, not settable in the ConnectionString")]
106 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
109 int ConnectionTimeout {
111 return connectionTimeout;
115 throw new ArgumentException("Timout should not be less than zero.");
116 connectionTimeout = value;
120 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
121 [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
126 if (State == ConnectionState.Closed)
128 return GetInfo (OdbcInfo.DatabaseName);
132 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
133 [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
134 [BrowsableAttribute (false)]
137 ConnectionState State {
139 if (hdbc != IntPtr.Zero)
140 return ConnectionState.Open;
141 return ConnectionState.Closed;
145 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
146 [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
152 if (State == ConnectionState.Closed)
154 return GetInfo (OdbcInfo.DataSourceName);
159 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
160 [OdbcDescriptionAttribute ("Current ODBC Driver")]
161 public string Driver {
163 if (State == ConnectionState.Closed)
166 return GetInfo (OdbcInfo.DriverName);
170 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
171 [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
172 [BrowsableAttribute (false)]
175 string ServerVersion {
177 return GetInfo (OdbcInfo.DbmsVersion);
181 internal string SafeDriver {
183 string driver_name = GetSafeInfo (OdbcInfo.DriverName);
184 if (driver_name == null)
190 #endregion // Properties
196 OdbcTransaction BeginTransaction ()
198 return BeginTransaction (IsolationLevel.Unspecified);
202 protected override DbTransaction BeginDbTransaction (IsolationLevel isolationLevel)
204 return BeginTransaction (isolationLevel);
209 OdbcTransaction BeginTransaction (IsolationLevel isolevel)
211 if (State == ConnectionState.Closed)
212 throw ExceptionHelper.ConnectionClosed ();
214 if (transaction == null) {
215 transaction = new OdbcTransaction (this, isolevel);
218 throw new InvalidOperationException ();
226 OdbcReturn ret = OdbcReturn.Error;
227 if (State == ConnectionState.Open) {
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];
237 OdbcCommand c = (OdbcCommand) wr.Target;
241 linkedCommands = null;
245 ret = libodbc.SQLDisconnect (hdbc);
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
253 if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
254 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
258 RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
264 OdbcCommand CreateCommand ()
266 return new OdbcCommand (string.Empty, this, transaction);
271 void ChangeDatabase (string value)
273 IntPtr ptr = IntPtr.Zero;
274 OdbcReturn ret = OdbcReturn.Error;
277 ptr = Marshal.StringToHGlobalUni (value);
278 ret = libodbc.SQLSetConnectAttr (hdbc, OdbcConnectionAttribute.CurrentCatalog, ptr, value.Length * 2);
280 if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
281 throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
283 if (ptr != IntPtr.Zero)
284 Marshal.FreeCoTaskMem (ptr);
288 protected override void Dispose (bool disposing)
290 if (!this.disposed) {
292 // release the native unmananged resources
294 this.disposed = true;
296 // call Dispose on the base class
297 base.Dispose (disposing);
303 object ICloneable.Clone ()
305 throw new NotImplementedException ();
309 protected override DbCommand CreateDbCommand ()
311 return CreateCommand ();
318 if (State == ConnectionState.Open)
319 throw new InvalidOperationException ();
321 OdbcReturn ret = OdbcReturn.Error;
322 OdbcException e = null;
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);
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);
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);
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)
350 string [] parts = item.Split (new char[1] {'='});
351 switch (parts [0].Trim ().ToLower ()) {
353 _dsn = parts [1].Trim ();
356 _uid = parts [1].Trim ();
359 _pwd = parts [1].Trim ();
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);
367 // DSN-less Connection
368 string OutConnectionString = new String (' ',1024);
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);
376 RaiseStateChange (ConnectionState.Closed, ConnectionState.Open);
378 // free handles if any.
386 public static void ReleaseObjectPool ()
388 throw new NotImplementedException ();
391 private void FreeHandles ()
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);
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);
409 public override DataTable GetSchema ()
411 if (State == ConnectionState.Closed)
412 throw ExceptionHelper.ConnectionClosed ();
413 return MetaDataCollections.Instance;
416 public override DataTable GetSchema (string collectionName)
418 return GetSchema (collectionName, null);
421 public override DataTable GetSchema (string collectionName, string [] restrictionValues)
423 if (State == ConnectionState.Closed)
424 throw ExceptionHelper.ConnectionClosed ();
425 return GetSchema (collectionName, null);
429 public override void EnlistTransaction (Transaction transaction)
431 throw new NotImplementedException ();
435 public void EnlistDistributedTransaction (ITransaction transaction)
437 throw new NotImplementedException ();
440 internal string GetInfo (OdbcInfo info)
442 if (State == ConnectionState.Closed)
443 throw new InvalidOperationException ("The connection is closed.");
445 OdbcReturn ret = OdbcReturn.Error;
446 short max_length = 512;
447 byte [] buffer = new byte [512];
448 short actualLength = 0;
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);
456 string GetSafeInfo (OdbcInfo info)
458 if (State == ConnectionState.Closed)
461 OdbcReturn ret = OdbcReturn.Error;
462 short max_length = 512;
463 byte [] buffer = new byte [512];
464 short actualLength = 0;
466 ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
467 if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
469 return Encoding.Unicode.GetString (buffer, 0, actualLength);
472 private void RaiseStateChange (ConnectionState from, ConnectionState to)
474 base.OnStateChange (new StateChangeEventArgs (from, to));
477 private OdbcInfoMessageEventArgs CreateOdbcInfoMessageEvent (OdbcErrorCollection errors)
479 return new OdbcInfoMessageEventArgs (errors);
482 private void OnOdbcInfoMessage (OdbcInfoMessageEventArgs e)
484 if (InfoMessage != null)
485 InfoMessage (this, e);
488 internal OdbcException CreateOdbcException (OdbcHandleType HandleType, IntPtr Handle)
493 OdbcReturn ret = OdbcReturn.Success;
495 OdbcErrorCollection errors = new OdbcErrorCollection ();
498 byte [] buf_MsgText = new byte [buflen * 2];
499 byte [] buf_SqlState = new byte [buflen * 2];
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);
506 case OdbcHandleType.Stmt:
507 ret = libodbc.SQLError (IntPtr.Zero, IntPtr.Zero, Handle, buf_SqlState,
508 ref nativeerror, buf_MsgText, buflen, ref txtlen);
510 case OdbcHandleType.Env:
511 ret = libodbc.SQLError (Handle, IntPtr.Zero, IntPtr.Zero, buf_SqlState,
512 ref nativeerror, buf_MsgText, buflen, ref txtlen);
516 if (ret != OdbcReturn.Success)
519 string state = RemoveTrailingNullChar (Encoding.Unicode.GetString (buf_SqlState));
520 string message = Encoding.Unicode.GetString (buf_MsgText, 0, txtlen * 2);
522 errors.Add (new OdbcError (SafeDriver, message, state, nativeerror));
525 string source = SafeDriver;
526 foreach (OdbcError error in errors)
527 error.SetSource (source);
528 return new OdbcException (errors);
531 static string RemoveTrailingNullChar (string value)
533 return value.TrimEnd ('\0');
536 internal object Link (OdbcCommand cmd)
539 if (linkedCommands == null)
540 linkedCommands = new ArrayList ();
541 linkedCommands.Add (new WeakReference (cmd));
542 return linkedCommands;
546 internal object Unlink (OdbcCommand cmd)
549 if (linkedCommands == null)
552 for (int i = 0; i < linkedCommands.Count; i++) {
553 WeakReference wr = (WeakReference) linkedCommands [i];
556 OdbcCommand c = (OdbcCommand) wr.Target;
558 linkedCommands [i] = null;
562 return linkedCommands;
568 #region Events and Delegates
571 [OdbcDescription ("DbConnection_InfoMessage")]
572 [OdbcCategory ("DataCategory_InfoMessage")]
573 public event OdbcInfoMessageEventHandler InfoMessage;
575 private void MessageHandler (OdbcException e)
577 OnOdbcInfoMessage (CreateOdbcInfoMessageEvent (e.Errors));