File: Connection.cs

package info (click to toggle)
mysql-connector-net 6.4.3-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 6,160 kB
  • ctags: 8,552
  • sloc: cs: 63,689; xml: 7,505; sql: 345; makefile: 50; ansic: 40
file content (885 lines) | stat: -rw-r--r-- 30,992 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most 
// MySQL Connectors. There are special exceptions to the terms and 
// conditions of the GPLv2 as it is applied to this software, see the 
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published 
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
// for more details.
//
// You should have received a copy of the GNU General Public License along 
// with this program; if not, write to the Free Software Foundation, Inc., 
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA

using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
#if !CF
using System.Drawing;
using System.Drawing.Design;
using System.Transactions;
#endif
using System.Text;
using IsolationLevel=System.Data.IsolationLevel;
using MySql.Data.Common;
using System.Diagnostics;
using MySql.Data.MySqlClient.Properties;

namespace MySql.Data.MySqlClient
{
    /// <include file='docs/MySqlConnection.xml' path='docs/ClassSummary/*'/>
#if !CF
    [ToolboxBitmap(typeof (MySqlConnection), "MySqlClient.resources.connection.bmp")]
    [DesignerCategory("Code")]
    [ToolboxItem(true)]
#endif
    public sealed class MySqlConnection : DbConnection, ICloneable
    {
        internal ConnectionState connectionState;
        internal Driver driver;
        private MySqlConnectionStringBuilder settings;
        private bool hasBeenOpen;
        private SchemaProvider schemaProvider;
        private ProcedureCache procedureCache;
        private bool isInUse;
#if !CF
        private PerformanceMonitor perfMonitor;
#endif
        private bool isKillQueryConnection;
        private string database;
        private int commandTimeout;

        /// <include file='docs/MySqlConnection.xml' path='docs/InfoMessage/*'/>
        public event MySqlInfoMessageEventHandler InfoMessage;

        private static Cache<string, MySqlConnectionStringBuilder> connectionStringCache =
            new Cache<string, MySqlConnectionStringBuilder>(0, 25);

