internal MySqlParameterCollection(MySqlCommand cmd)
 {
   indexHashCS = new Dictionary<string, int>();
   indexHashCI = new Dictionary<string,int>(StringComparer.CurrentCultureIgnoreCase);
   containsUnnamedParameters = false;
   Clear();
 }
Exemplo n.º 2
0
    /// <summary>
    /// Executes a single command against a MySQL database.  The <see cref="MySqlConnection"/> is assumed to be
    /// open when the method is called and remains open after the method completes.
    /// </summary>
    /// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
    /// <param name="commandText">SQL command to be executed</param>
    /// <param name="commandParameters">Array of <see cref="MySqlParameter"/> objects to use with the command.</param>
    /// <returns></returns>
    public static int ExecuteNonQuery(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters)
    {
      //create a command and prepare it for execution
      MySqlCommand cmd = new MySqlCommand();
      cmd.Connection = connection;
      cmd.CommandText = commandText;
      cmd.CommandType = CommandType.Text;

      if (commandParameters != null)
        foreach (MySqlParameter p in commandParameters)
          cmd.Parameters.Add(p);

      int result = cmd.ExecuteNonQuery();
      cmd.Parameters.Clear();

      return result;
    }
Exemplo n.º 3
0
        /// <summary>
        /// Retrieves parameter information from the stored procedure specified 
        /// in the MySqlCommand and populates the Parameters collection of the 
        /// specified MySqlCommand object.
        /// This method is not currently supported since stored procedures are 
        /// not available in MySql.
        /// </summary>
        /// <param name="command">The MySqlCommand referencing the stored 
        /// procedure from which the parameter information is to be derived. 
        /// The derived parameters are added to the Parameters collection of the 
        /// MySqlCommand.</param>
        /// <exception cref="InvalidOperationException">The command text is not 
        /// a valid stored procedure name.</exception>
        public static void DeriveParameters(MySqlCommand command)
        {
            if (command.CommandType != CommandType.StoredProcedure)
                throw new InvalidOperationException(Resources.CanNotDeriveParametersForTextCommands);

            // retrieve the proc definition from the cache.
            string spName = command.CommandText;
            if (spName.IndexOf(".") == -1)
                spName = command.Connection.Database + "." + spName;

            try
            {
                ProcedureCacheEntry entry = command.Connection.ProcedureCache.GetProcedure(command.Connection, spName, null);
                command.Parameters.Clear();
                foreach (MySqlSchemaRow row in entry.parameters.Rows)
                {
                    MySqlParameter p = new MySqlParameter();
                    p.ParameterName = String.Format("@{0}", row["PARAMETER_NAME"]);
                    if (row["ORDINAL_POSITION"].Equals(0) && p.ParameterName == "@")
                        p.ParameterName = "@RETURN_VALUE";
                    p.Direction = GetDirection(row);
                    bool unsigned = StoredProcedure.GetFlags(row["DTD_IDENTIFIER"].ToString()).IndexOf("UNSIGNED") != -1;
                    bool real_as_float = entry.procedure.Rows[0]["SQL_MODE"].ToString().IndexOf("REAL_AS_FLOAT") != -1;
                    p.MySqlDbType = MetaData.NameToType(row["DATA_TYPE"].ToString(),
                      unsigned, real_as_float, command.Connection);
                    if (row["CHARACTER_MAXIMUM_LENGTH"] != null)
                        p.Size = (int)row["CHARACTER_MAXIMUM_LENGTH"];
#if NET452 || DNX452 || NETSTANDARD1_6
          if (row["NUMERIC_PRECISION"] != null)
            p.Precision = Convert.ToByte(row["NUMERIC_PRECISION"]);
          if (row["NUMERIC_SCALE"] != null )
            p.Scale = Convert.ToByte(row["NUMERIC_SCALE"]);
#endif
                    if (p.MySqlDbType == MySqlDbType.Set || p.MySqlDbType == MySqlDbType.Enum)
                        p.PossibleValues = GetPossibleValues(row);
                    command.Parameters.Add(p);
                }
            }
            catch (InvalidOperationException ioe)
            {
                throw new MySqlException(Resources.UnableToDeriveParameters, ioe);
            }
        }
