Exemplo n.º 1
0
 public virtual void CloseQuery(MyCatConnection connection, int statementId)
 {
     if (handler.WarningCount > 0)
     {
         ReportWarnings(connection);
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Loads the properties from the connected server into a hashtable
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        private Dictionary <string, string> LoadServerProperties(MyCatConnection connection)
        {
            // load server properties
            Dictionary <string, string> hash = new Dictionary <string, string>();
            MyCatCommand cmd = new MyCatCommand("SHOW VARIABLES", connection);

            try
            {
                using (MyCatDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string key   = reader.GetString(0);
                        string value = reader.GetString(1);
                        hash[key] = value;
                    }
                }
                // Get time zone offset as numerical value
                timeZoneOffset = TimeZoneInfo.Local.BaseUtcOffset.Hours;
                return(hash);
            }
            catch (Exception ex)
            {
                MyCatTrace.LogError(ThreadID, ex.Message);
                throw;
            }
        }
        public override void CloseQuery(MyCatConnection connection, int statementId)
        {
            base.CloseQuery(connection, statementId);

            MyCatTrace.TraceEvent(TraceEventType.Information, MyCatTraceEventType.QueryClosed,
                                  Resources.TraceQueryDone, driverId);
        }
Exemplo n.º 4
0
 /// <include file='docs/mysqlcommand.xml' path='docs/ctor4/*'/>
 public MyCatCommand(string cmdText, MyCatConnection connection,
                     MyCatTransaction transaction)
     :
     this(cmdText, connection)
 {
     curTransaction = transaction;
 }
        public ProcedureCacheEntry GetProcedure(MyCatConnection conn, string spName, string cacheKey)
        {
            ProcedureCacheEntry proc = null;

            if (cacheKey != null)
            {
                int hash = cacheKey.GetHashCode();

                lock (procHash)
                {
                    procHash.TryGetValue(hash, out proc);
                }
            }
            if (proc == null)
            {
                proc = AddNew(conn, spName);
                conn.PerfMonitor.AddHardProcedureQuery();
                if (conn.Settings.Logging)
                {
                    MyCatTrace.LogInformation(conn.ServerThread,
                                              String.Format(Resources.HardProcQuery, spName));
                }
            }
            else
            {
                conn.PerfMonitor.AddSoftProcedureQuery();
                if (conn.Settings.Logging)
                {
                    MyCatTrace.LogInformation(conn.ServerThread,
                                              String.Format(Resources.SoftProcQuery, spName));
                }
            }
            return(proc);
        }
 public MyCatTransactionScope(MyCatConnection con, Transaction trans,
                              MyCatTransaction simpleTransaction)
 {
     connection             = con;
     baseTransaction        = trans;
     this.simpleTransaction = simpleTransaction;
 }
Exemplo n.º 7
0
        public virtual List <MyCatError> ReportWarnings(MyCatConnection connection)
        {
            List <MyCatError> warnings = new List <MyCatError>();

            MyCatCommand cmd = new MyCatCommand("SHOW WARNINGS", connection);

            cmd.InternallyCreated = true;
            using (MyCatDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    warnings.Add(new MyCatError(reader.GetString(0),
                                                reader.GetInt32(1), reader.GetString(2)));
                }
            }

            MyCatInfoMessageEventArgs args = new MyCatInfoMessageEventArgs();

            args.errors = warnings.ToArray();
            if (connection != null)
            {
                connection.OnInfoMessage(args);
            }
            return(warnings);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>.
        /// The state of the <see cref="MyCatConnection"/> object remains unchanged after execution
        /// of this method.
        /// </summary>
        /// <param name="connection"><see cref="MyCatConnection"/> object to use</param>
        /// <param name="commandText">Command to execute</param>
        /// <param name="commandParameters">Parameters to use for the command</param>
        /// <returns><see cref="DataSet"/> containing the resultset</returns>
        public static DataSet ExecuteDataset(MyCatConnection connection, string commandText, params MyCatParameter[] commandParameters)
        {
            //create a command and prepare it for execution
            MyCatCommand cmd = new MyCatCommand();

            cmd.Connection  = connection;
            cmd.CommandText = commandText;
            cmd.CommandType = CommandType.Text;

            if (commandParameters != null)
            {
                foreach (MyCatParameter p in commandParameters)
                {
                    cmd.Parameters.Add(p);
                }
            }

            //create the DataAdapter & DataSet
            MyCatDataAdapter da = new MyCatDataAdapter(cmd);
            DataSet          ds = new DataSet();

            //fill the DataSet using default values for DataTable names, etc.
            da.Fill(ds);

            // detach the MyCatParameters from the command object, so they can be used again.
            cmd.Parameters.Clear();

            //return the dataset
            return(ds);
        }
 public CommandTimer(MyCatConnection connection, int timeout)
 {
     this.connection = connection;
     if (connection != null)
     {
         timeoutSet = connection.SetCommandTimeout(timeout);
     }
 }
Exemplo n.º 10
0
 public void Dispose()
 {
     if (timeoutSet)
     {
         timeoutSet = false;
         connection.ClearCommandTimeout();
         connection = null;
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Executes a single command against a MySQL database.
        /// </summary>
        /// <param name="connectionString">Settings to use for this command</param>
        /// <param name="commandText">Command text to use</param>
        /// <param name="commandParameters">Array of <see cref="MyCatParameter"/> objects to use with the command</param>
        /// <returns><see cref="MyCatDataReader"/> object ready to read the results of the command</returns>
        public static MyCatDataReader ExecuteReader(string connectionString, string commandText, params MyCatParameter[] commandParameters)
        {
            //create & open a SqlConnection
            MyCatConnection cn = new MyCatConnection(connectionString);

            cn.Open();

            //call the private overload that takes an internally owned connection in place of the connection string
            return(ExecuteReader(cn, null, commandText, commandParameters, false));
        }
    public ExceptionInterceptor(MyCatConnection connection) 
    {
      this.connection = connection;

      LoadInterceptors(connection.Settings.ExceptionInterceptors);

      // we always have the standard interceptor
      interceptors.Add(new StandardExceptionInterceptor());

    }
        public override List <MyCatError> ReportWarnings(MyCatConnection connection)
        {
            List <MyCatError> warnings = base.ReportWarnings(connection);

            foreach (MyCatError warning in warnings)
            {
                MyCatTrace.TraceEvent(TraceEventType.Warning, MyCatTraceEventType.Warning,
                                      Resources.TraceWarning, driverId, warning.Level, warning.Code, warning.Message);
            }
            return(warnings);
        }
Exemplo n.º 14
0
 public MyCatBulkLoader(MyCatConnection connection)
 {
     Connection              = connection;
     Local                   = true;
     FieldTerminator         = defaultFieldTerminator;
     LineTerminator          = defaultLineTerminator;
     FieldQuotationCharacter = Char.MinValue;
     ConflictOption          = MyCatBulkLoaderConflictOption.None;
     columns                 = new List <string>();
     expressions             = new List <string>();
 }
Exemplo n.º 15
0
        /// <summary>
        /// Executes a single command against a MySQL database.  A new <see cref="MyCatConnection"/> is created
        /// using the <see cref="MyCatConnection.ConnectionString"/> given.
        /// </summary>
        /// <param name="connectionString"><see cref="MyCatConnection.ConnectionString"/> to use</param>
        /// <param name="commandText">SQL command to be executed</param>
        /// <param name="parms">Array of <see cref="MyCatParameter"/> objects to use with the command.</param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string connectionString, string commandText, params MyCatParameter[] parms)
        {
            //create & open a SqlConnection, and dispose of it after we are done.
            using (MyCatConnection cn = new MyCatConnection(connectionString))
            {
                cn.Open();

                //call the overload that takes a connection in place of the connection string
                return(ExecuteNonQuery(cn, commandText, parms));
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a new MyCatConnection object with the exact same ConnectionString value
        /// </summary>
        /// <returns>A cloned MyCatConnection object</returns>
        public object Clone()
        {
            MyCatConnection clone            = new MyCatConnection();
            string          connectionString = Settings.ConnectionString;

            if (connectionString != null)
            {
                clone.ConnectionString = connectionString;
            }
            return(clone);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Updates the given table with data from the given <see cref="DataSet"/>
        /// </summary>
        /// <param name="connectionString">Settings to use for the update</param>
        /// <param name="commandText">Command text to use for the update</param>
        /// <param name="ds"><see cref="DataSet"/> containing the new data to use in the update</param>
        /// <param name="tablename">Tablename in the dataset to update</param>
        public static void UpdateDataSet(string connectionString, string commandText, DataSet ds, string tablename)
        {
            MyCatConnection cn = new MyCatConnection(connectionString);

            cn.Open();
            MyCatDataAdapter    da = new MyCatDataAdapter(commandText, cn);
            MyCatCommandBuilder cb = new MyCatCommandBuilder(da);

            cb.ToString();
            da.Update(ds, tablename);
            cn.Close();
        }
Exemplo n.º 18
0
 internal static string GetDefaultCollation(string charset, MyCatConnection connection)
 {
     lock (lockObject)
     {
         if (defaultCollations == null)
         {
             InitCollections(connection);
         }
     }
     if (!defaultCollations.ContainsKey(charset))
     {
         return(null);
     }
     return(defaultCollations[charset]);
 }
Exemplo n.º 19
0
        internal static int GetMaxLength(string charset, MyCatConnection connection)
        {
            lock (lockObject)
            {
                if (maxLengths == null)
                {
                    InitCollections(connection);
                }
            }

            if (!maxLengths.ContainsKey(charset))
            {
                return(1);
            }
            return(maxLengths[charset]);
        }
Exemplo n.º 20
0
        internal static void InitCollections(MyCatConnection connection)
        {
            defaultCollations = new Dictionary <string, string>();
            maxLengths        = new Dictionary <string, int>();

            MyCatCommand cmd = new MyCatCommand("SHOW CHARSET", connection);

            using (MyCatDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    defaultCollations.Add(reader.GetString(0), reader.GetString(2));
                    maxLengths.Add(reader.GetString(0), Convert.ToInt32(reader.GetValue(3)));
                }
            }
        }
Exemplo n.º 21
0
        /*
         * Because the user should not be able to directly create a
         * DataReader object, the constructors are
         * marked as internal.
         */
        internal MyCatDataReader(MyCatCommand cmd, PreparableStatement statement, CommandBehavior behavior)
        {
            this.command    = cmd;
            connection      = (MyCatConnection)command.Connection;
            commandBehavior = behavior;
            driver          = connection.driver;
            affectedRows    = -1;
            this.statement  = statement;

#if !RT
            if (cmd.CommandType == CommandType.StoredProcedure &&
                cmd.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord
                )
            {
                disableZeroAffectedRows = true;
            }
#endif
        }
        private static ProcedureCacheEntry GetProcData(MyCatConnection connection, string spName)
        {
            string schema = String.Empty;
            string name   = spName;

            int dotIndex = spName.IndexOf(".");

            if (dotIndex != -1)
            {
                schema = spName.Substring(0, dotIndex);
                name   = spName.Substring(dotIndex + 1, spName.Length - dotIndex - 1);
            }

            string[] restrictions = new string[4];
            restrictions[1] = schema.Length > 0 ? schema : connection.CurrentDatabase();
            restrictions[2] = name;
            MyCatSchemaCollection proc = connection.GetSchemaCollection("procedures", restrictions);

            if (proc.Rows.Count > 1)
            {
                throw new MyCatException(Resources.ProcAndFuncSameName);
            }
            if (proc.Rows.Count == 0)
            {
                throw new MyCatException(String.Format(Resources.InvalidProcName, name, schema));
            }

            ProcedureCacheEntry entry = new ProcedureCacheEntry();

            entry.procedure = proc;

            // we don't use GetSchema here because that would cause another
            // query of procedures and we don't need that since we already
            // know the procedure we care about.
            ISSchemaProvider isp = new ISSchemaProvider(connection);

            string[] rest = isp.CleanRestrictions(restrictions);
            MyCatSchemaCollection parameters = isp.GetProcedureParameters(rest, proc);

            entry.parameters = parameters;

            return(entry);
        }
Exemplo n.º 23
0
        public void CancelQuery(int timeout)
        {
            MyCatConnectionStringBuilder cb = new MyCatConnectionStringBuilder(
                Settings.ConnectionString);

            cb.Pooling           = false;
            cb.AutoEnlist        = false;
            cb.ConnectionTimeout = (uint)timeout;

            using (MyCatConnection c = new MyCatConnection(cb.ConnectionString))
            {
                c.isKillQueryConnection = true;
                c.Open();
                string       commandText = "KILL QUERY " + ServerThread;
                MyCatCommand cmd         = new MyCatCommand(commandText, c);
                cmd.CommandTimeout = timeout;
                cmd.ExecuteNonQuery();
            }
        }
Exemplo n.º 24
0
        public SystemPerformanceMonitor(MyCatConnection connection) : base(connection)
        {
            string categoryName = Resources.PerfMonCategoryName;

            if (connection.Settings.UsePerformanceMonitor && procedureHardQueries == null)
            {
                try
                {
                    procedureHardQueries = new PerformanceCounter(categoryName,
                                                                  "HardProcedureQueries", false);
                    procedureSoftQueries = new PerformanceCounter(categoryName,
                                                                  "SoftProcedureQueries", false);
                }
                catch (Exception ex)
                {
                    MyCatTrace.LogError(connection.ServerThread, ex.Message);
                }
            }
        }
Exemplo n.º 25
0
        public Task ClearPoolAsync(MyCatConnection connection, CancellationToken cancellationToken)
        {
            var result = new TaskCompletionSource <bool>();

            if (cancellationToken == CancellationToken.None || !cancellationToken.IsCancellationRequested)
            {
                try
                {
                    ClearPool(connection);
                    result.SetResult(true);
                }
                catch (Exception ex)
                {
                    result.SetException(ex);
                }
            }
            else
            {
                result.SetCanceled();
            }
            return(result.Task);
        }
Exemplo n.º 26
0
        public static Task <object> ExecuteScalarAsync(MyCatConnection connection, string commandText, CancellationToken cancellationToken, params MyCatParameter[] commandParameters)
        {
            var result = new TaskCompletionSource <object>();

            if (cancellationToken == CancellationToken.None || !cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var scalarResult = ExecuteScalar(connection, commandText, commandParameters);
                    result.SetResult(scalarResult);
                }
                catch (Exception ex)
                {
                    result.SetException(ex);
                }
            }
            else
            {
                result.SetCanceled();
            }
            return(result.Task);
        }
Exemplo n.º 27
0
        private static Task <MyCatDataReader> ExecuteReaderAsync(MyCatConnection connection, MyCatTransaction transaction, string commandText, MyCatParameter[] commandParameters, bool ExternalConn, CancellationToken cancellationToken)
        {
            var result = new TaskCompletionSource <MyCatDataReader>();

            if (cancellationToken == CancellationToken.None || !cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var reader = ExecuteReader(connection, transaction, commandText, commandParameters, ExternalConn);
                    result.SetResult(reader);
                }
                catch (Exception ex)
                {
                    result.SetException(ex);
                }
            }
            else
            {
                result.SetCanceled();
            }
            return(result.Task);
        }
        private ProcedureCacheEntry AddNew(MyCatConnection connection, string spName)
        {
            ProcedureCacheEntry procData = GetProcData(connection, spName);

            if (maxSize > 0)
            {
                string cacheKey = GetCacheKey(spName, procData);
                int    hash     = cacheKey.GetHashCode();
                lock (procHash)
                {
                    if (procHash.Keys.Count >= maxSize)
                    {
                        TrimHash();
                    }
                    if (!procHash.ContainsKey(hash))
                    {
                        procHash[hash] = procData;
                        hashQueue.Enqueue(hash);
                    }
                }
            }
            return(procData);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Executes a single command against a MySQL database.  The <see cref="MyCatConnection"/> is assumed to be
        /// open when the method is called and remains open after the method completes.
        /// </summary>
        /// <param name="connection"><see cref="MyCatConnection"/> object to use</param>
        /// <param name="commandText">SQL command to be executed</param>
        /// <param name="commandParameters">Array of <see cref="MyCatParameter"/> objects to use with the command.</param>
        /// <returns></returns>
        public static int ExecuteNonQuery(MyCatConnection connection, string commandText, params MyCatParameter[] commandParameters)
        {
            //create a command and prepare it for execution
            MyCatCommand cmd = new MyCatCommand();

            cmd.Connection  = connection;
            cmd.CommandText = commandText;
            cmd.CommandType = CommandType.Text;

            if (commandParameters != null)
            {
                foreach (MyCatParameter p in commandParameters)
                {
                    cmd.Parameters.Add(p);
                }
            }

            int result = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();

            return(result);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Loads all the current character set names and ids for this server
        /// into the charSets hashtable
        /// </summary>
        private void LoadCharacterSets(MyCatConnection connection)
        {
            MyCatCommand cmd = new MyCatCommand("SHOW COLLATION", connection);

            // now we load all the currently active collations
            try
            {
                using (MyCatDataReader reader = cmd.ExecuteReader())
                {
                    charSets = new Dictionary <int, string>();
                    while (reader.Read())
                    {
                        charSets[Convert.ToInt32(reader["id"], NumberFormatInfo.InvariantInfo)] =
                            reader.GetString(reader.GetOrdinal("charset"));
                    }
                }
            }
            catch (Exception ex)
            {
                MyCatTrace.LogError(ThreadID, ex.Message);
                throw;
            }
        }