        /// <include file='docs/MySqlConnection.xml' path='docs/DefaultCtor/*'/>
        public MySqlConnection()
        {
            //TODO: add event data to StateChange docs
            settings = new MySqlConnectionStringBuilder();
            database = String.Empty;
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/Ctor1/*'/>
        public MySqlConnection(string connectionString)
            : this()
        {
            ConnectionString = connectionString;
        }

        #region Interal Methods & Properties

#if !CF
        internal PerformanceMonitor PerfMonitor
        {
            get { return perfMonitor; }
        }

#endif

        internal ProcedureCache ProcedureCache
        {
            get { return procedureCache; }
        }

        internal MySqlConnectionStringBuilder Settings
        {
            get { return settings; }
        }

        internal MySqlDataReader Reader
        {
            get 
            { 
                if (driver == null)
                    return null;
                return driver.reader;
            }
            set 
            { 
                driver.reader = value;
                isInUse = driver.reader != null;
            }
        }

        internal void OnInfoMessage(MySqlInfoMessageEventArgs args)
        {
            if (InfoMessage != null)
            {
                InfoMessage(this, args);
            }
        }

        internal bool SoftClosed
        {
            get 
            {
#if !CF
                return (State == ConnectionState.Closed) && 
                    driver != null && 
                    driver.CurrentTransaction != null;
#else
                return false;            
#endif
            }
        }

        internal bool IsInUse
        {
            get{ return isInUse; }
            set{ isInUse = value; }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Returns the id of the server thread this connection is executing on
        /// </summary>
#if !CF
        [Browsable(false)]
#endif
            public int ServerThread
        {
            get { return driver.ThreadID; }
        }

        /// <summary>
        /// Gets the name of the MySQL server to which to connect.
        /// </summary>
#if !CF
        [Browsable(true)]
#endif
            public override string DataSource
        {
            get { return settings.Server; }
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/ConnectionTimeout/*'/>
#if !CF
        [Browsable(true)]
#endif
            public override int ConnectionTimeout
        {
            get { return (int) settings.ConnectionTimeout; }
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/Database/*'/>
#if !CF
        [Browsable(true)]
#endif
            public override string Database
        {
            get { return database; }
        }

        /// <summary>
        /// Indicates if this connection should use compression when communicating with the server.
        /// </summary>
#if !CF
        [Browsable(false)]
#endif
            public bool UseCompression
        {
            get { return settings.UseCompression; }
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/State/*'/>
#if !CF
        [Browsable(false)]
#endif
            public override ConnectionState State
        {
            get { return connectionState; }
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/ServerVersion/*'/>
#if !CF
        [Browsable(false)]
#endif
            public override string ServerVersion
        {
            get { return driver.Version.ToString(); }
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/ConnectionString/*'/>
#if !CF
        [Editor("MySql.Data.MySqlClient.Design.ConnectionStringTypeEditor,MySqlClient.Design", typeof (UITypeEditor))]
        [Browsable(true)]
        [Category("Data")]
        [Description(
            "Information used to connect to a DataSource, such as 'Server=xxx;UserId=yyy;Password=zzz;Database=dbdb'.")]
#endif
            public override string ConnectionString
        {
            get
            {
                // Always return exactly what the user set.
                // Security-sensitive information may be removed.
                return settings.GetConnectionString(!hasBeenOpen || settings.PersistSecurityInfo);
            }
            set
            {
                if (State != ConnectionState.Closed)
                    throw new MySqlException(
                        "Not allowed to change the 'ConnectionString' property while the connection (state=" + State +
                        ").");

                MySqlConnectionStringBuilder newSettings;
                lock (connectionStringCache)
                {
                    if (value == null)
                        newSettings = new MySqlConnectionStringBuilder();
                    else
                    {
                        newSettings = (MySqlConnectionStringBuilder)connectionStringCache[value];
                        if (null == newSettings)
                        {
                            newSettings = new MySqlConnectionStringBuilder(value);
                            connectionStringCache.Add(value, newSettings);
                        }
                    }
                }

                settings = newSettings;

                if (settings.Database != null && settings.Database.Length > 0)
                    this.database = settings.Database;

                if (driver != null)
                    driver.Settings = newSettings;
            }
        }

#if !CF && !__MonoCS__

        protected override DbProviderFactory DbProviderFactory
        {
            get
            {
                return MySqlClientFactory.Instance;
            }
        }
		
#endif

        #endregion

        #region Transactions

#if !MONO && !CF
        /// <summary>
        /// Enlists in the specified transaction. 
        /// </summary>
        /// <param name="transaction">
        /// A reference to an existing <see cref="System.Transactions.Transaction"/> in which to enlist.
        /// </param>
        public override void EnlistTransaction(Transaction transaction)
        {
            // enlisting in the null transaction is a noop
            if (transaction == null)
                return;

            // guard against trying to enlist in more than one transaction
            if (driver.CurrentTransaction != null)
            {
                if (driver.CurrentTransaction.BaseTransaction == transaction)
                    return;

                throw new MySqlException("Already enlisted");
            }

            // now see if we need to swap out drivers.  We would need to do this since
            // we have to make sure all ops for a given transaction are done on the
            // same physical connection.
            Driver existingDriver = DriverTransactionManager.GetDriverInTransaction(transaction);
            if (existingDriver != null)
            {
                // we can't allow more than one driver to contribute to the same connection
                if (existingDriver.IsInActiveUse)
                    throw new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported);

                // there is an existing driver and it's not being currently used.
                // now we need to see if it is using the same connection string
                string text1 = existingDriver.Settings.ConnectionString;
                string text2 = Settings.ConnectionString;
                if (String.Compare(text1, text2, true) != 0)
                    throw new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported);

                // close existing driver
                // set this new driver as our existing driver
                CloseFully();
                driver = existingDriver;
            }

            if (driver.CurrentTransaction == null)
            {
                MySqlPromotableTransaction t = new MySqlPromotableTransaction(this, transaction);
                if (!transaction.EnlistPromotableSinglePhase(t))
                    throw new NotSupportedException(Resources.DistributedTxnNotSupported);

                driver.CurrentTransaction = t;
                DriverTransactionManager.SetDriverInTransaction(driver);
                driver.IsInActiveUse = true;
            }
        }
#endif

        /// <include file='docs/MySqlConnection.xml' path='docs/BeginTransaction/*'/>
        public new MySqlTransaction BeginTransaction()
        {
            return BeginTransaction(IsolationLevel.RepeatableRead);
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/BeginTransaction1/*'/>
        public new MySqlTransaction BeginTransaction(IsolationLevel iso)
        {
            //TODO: check note in help
            if (State != ConnectionState.Open)
                throw new InvalidOperationException(Resources.ConnectionNotOpen);

            // First check to see if we are in a current transaction
            if (driver.HasStatus(ServerStatusFlags.InTransaction))
                throw new InvalidOperationException(Resources.NoNestedTransactions);

            MySqlTransaction t = new MySqlTransaction(this, iso);

            MySqlCommand cmd = new MySqlCommand("", this);

            cmd.CommandText = "SET SESSION TRANSACTION ISOLATION LEVEL ";
            switch (iso)
            {
                case IsolationLevel.ReadCommitted:
                    cmd.CommandText += "READ COMMITTED";
                    break;
                case IsolationLevel.ReadUncommitted:
                    cmd.CommandText += "READ UNCOMMITTED";
                    break;
                case IsolationLevel.RepeatableRead:
                    cmd.CommandText += "REPEATABLE READ";
                    break;
                case IsolationLevel.Serializable:
                    cmd.CommandText += "SERIALIZABLE";
                    break;
                case IsolationLevel.Chaos:
                    throw new NotSupportedException(Resources.ChaosNotSupported);
                case IsolationLevel.Snapshot:
                    throw new NotSupportedException(Resources.SnapshotNotSupported);
            }

            cmd.ExecuteNonQuery();

            cmd.CommandText = "BEGIN";
            cmd.ExecuteNonQuery();

            return t;
        }

        #endregion

        /// <include file='docs/MySqlConnection.xml' path='docs/ChangeDatabase/*'/>
        public override void ChangeDatabase(string databaseName)
        {
            if (databaseName == null || databaseName.Trim().Length == 0)
                throw new ArgumentException(Resources.ParameterIsInvalid, "databaseName");

            if (State != ConnectionState.Open)
                throw new InvalidOperationException(Resources.ConnectionNotOpen);

            // This lock  prevents promotable transaction rollback to run
            // in parallel
            lock (driver)
            {
#if !CF
                if (Transaction.Current != null &&
                    Transaction.Current.TransactionInformation.Status == TransactionStatus.Aborted)
                {
                    throw new TransactionAbortedException();
                }
#endif
                // We use default command timeout for SetDatabase
                using (new CommandTimer(this, (int)Settings.DefaultCommandTimeout))
                {
                    driver.SetDatabase(databaseName);
                }
            }
            this.database = databaseName;
        }

        internal void SetState(ConnectionState newConnectionState, bool broadcast)
        {
            if (newConnectionState == connectionState && !broadcast)
                return;
            ConnectionState oldConnectionState = connectionState;
            connectionState = newConnectionState;
			if (broadcast)
				OnStateChange(new StateChangeEventArgs(oldConnectionState, connectionState));
        }

        /// <summary>
        /// Ping
        /// </summary>
        /// <returns></returns>
        public bool Ping()
        {
            if(Reader != null)
                throw new MySqlException(Resources.DataReaderOpen);
            if (driver != null && driver.Ping())
                return true;
            driver = null;
            SetState(ConnectionState.Closed, true);
            return false;
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/Open/*'/>
        public override void Open()
        {
            if (State == ConnectionState.Open)
                throw new InvalidOperationException(Resources.ConnectionAlreadyOpen);

            SetState(ConnectionState.Connecting, true);

#if !CF
                // if we are auto enlisting in a current transaction, then we will be
                // treating the connection as pooled
                if (settings.AutoEnlist && Transaction.Current != null)
                {
                    driver = DriverTransactionManager.GetDriverInTransaction(Transaction.Current);
                    if (driver != null &&
                        (driver.IsInActiveUse ||
                        !driver.Settings.EquivalentTo(this.Settings)))
                        throw new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported);
                }
#endif

            try
            {
                if (settings.Pooling)
                {
                    MySqlPool pool = MySqlPoolManager.GetPool(settings);
                    if (driver == null || !driver.IsOpen)
                        driver = pool.GetConnection();
                    procedureCache = pool.ProcedureCache;
                    
                }
                else
                {
                    if (driver == null || !driver.IsOpen)
                        driver = Driver.Create(settings);
                    procedureCache = new ProcedureCache((int) settings.ProcedureCacheSize);
                }
            }
            catch (Exception)
            {
                SetState(ConnectionState.Closed, true);
                throw;
            }

            // if the user is using old syntax, let them know
            if (driver.Settings.UseOldSyntax)
                MySqlTrace.LogWarning(ServerThread,
                    "You are using old syntax that will be removed in future versions");

            SetState(ConnectionState.Open, false);
            driver.Configure(this);
            if (settings.Database != null && settings.Database != String.Empty)
                ChangeDatabase(settings.Database);

            // setup our schema provider
            schemaProvider = new ISSchemaProvider(this);
#if !CF
            perfMonitor = new PerformanceMonitor(this);
#endif

            // if we are opening up inside a current transaction, then autoenlist
            // TODO: control this with a connection string option
#if !MONO && !CF
            if (Transaction.Current != null && settings.AutoEnlist)
                EnlistTransaction(Transaction.Current);
#endif

            hasBeenOpen = true;
			SetState(ConnectionState.Open, true);
		}

        /// <include file='docs/MySqlConnection.xml' path='docs/CreateCommand/*'/>
        public new MySqlCommand CreateCommand()
        {
            // Return a new instance of a command object.
            MySqlCommand c = new MySqlCommand();
            c.Connection = this;
            return c;
        }

        #region ICloneable

        /// <summary>
        /// Creates a new MySqlConnection object with the exact same ConnectionString value
        /// </summary>
        /// <returns>A cloned MySqlConnection object</returns>
        public MySqlConnection Clone()
        {
            MySqlConnection clone = new MySqlConnection();
            string connectionString = settings.ConnectionString;
            if (connectionString != null)
                clone.ConnectionString = connectionString;
            return clone;
        }

        object ICloneable.Clone()
        {
            return this.Clone();
        }

        #endregion

        #region IDisposeable

        protected override void Dispose(bool disposing)
        {
            if (State == ConnectionState.Open)
                Close();
            base.Dispose(disposing);
        }

        #endregion

        protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
        {
            if (isolationLevel == IsolationLevel.Unspecified)
                return BeginTransaction();
            return BeginTransaction(isolationLevel);
        }

        protected override DbCommand CreateDbCommand()
        {
            return CreateCommand();
        }

        internal void Abort()
        {
            try
            {
                driver.Close();
            }
            catch (Exception ex)
            {
                MySqlTrace.LogWarning(ServerThread, String.Concat("Error occurred aborting the connection. Exception was: ", ex.Message));
            }
            finally
            {
                this.isInUse = false;
            }
            SetState(ConnectionState.Closed, true);
        }

        internal void CloseFully()
        {
            if (settings.Pooling && driver.IsOpen)
            {
                // if we are in a transaction, roll it back
                if (driver.HasStatus(ServerStatusFlags.InTransaction))
                {
                    MySqlTransaction t = new MySqlTransaction(this, IsolationLevel.Unspecified);
                    t.Rollback();
                }

                MySqlPoolManager.ReleaseConnection(driver);
            }
            else
                driver.Close();
            driver = null;
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/Close/*'/>
        public override void Close()
        {
            if (State == ConnectionState.Closed) return;

            if (Reader != null)
                Reader.Close();

			// if the reader was opened with CloseConnection then driver
			// will be null on the second time through
			if (driver != null)
			{
#if !CF
				if (driver.CurrentTransaction == null)
#endif	
			        CloseFully();
#if !CF
				else
					driver.IsInActiveUse = false;
#endif
			}

            SetState(ConnectionState.Closed, true);
        }

		internal string CurrentDatabase()
		{
			if (Database != null && Database.Length > 0)
				return Database;
			MySqlCommand cmd = new MySqlCommand("SELECT database()", this);
			return cmd.ExecuteScalar().ToString();
		}



        internal void HandleTimeoutOrThreadAbort(Exception ex)
        {
            bool isFatal = false;

            if (isKillQueryConnection)
            {
                // Special connection started to cancel a query.
                // Abort will prevent recursive connection spawning
                Abort();
                if (ex is TimeoutException)
                {
                    throw new MySqlException(Resources.Timeout, true, ex);
                }
                else
                {
                    return;
                }
            }

            try
            {

                // Do a fast cancel.The reason behind small values for connection
                // and command timeout is that we do not want user to wait longer
                // after command has already expired.
                // Microsoft's SqlClient seems to be using 5 seconds timeouts 
                // here as well.
                // Read the  error packet with "interrupted" message.
                CancelQuery(5);
                driver.ResetTimeout(5000);
                if (Reader != null)
                {
                    Reader.Close();
                    Reader = null;
                }
            }
            catch (Exception ex2)
            {
                MySqlTrace.LogWarning(ServerThread, "Could not kill query, " +
                    " aborting connection. Exception was " + ex2.Message);
                Abort();
                isFatal = true;
            }
            if (ex is TimeoutException)
            {
                throw new MySqlException(Resources.Timeout, isFatal, ex);
            }
        }

        public void CancelQuery(int timeout)
        {
            MySqlConnectionStringBuilder cb = new MySqlConnectionStringBuilder(
                Settings.ConnectionString);
            cb.Pooling = false;
            cb.AutoEnlist = false;
            cb.ConnectionTimeout = (uint) timeout;
          
            using(MySqlConnection c = new MySqlConnection(cb.ConnectionString))
            {
                c.isKillQueryConnection = true;
                c.Open();
                string commandText = "KILL QUERY " + ServerThread;
                MySqlCommand cmd = new MySqlCommand(commandText, c);
                cmd.CommandTimeout = timeout;
                cmd.ExecuteNonQuery();
            }
        }

#region Routines for timeout support.

        // Problem description:
        // Sometimes, ExecuteReader is called recursively. This is the case if
        // command behaviors are used and we issue "set sql_select_limit" 
        // before and after command. This is also the case with prepared 
        // statements , where we set session variables. In these situations, we 
        // have to prevent  recursive ExecuteReader calls from overwriting 
        // timeouts set by the top level command.
        
        // To solve the problem, SetCommandTimeout() and ClearCommandTimeout() are 
        // introduced . Query timeout here is  "sticky", that is once set with 
        // SetCommandTimeout, it only be overwritten after ClearCommandTimeout 
        // (SetCommandTimeout would return false if it timeout has not been 
        // cleared).

        // The proposed usage pattern of there routines is following: 
        // When timed operations starts, issue SetCommandTimeout(). When it 
        // finishes, issue ClearCommandTimeout(), but _only_ if call to 
        // SetCommandTimeout() was successful.

       
        /// <summary>
        /// Sets query timeout. If timeout has been set prior and not
        /// yet cleared ClearCommandTimeout(), it has no effect.
        /// </summary>
        /// <param name="value">timeout in seconds</param>
        /// <returns>true if </returns>
        internal bool SetCommandTimeout(int value)
        {
            if (!hasBeenOpen)
                // Connection timeout is handled by driver
                return false;

            if (commandTimeout != 0)
                // someone is trying to set a timeout while command is already
                // running. It could be for example recursive call to ExecuteReader
                // Ignore the request, as only top-level (non-recursive commands)
                // can set timeouts.
                return false;

            if (driver == null)
                return false;

            commandTimeout = value;
            driver.ResetTimeout(commandTimeout * 1000);
            return true;
        }

        /// <summary>
        /// Clears query timeout, allowing next SetCommandTimeout() to succeed.
        /// </summary>
        internal void ClearCommandTimeout()
        {
            if (!hasBeenOpen)
                return;
            commandTimeout = 0;
            if (driver != null)
            {
                driver.ResetTimeout(0);
            }
        }
#endregion


        #region GetSchema Support

        /// <summary>
        /// Returns schema information for the data source of this <see cref="DbConnection"/>. 
        /// </summary>
        /// <returns>A <see cref="DataTable"/> that contains schema information. </returns>
        public override DataTable GetSchema()
        {
            return GetSchema(null);
        }

        /// <summary>
        /// Returns schema information for the data source of this 
        /// <see cref="DbConnection"/> using the specified string for the schema name. 
        /// </summary>
        /// <param name="collectionName">Specifies the name of the schema to return. </param>
        /// <returns>A <see cref="DataTable"/> that contains schema information. </returns>
        public override DataTable GetSchema(string collectionName)
        {
            if (collectionName == null)
                collectionName = SchemaProvider.MetaCollection;

            return GetSchema(collectionName, null);
        }

        /// <summary>
        /// Returns schema information for the data source of this <see cref="DbConnection"/>
        /// using the specified string for the schema name and the specified string array 
        /// for the restriction values. 
        /// </summary>
        /// <param name="collectionName">Specifies the name of the schema to return.</param>
        /// <param name="restrictionValues">Specifies a set of restriction values for the requested schema.</param>
        /// <returns>A <see cref="DataTable"/> that contains schema information.</returns>
        public override DataTable GetSchema(string collectionName, string[] restrictionValues)
        {
            if (collectionName == null)
                collectionName = SchemaProvider.MetaCollection;

            string[] restrictions = schemaProvider.CleanRestrictions(restrictionValues);
            DataTable dt = schemaProvider.GetSchema(collectionName, restrictions);
            return dt;
        }

        #endregion

        #region Pool Routines

        /// <include file='docs/MySqlConnection.xml' path='docs/ClearPool/*'/>
        public static void ClearPool(MySqlConnection connection)
        {
            MySqlPoolManager.ClearPool(connection.Settings);
        }

        /// <include file='docs/MySqlConnection.xml' path='docs/ClearAllPools/*'/>
        public static void ClearAllPools()
        {
            MySqlPoolManager.ClearAllPools();
        }

        #endregion
    }

    /// <summary>
    /// Represents the method that will handle the <see cref="MySqlConnection.InfoMessage"/> event of a 
    /// <see cref="MySqlConnection"/>.
    /// </summary>
    public delegate void MySqlInfoMessageEventHandler(object sender, MySqlInfoMessageEventArgs args);

    /// <summary>
    /// Provides data for the InfoMessage event. This class cannot be inherited.
    /// </summary>
    public class MySqlInfoMessageEventArgs : EventArgs
    {
        /// <summary>
        /// 
        /// </summary>
        public MySqlError[] errors;
    }

    /// <summary>
    /// IDisposable wrapper around SetCommandTimeout and ClearCommandTimeout
    /// functionality
    /// </summary>
    internal class CommandTimer:IDisposable
    {
        bool timeoutSet;
        MySqlConnection connection;

        public CommandTimer(MySqlConnection connection, int timeout)
        {
            this.connection = connection;
            if (connection != null)
            {
                timeoutSet = connection.SetCommandTimeout(timeout);
            }
        }

        #region IDisposable Members
        public void Dispose()
        {
            if (timeoutSet)
            {
                timeoutSet = false;
                connection.ClearCommandTimeout();
                connection = null;
            }
        }
        #endregion
    }
}