Exemplo n.º 4
0
 internal void AddToBatch(MySqlCommand command)
 {
     if (batch == null)
         batch = new List<MySqlCommand>();
     batch.Add(command);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Creates a clone of this MySqlCommand object.  CommandText, Connection, and Transaction properties
        /// are included as well as the entire parameter list.
        /// </summary>
        /// <returns>The cloned MySqlCommand object</returns>
        public MySqlCommand Clone()
        {
            MySqlCommand clone = new MySqlCommand(cmdText, connection, curTransaction);
            clone.CommandType = CommandType;
            clone.commandTimeout = commandTimeout;
            clone.useDefaultTimeout = useDefaultTimeout;
            clone.batchableCommandText = batchableCommandText;
            clone.EnableCaching = EnableCaching;
            clone.CacheAge = CacheAge;
            PartialClone(clone);

            foreach (MySqlParameter p in parameters)
            {
                clone.Parameters.Add(p.Clone());
            }
            return clone;
        }
Exemplo n.º 6
0
 /// <include file='docs/MySqlDataAdapter.xml' path='docs/Ctor2/*'/>
 public MySqlDataAdapter(string selectCommandText, MySqlConnection connection)
   : this()
 {
     SelectCommand = new MySqlCommand(selectCommandText, connection);
 }
Exemplo n.º 7
0
 partial void PartialClone(MySqlCommand clone)
 {
   clone.UpdatedRowSource = UpdatedRowSource;
 }
Exemplo n.º 8
0
 private Statement(MySqlCommand cmd)
 {
   command = cmd;
   buffers = new List<MySqlPacket>();
 }
Exemplo n.º 9
0
        public virtual MySqlSchemaCollection GetIndexColumns(string[] restrictions)
        {
            MySqlSchemaCollection dt = new MySqlSchemaCollection("IndexColumns");
            dt.AddColumn("INDEX_CATALOG", typeof(string));
            dt.AddColumn("INDEX_SCHEMA", typeof(string));
            dt.AddColumn("INDEX_NAME", typeof(string));
            dt.AddColumn("TABLE_NAME", typeof(string));
            dt.AddColumn("COLUMN_NAME", typeof(string));
            dt.AddColumn("ORDINAL_POSITION", typeof(int));
            dt.AddColumn("SORT_ORDER", typeof(string));

            int max = restrictions == null ? 4 : restrictions.Length;
            string[] tableRestrictions = new string[Math.Max(max, 4)];
            if (restrictions != null)
                restrictions.CopyTo(tableRestrictions, 0);
            tableRestrictions[3] = "BASE TABLE";
            MySqlSchemaCollection tables = GetTables(tableRestrictions);

            foreach (MySqlSchemaRow table in tables.Rows)
            {
                string sql = String.Format("SHOW INDEX FROM `{0}`.`{1}`",
                               table["TABLE_SCHEMA"], table["TABLE_NAME"]);
                MySqlCommand cmd = new MySqlCommand(sql, connection);
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string key_name = GetString(reader, reader.GetOrdinal("KEY_NAME"));
                        string col_name = GetString(reader, reader.GetOrdinal("COLUMN_NAME"));

                        if (restrictions != null)
                        {
                            if (restrictions.Length >= 4 && restrictions[3] != null &&
                              key_name != restrictions[3])
                                continue;
                            if (restrictions.Length >= 5 && restrictions[4] != null &&
                              col_name != restrictions[4])
                                continue;
                        }
                        MySqlSchemaRow row = dt.AddRow();
                        row["INDEX_CATALOG"] = null;
                        row["INDEX_SCHEMA"] = table["TABLE_SCHEMA"];
                        row["INDEX_NAME"] = key_name;
                        row["TABLE_NAME"] = GetString(reader, reader.GetOrdinal("TABLE"));
                        row["COLUMN_NAME"] = col_name;
                        row["ORDINAL_POSITION"] = reader.GetValue(reader.GetOrdinal("SEQ_IN_INDEX"));
                        row["SORT_ORDER"] = reader.GetString("COLLATION");
                    }
                }
            }

            return dt;
        }
Exemplo n.º 10
0
        private void LoadTableColumns(MySqlSchemaCollection schemaCollection, string schema,
                        string tableName, string columnRestriction)
        {
            string sql = String.Format("SHOW FULL COLUMNS FROM `{0}`.`{1}`",
                           schema, tableName);
            MySqlCommand cmd = new MySqlCommand(sql, connection);

            int pos = 1;
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    string colName = reader.GetString(0);
                    if (columnRestriction != null && colName != columnRestriction)
                        continue;
                    MySqlSchemaRow row = schemaCollection.AddRow();
                    row["TABLE_CATALOG"] = DBNull.Value;
                    row["TABLE_SCHEMA"] = schema;
                    row["TABLE_NAME"] = tableName;
                    row["COLUMN_NAME"] = colName;
                    row["ORDINAL_POSITION"] = pos++;
                    row["COLUMN_DEFAULT"] = reader.GetValue(5);
                    row["IS_NULLABLE"] = reader.GetString(3);
                    row["DATA_TYPE"] = reader.GetString(1);
                    row["CHARACTER_MAXIMUM_LENGTH"] = DBNull.Value;
                    row["CHARACTER_OCTET_LENGTH"] = DBNull.Value;
                    row["NUMERIC_PRECISION"] = DBNull.Value;
                    row["NUMERIC_SCALE"] = DBNull.Value;
                    row["CHARACTER_SET_NAME"] = reader.GetValue(2);
                    row["COLLATION_NAME"] = row["CHARACTER_SET_NAME"];
                    row["COLUMN_TYPE"] = reader.GetString(1);
                    row["COLUMN_KEY"] = reader.GetString(4);
                    row["EXTRA"] = reader.GetString(6);
                    row["PRIVILEGES"] = reader.GetString(7);
                    row["COLUMN_COMMENT"] = reader.GetString(8);
                    ParseColumnRow(row);
                }
            }
        }
Exemplo n.º 11
0
        protected MySqlSchemaCollection QueryCollection(string name, string sql)
        {
            MySqlSchemaCollection c = new MySqlSchemaCollection(name);
            MySqlCommand cmd = new MySqlCommand(sql, connection);
            MySqlDataReader reader = cmd.ExecuteReader();

            for (int i = 0; i < reader.FieldCount; i++)
                c.AddColumn(reader.GetName(i), reader.GetFieldType(i));

            using (reader)
            {
                while (reader.Read())
                {
                    MySqlSchemaRow row = c.AddRow();
                    for (int i = 0; i < reader.FieldCount; i++)
                        row[i] = reader.GetValue(i);
                }
            }
            return c;
        }
Exemplo n.º 12
0
    /// <summary>
    /// Execute the load operation
    /// </summary>
    /// <returns>The number of rows inserted.</returns>
    public int Load()
    {
      bool openedConnection = false;

      if (Connection == null)
        throw new InvalidOperationException(Resources.ConnectionNotSet);

      // next we open up the connetion if it is not already open
      if (connection.State != ConnectionState.Open)
      {
        openedConnection = true;
        connection.Open();
      }

      try
      {
        string sql = BuildSqlCommand();
        MySqlCommand cmd = new MySqlCommand(sql, Connection);
        cmd.CommandTimeout = Timeout;
        return cmd.ExecuteNonQuery();
      }
      finally
      {
        if (openedConnection)
          connection.Close();
      }
    }
Exemplo n.º 13
0
        public virtual List<MySqlError> ReportWarnings(MySqlConnection connection)
        {
            List<MySqlError> warnings = new List<MySqlError>();

            MySqlCommand cmd = new MySqlCommand("SHOW WARNINGS", connection);
            cmd.InternallyCreated = true;
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    warnings.Add(new MySqlError(reader.GetString(0),
                                  reader.GetInt32(1), reader.GetString(2)));
                }
            }

            MySqlInfoMessageEventArgs args = new MySqlInfoMessageEventArgs();
            args.errors = warnings.ToArray();
            if (connection != null)
                connection.OnInfoMessage(args);
            return warnings;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Loads all the current character set names and ids for this server 
        /// into the charSets hashtable
        /// </summary>
        private void LoadCharacterSets(MySqlConnection connection)
        {
            MySqlCommand cmd = new MySqlCommand("SHOW COLLATION", connection);

            // now we load all the currently active collations
            try
            {
                using (MySqlDataReader 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)
            {
                MySqlTrace.LogError(ThreadID, ex.Message);
                throw;
            }
        }
Exemplo n.º 15
0
        private int GetTimeZoneOffset(MySqlConnection con)
        {
            MySqlCommand cmd = new MySqlCommand("select timediff( curtime(), utc_time() )", con);
            string s = cmd.ExecuteScalar() as string;
            if (s == null) s = "0:00";

            return int.Parse(s.Substring(0, s.IndexOf(':')));
        }
Exemplo n.º 16
0
 internal string CurrentDatabase()
 {
     if (Database != null && Database.Length > 0)
         return Database;
     MySqlCommand cmd = new MySqlCommand("SELECT database()", this);
     return cmd.ExecuteScalar().ToString();
 }
Exemplo n.º 17
0
        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();
            }
        }
Exemplo n.º 18
0
 private string GetSqlMode()
 {
     MySqlCommand cmd = new MySqlCommand("SELECT @@SQL_MODE", connection);
     return cmd.ExecuteScalar().ToString();
 }
Exemplo n.º 19
0
 public Statement(MySqlCommand cmd, string text)
   : this(cmd)
 {
   commandText = text;
 }
Exemplo n.º 20
0
        /// <summary>
        /// GetForeignKeysOnTable retrieves the foreign keys on the given table.
        /// Since MySQL supports foreign keys on versions prior to 5.0, we can't  use
        /// information schema.  MySQL also does not include any type of SHOW command
        /// for foreign keys so we have to resort to use SHOW CREATE TABLE and parsing
        /// the output.
        /// </summary>
        /// <param name="fkTable">The table to store the key info in.</param>
        /// <param name="tableToParse">The table to get the foeign key info for.</param>
        /// <param name="filterName">Only get foreign keys that match this name.</param>
        /// <param name="includeColumns">Should column information be included in the table.</param>
        private void GetForeignKeysOnTable(MySqlSchemaCollection fkTable, MySqlSchemaRow tableToParse,
                           string filterName, bool includeColumns)
        {
            string sqlMode = GetSqlMode();

            if (filterName != null)
                filterName = StringUtility.ToLowerInvariant(filterName);

            string sql = string.Format("SHOW CREATE TABLE `{0}`.`{1}`",
                           tableToParse["TABLE_SCHEMA"], tableToParse["TABLE_NAME"]);
            string lowerBody = null, body = null;
            MySqlCommand cmd = new MySqlCommand(sql, connection);
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                reader.Read();
                body = reader.GetString(1);
                lowerBody = StringUtility.ToLowerInvariant(body);
            }

            MySqlTokenizer tokenizer = new MySqlTokenizer(lowerBody);
            tokenizer.AnsiQuotes = sqlMode.IndexOf("ANSI_QUOTES") != -1;
            tokenizer.BackslashEscapes = sqlMode.IndexOf("NO_BACKSLASH_ESCAPES") != -1;

            while (true)
            {
                string token = tokenizer.NextToken();
                // look for a starting contraint
                while (token != null && (token != "constraint" || tokenizer.Quoted))
                    token = tokenizer.NextToken();
                if (token == null) break;

                ParseConstraint(fkTable, tableToParse, tokenizer, includeColumns);
            }
        }
Exemplo n.º 21
0
 /// <include file='docs/MySqlDataAdapter.xml' path='docs/Ctor1/*'/>
 public MySqlDataAdapter(MySqlCommand selectCommand)
   : this()
 {
     SelectCommand = selectCommand;
 }
Exemplo n.º 22
0
        public virtual MySqlSchemaCollection GetProcedures(string[] restrictions)
        {
            MySqlSchemaCollection dt = new MySqlSchemaCollection("Procedures");
            dt.AddColumn("SPECIFIC_NAME", typeof(string));
            dt.AddColumn("ROUTINE_CATALOG", typeof(string));
            dt.AddColumn("ROUTINE_SCHEMA", typeof(string));
            dt.AddColumn("ROUTINE_NAME", typeof(string));
            dt.AddColumn("ROUTINE_TYPE", typeof(string));
            dt.AddColumn("DTD_IDENTIFIER", typeof(string));
            dt.AddColumn("ROUTINE_BODY", typeof(string));
            dt.AddColumn("ROUTINE_DEFINITION", typeof(string));
            dt.AddColumn("EXTERNAL_NAME", typeof(string));
            dt.AddColumn("EXTERNAL_LANGUAGE", typeof(string));
            dt.AddColumn("PARAMETER_STYLE", typeof(string));
            dt.AddColumn("IS_DETERMINISTIC", typeof(string));
            dt.AddColumn("SQL_DATA_ACCESS", typeof(string));
            dt.AddColumn("SQL_PATH", typeof(string));
            dt.AddColumn("SECURITY_TYPE", typeof(string));
            dt.AddColumn("CREATED", typeof(DateTime));
            dt.AddColumn("LAST_ALTERED", typeof(DateTime));
            dt.AddColumn("SQL_MODE", typeof(string));
            dt.AddColumn("ROUTINE_COMMENT", typeof(string));
            dt.AddColumn("DEFINER", typeof(string));

            StringBuilder sql = new StringBuilder("SELECT * FROM mysql.proc WHERE 1=1");
            if (restrictions != null)
            {
                if (restrictions.Length >= 2 && restrictions[1] != null)
                    sql.AppendFormat(CultureInfo.InvariantCulture,
                      " AND db LIKE '{0}'", restrictions[1]);
                if (restrictions.Length >= 3 && restrictions[2] != null)
                    sql.AppendFormat(CultureInfo.InvariantCulture,
                      " AND name LIKE '{0}'", restrictions[2]);
                if (restrictions.Length >= 4 && restrictions[3] != null)
                    sql.AppendFormat(CultureInfo.InvariantCulture,
                      " AND type LIKE '{0}'", restrictions[3]);
            }

            MySqlCommand cmd = new MySqlCommand(sql.ToString(), connection);
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    MySqlSchemaRow row = dt.AddRow();
                    row["SPECIFIC_NAME"] = reader.GetString("specific_name");
                    row["ROUTINE_CATALOG"] = DBNull.Value;
                    row["ROUTINE_SCHEMA"] = reader.GetString("db");
                    row["ROUTINE_NAME"] = reader.GetString("name");
                    string routineType = reader.GetString("type");
                    row["ROUTINE_TYPE"] = routineType;
                    row["DTD_IDENTIFIER"] = StringUtility.ToLowerInvariant(routineType) == "function" ?
                      (object)reader.GetString("returns") : DBNull.Value;
                    row["ROUTINE_BODY"] = "SQL";
                    row["ROUTINE_DEFINITION"] = reader.GetString("body");
                    row["EXTERNAL_NAME"] = DBNull.Value;
                    row["EXTERNAL_LANGUAGE"] = DBNull.Value;
                    row["PARAMETER_STYLE"] = "SQL";
                    row["IS_DETERMINISTIC"] = reader.GetString("is_deterministic");
                    row["SQL_DATA_ACCESS"] = reader.GetString("sql_data_access");
                    row["SQL_PATH"] = DBNull.Value;
                    row["SECURITY_TYPE"] = reader.GetString("security_type");
                    row["CREATED"] = reader.GetDateTime("created");
                    row["LAST_ALTERED"] = reader.GetDateTime("modified");
                    row["SQL_MODE"] = reader.GetString("sql_mode");
                    row["ROUTINE_COMMENT"] = reader.GetString("comment");
                    row["DEFINER"] = reader.GetString("definer");
                }
            }

            return dt;
        }
Exemplo n.º 23
0
 /// <include file='docs/MySqlDataAdapter.xml' path='docs/Ctor3/*'/>
 public MySqlDataAdapter(string selectCommandText, string selectConnString)
   : this()
 {
     SelectCommand = new MySqlCommand(selectCommandText,
       new MySqlConnection(selectConnString));
 }
Exemplo n.º 24
0
        private void FindTables(MySqlSchemaCollection schema, string[] restrictions)
        {
            StringBuilder sql = new StringBuilder();
            StringBuilder where = new StringBuilder();
            sql.AppendFormat(CultureInfo.InvariantCulture,
                     "SHOW TABLE STATUS FROM `{0}`", restrictions[1]);
            if (restrictions != null && restrictions.Length >= 3 &&
              restrictions[2] != null)
                where.AppendFormat(CultureInfo.InvariantCulture,
                           " LIKE '{0}'", restrictions[2]);
            sql.Append(where.ToString());

            string table_type = restrictions[1].ToLower() == "information_schema"
                        ?
                      "SYSTEM VIEW"
                        : "BASE TABLE";

            MySqlCommand cmd = new MySqlCommand(sql.ToString(), connection);
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    MySqlSchemaRow row = schema.AddRow();
                    row["TABLE_CATALOG"] = null;
                    row["TABLE_SCHEMA"] = restrictions[1];
                    row["TABLE_NAME"] = reader.GetString(0);
                    row["TABLE_TYPE"] = table_type;
                    row["ENGINE"] = GetString(reader, 1);
                    row["VERSION"] = reader.GetValue(2);
                    row["ROW_FORMAT"] = GetString(reader, 3);
                    row["TABLE_ROWS"] = reader.GetValue(4);
                    row["AVG_ROW_LENGTH"] = reader.GetValue(5);
                    row["DATA_LENGTH"] = reader.GetValue(6);
                    row["MAX_DATA_LENGTH"] = reader.GetValue(7);
                    row["INDEX_LENGTH"] = reader.GetValue(8);
                    row["DATA_FREE"] = reader.GetValue(9);
                    row["AUTO_INCREMENT"] = reader.GetValue(10);
                    row["CREATE_TIME"] = reader.GetValue(11);
                    row["UPDATE_TIME"] = reader.GetValue(12);
                    row["CHECK_TIME"] = reader.GetValue(13);
                    row["TABLE_COLLATION"] = GetString(reader, 14);
                    row["CHECKSUM"] = reader.GetValue(15);
                    row["CREATE_OPTIONS"] = GetString(reader, 16);
                    row["TABLE_COMMENT"] = GetString(reader, 17);
                }
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// Reset SQL_SELECT_LIMIT that could have been modified by CommandBehavior.
 /// </summary>
 internal void ResetSqlSelectLimit()
 {
     // if we are supposed to reset the sql select limit, do that here
     if (resetSqlSelect)
     {
         resetSqlSelect = false;
         MySqlCommand command = new MySqlCommand("SET SQL_SELECT_LIMIT=DEFAULT", connection);
         command.internallyCreated = true;
         command.ExecuteNonQuery();
     }
 }
Exemplo n.º 26
0
        public virtual MySqlSchemaCollection GetUDF(string[] restrictions)
        {
            string sql = "SELECT name,ret,dl FROM mysql.func";
            if (restrictions != null)
            {
                if (restrictions.Length >= 1 && !String.IsNullOrEmpty(restrictions[0]))
                    sql += String.Format(" WHERE name LIKE '{0}'", restrictions[0]);
            }

            MySqlSchemaCollection dt = new MySqlSchemaCollection("User-defined Functions");
            dt.AddColumn("NAME", typeof(string));
            dt.AddColumn("RETURN_TYPE", typeof(int));
            dt.AddColumn("LIBRARY_NAME", typeof(string));

            MySqlCommand cmd = new MySqlCommand(sql, connection);
            try
            {
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        MySqlSchemaRow row = dt.AddRow();
                        row[0] = reader.GetString(0);
                        row[1] = reader.GetInt32(1);
                        row[2] = reader.GetString(2);
                    }
                }
            }
            catch (MySqlException ex)
            {
                if (ex.Number != (int)MySqlErrorCode.TableAccessDenied)
                    throw;
                throw new MySqlException(Resources.UnableToEnumerateUDF, ex);
            }

            return dt;
        }
Exemplo n.º 27
0
 partial void PartialClone(MySqlCommand clone);
Exemplo n.º 28
0
        /// <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));
                    break;
                case IsolationLevel.Snapshot:
                    Throw(new NotSupportedException(Resources.SnapshotNotSupported));
                    break;
            }

            cmd.ExecuteNonQuery();

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

            return t;
        }
Exemplo n.º 29
0
        internal string GetCommandTextForBatching()
        {
            if (batchableCommandText == null)
            {
                // if the command starts with insert and is "simple" enough, then
                // we can use the multi-value form of insert
                if (String.Compare(CommandText.Substring(0, 6), "INSERT", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    MySqlCommand cmd = new MySqlCommand("SELECT @@sql_mode", Connection);
                    string sql_mode = StringUtility.ToUpperInvariant(cmd.ExecuteScalar().ToString());
                    MySqlTokenizer tokenizer = new MySqlTokenizer(CommandText);
                    tokenizer.AnsiQuotes = sql_mode.IndexOf("ANSI_QUOTES") != -1;
                    tokenizer.BackslashEscapes = sql_mode.IndexOf("NO_BACKSLASH_ESCAPES") == -1;
                    string token = StringUtility.ToLowerInvariant(tokenizer.NextToken());
                    while (token != null)
                    {
                        if (StringUtility.ToUpperInvariant(token) == "VALUES" &&
                            !tokenizer.Quoted)
                        {
                            token = tokenizer.NextToken();
                            if (token != "(")
                                throw new Exception();

                            // find matching right paren, and ensure that parens 
                            // are balanced.
                            int openParenCount = 1;
                            while (token != null)
                            {
                                batchableCommandText += token;
                                token = tokenizer.NextToken();

                                if (token == "(")
                                    openParenCount++;
                                else if (token == ")")
                                    openParenCount--;

                                if (openParenCount == 0)
                                    break;
                            }

                            if (token != null)
                                batchableCommandText += token;
                            token = tokenizer.NextToken();
                            if (token != null && (token == "," ||
                                StringUtility.ToUpperInvariant(token) == "ON"))
                            {
                                batchableCommandText = null;
                                break;
                            }
                        }
                        token = tokenizer.NextToken();
                    }
                }
                // Otherwise use the command verbatim
                else batchableCommandText = CommandText;
            }

            return batchableCommandText;
        }
Exemplo n.º 30
0
 /// <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;
 }