Use MySQL specific syntax for engine type and character encoding
547436
function (name, generator, options) {
            options = options || {};
            var engine = options.engine, charset = options.charset, collate = options.collate;
            if (isUndefined(engine)) {
                engine = this._static.defaultEngine;
            }
            if (isUndefined(charset)) {
                charset = this._static.defaultCharset;
            }
            if (isUndefined(collate)) {
                collate = this._static.defaultCollate;
            }
            generator.columns.forEach(function (c) {
                var t = c.table;
                if (t) {
                    delete c.table;
                    generator.foreignKey([c.name], t, merge({}, c, {name: null, type: "foreignKey"}));
                }
            });
            return format(" %s%s%s%s", this._super(arguments), engine ? " ENGINE=" + engine : "",
                charset ? " DEFAULT CHARSET=" + charset : "", collate ? " DEFAULT COLLATE=" + collate : "");
        }
413610
def mysql_to_dict(data, key):
    '''
    
    '''
    ret = {}
    headers = ['']
    for line in data:
        if not line:
            continue
        if line.startswith('+'):
            continue
        comps = line.split('|')
        for comp in range(len(comps)):
            comps[comp] = comps[comp].strip()
        if len(headers) > 1:
            index = len(headers) - 1
            row = {}
            for field in range(index):
                if field < 1:
                    continue
                else:
                    row[headers[field]] = salt.utils.stringutils.to_num(comps[field])
            ret[row[key]] = row
        else:
            headers = comps
    return ret
997920
private function getCreateTable($data, $charset = 'utf8')
    {
    	$sql  = "CREATE TABLE `".$data['name']."` (\n";
    	
    	if (is_array($data['fields'])) foreach ($data['fields'] as $field) {
    	    $sql .= "    `".$field['name']."` ".$this->getFieldDef($field).",\n";
    	}
    	
    	if (is_array($data['keys'])) foreach ($data['keys'] as $key) 
    		$sql .= '    '.$this->getIndexDef($key).",\n";
    	
    	$sql = substr($sql, 0, -2)."\n)";
    	if (isset($data['engine'])) $sql .= ' ENGINE='.$data['engine'];
    	if ($charset) $sql .= ' DEFAULT CHARSET '.$charset;
    	$sql .= ";\n";
    	return $sql;
    }
516341
function(bindings) {
    return [
      'mysqldump',
      '-u',
      bindings.mysql_username,
      '-p' + bindings.mysql_password,
      '-h',
      bindings.mysql_host,
      '-P',
      bindings.mysql_port.toString(),
      '--no-autocommit',
      '--single-transaction',
      '--opt',
      '-Q',
      bindings.mysql_database
    ];
  }
172415
def _CheckDatabaseEncoding(cursor):
  """"""
  cur_character_set = _ReadVariable("character_set_database", cursor)
  if cur_character_set != CHARACTER_SET:
    raise EncodingEnforcementError(
        "Require MySQL character_set_database of {}, got {}."
        " To create your database, use: {}".format(CHARACTER_SET,
                                                   cur_character_set,
                                                   CREATE_DATABASE_QUERY))
800588
def parse_statements(queries_input, engine):
    

    queries = []
    query = ''
    sql_delimiter = ';'

    # Possible delimiters used in PostgreSQL functions
    postgres_func_delimiters = ['$$', '##']

    # Split input by lines
    lines = queries_input.strip().split('\n')

    for k, line in enumerate(lines):
        # Strip line
        line = line.strip()

        # Skip empty lines and comments
        if not line or line.startswith('--'):
            continue

        # Detect new SQL delimiter
        if engine == 'mysql' and line.upper().startswith('DELIMITER '):
            sql_delimiter = line.split()[1]
            continue
        elif engine == 'postgresql' and [delimiter for delimiter in postgres_func_delimiters if 'AS ' + delimiter in line.upper()]:
            sql_delimiter = line.split()[-1]

            # Ensure that we leave 'AS [DELIMITER]'
            query += line + '\n'

            continue

        # Statement is not finished
        if sql_delimiter not in line and k != len(lines) - 1:
            # Append line
            query += line + '\n'
        else:  # Statement is finished
            # Replace non default delimiter
            if sql_delimiter != ';' and engine == 'mysql' and line.endswith(sql_delimiter):
                line = line.replace(sql_delimiter, ';')

            queries.append(query + line)
            query = ''

    return queries
674186
def decode_mysql_literal(text):
    
    if MYSQL_NULL_PATTERN.match(text):
        return None

    if MYSQL_BOOLEAN_PATTERN.match(text):
        return text.lower() == "true"

    if MYSQL_FLOAT_PATTERN.match(text):
        return float(text)

    if MYSQL_INT_PATTERN.match(text):
        return int(text)

    if MYSQL_STRING_PATTERN.match(text):
        return decode_mysql_string_literal(text)

    raise ValueError("Unable to decode given value: %r" % (text,))
842751
private function listOfMySQLqueryLanguageType($qType)
    {
        $keyForReturn = 'Type ' . $qType . ' stands for';
        $vMap         = ['DCL', 'DDL', 'DML', 'DQL', 'DTL'];
        if (in_array($qType, $vMap)) {
            $valForReturn = $this->readTypeFromJsonFile('MySQLiLanguageTypes')[$qType];
            return [$keyForReturn => $valForReturn[0] . ' (' . $valForReturn[1] . ')'];
        }
        return [$keyForReturn => 'unknown'];
    }
65409
public function encoding() {
		$db = $this->_getConnection();
		$config = $db->config();
		$database = $config['database'];
		$prefix = ''; //$config['prefix'];
		$encoding = 'utf8mb4';
		$collate = 'utf8mb4_unicode_ci';

		try {
			$script = "ALTER DATABASE $database CHARACTER SET $encoding COLLATE $collate;";
			if (!$this->params['dry-run']) {
				$db->query($script);
			} else {
				$this->out($script);
			}
		} catch (Exception $e) {
			$this->err('Could not alter database: ' . $e->getMessage() . ' - Skipping.');
		}

		$script = <<<SQL
SELECT  CONCAT('ALTER TABLE `', table_name, '` CONVERT TO CHARACTER SET $encoding COLLATE $collate;') AS statement
FROM    information_schema.tables AS tb
WHERE   table_schema = '$database'
AND     table_name LIKE '$prefix%'
AND     `TABLE_TYPE` = 'BASE TABLE';
SQL;
		/** @var \Cake\Database\Statement\StatementDecorator $res */
		$res = $db->query($script);
		if (!$res) {
			$this->abort('Nothing to do...');
		}

		$script = [];
		foreach ($res as $r) {
			$script[] = $r['statement'];
		}

		if (!$this->param('dry-run')) {
			$continue = $this->in(count($res) . ' tables will be altered.', ['Y', 'N'], 'N');
			if (strtoupper($continue) !== 'Y') {
				$this->abort('Aborted!');
			}
		}

		foreach ($script as $row) {
			preg_match('/`(.+)`/', $row, $matches);
			$table = $matches[1];
			$sql = "ALTER TABLE `$table` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;";

			if ($this->params['interactive']) {
				$in = $this->in('Fix table ' . $table . '?', ['y', 'n'], 'y');
				if ($in !== 'y') {
					$this->out(' - skipping ' . $table);
					continue;
				}
			}

			if (!$this->params['dry-run']) {
				$this->out(' - fixing table ' . $table, 1, Shell::VERBOSE);
				$db->query($row);
				$db->query($sql);
			} else {
				$this->out($row);
				$this->out($sql);
			}
		}
		$this->out('Done :)');
	}
223330
def parse_config(self):
        """"""
        config = config_get()
        mysql_config = {}
        if 'max-connections' in config:
            mysql_config['max_connections'] = config['max-connections']

        if 'wait-timeout' in config:
            mysql_config['wait_timeout'] = config['wait-timeout']

        if 'innodb-flush-log-at-trx-commit' in config:
            mysql_config['innodb_flush_log_at_trx_commit'] = \
                config['innodb-flush-log-at-trx-commit']
        elif 'tuning-level' in config:
            mysql_config['innodb_flush_log_at_trx_commit'] = \
                self.INNODB_FLUSH_CONFIG_VALUES.get(config['tuning-level'], 1)

        if ('innodb-change-buffering' in config and
                config['innodb-change-buffering'] in self.INNODB_VALID_BUFFERING_VALUES):
            mysql_config['innodb_change_buffering'] = config['innodb-change-buffering']

        if 'innodb-io-capacity' in config:
            mysql_config['innodb_io_capacity'] = config['innodb-io-capacity']

        # Set a sane default key_buffer size
        mysql_config['key_buffer'] = self.human_to_bytes('32M')
        total_memory = self.human_to_bytes(self.get_mem_total())

        dataset_bytes = config.get('dataset-size', None)
        innodb_buffer_pool_size = config.get('innodb-buffer-pool-size', None)

        if innodb_buffer_pool_size:
            innodb_buffer_pool_size = self.human_to_bytes(
                innodb_buffer_pool_size)
        elif dataset_bytes:
            log("Option 'dataset-size' has been deprecated, please use"
                "innodb_buffer_pool_size option instead", level="WARN")
            innodb_buffer_pool_size = self.human_to_bytes(
                dataset_bytes)
        else:
            # NOTE(jamespage): pick the smallest of 50% of RAM or 512MB
            #                  to ensure that deployments in containers
            #                  without constraints don't try to consume
            #                  silly amounts of memory.
            innodb_buffer_pool_size = min(
                int(total_memory * self.DEFAULT_INNODB_BUFFER_FACTOR),
                self.DEFAULT_INNODB_BUFFER_SIZE_MAX
            )

        if innodb_buffer_pool_size > total_memory:
            log("innodb_buffer_pool_size; {} is greater than system available memory:{}".format(
                innodb_buffer_pool_size,
                total_memory), level='WARN')

        mysql_config['innodb_buffer_pool_size'] = innodb_buffer_pool_size
        return mysql_config
765952
protected function _mysql()
	{
		$this->_msg( 'Changing typeid to not allow NULL values', 0 );
		$this->_status( '' );

		foreach ( $this->_mysql as $table => $stmt ) {
			$this->_msg( sprintf ( 'Checking table "%1$s": ', $table ), 1 );

			if ( $this->_schema->tableExists( $table ) === true
				&& $this->_schema->columnExists( $table, 'typeid' ) === true
				&& $this->_schema->getColumnDetails( $table, 'typeid' )->isNullable() === true )
			{
				$this->_executeList( $stmt );
				$this->_status( 'migrated' );
			} else {
				$this->_status( 'OK' );
			}
		}
	}
645394
def sqlalchemy_escape(val, escape_char, special_chars):
    
    if sys.version_info[:2] >= (3, 0):
        assert isinstance(val, str)
    else:
        assert isinstance(val, basestring)
    result = []
    for c in val:
        if c in special_chars + escape_char:
            result.extend(escape_char + c)
        else:
            result.extend(c)
    return ''.join(result)
145269
private String exportToSql() throws SQLException {

        StringBuilder sql = new StringBuilder();
        sql.append("--");
        sql.append("\n-- Generated by mysql-backup4j");
        sql.append("\n-- https://github.com/SeunMatt/mysql-backup4j");
        sql.append("\n-- Date: ").append(new SimpleDateFormat("d-M-Y H:m:s").format(new Date()));
        sql.append("\n--");

        //these declarations are extracted from HeidiSQL
        sql.append("\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;")
                .append("\n/*!40101 SET NAMES utf8 */;")
                .append("\n/*!50503 SET NAMES utf8mb4 */;")
                .append("\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;")
                .append("\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;");


        //get the tables that are in the database
        List<String> tables = MysqlBaseService.getAllTables(database, stmt);

        //for every table, get the table creation and data
        // insert statement
        for (String s: tables) {
            try {
                sql.append(getTableInsertStatement(s.trim()));
                sql.append(getDataInsertStatement(s.trim()));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        sql.append("\n/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;")
                .append("\n/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;")
                .append("\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;");

        this.generatedSql = sql.toString();
        return sql.toString();
    }
913479
def decode_sql(self, sql):
        
        # JSON is defined as using "unicode", we'll go a step further and
        # mandate utf-8 (though for the base64 part, it doesn't really matter!)
        base64_sql_bytes = to_unicode(sql).encode('utf-8')
        # in python3.x you can pass `validate=True` to b64decode to get this
        # behavior.
        if not re.match(b'^[A-Za-z0-9+/]*={0,2}$', base64_sql_bytes):
            self.raise_invalid_base64(sql)

        try:
            sql_bytes = base64.b64decode(base64_sql_bytes)
        except ValueError:
            self.raise_invalid_base64(sql)

        return sql_bytes.decode('utf-8')
718382
def compile_select(self, query):
        
        sql = super(MySqlQueryGrammar, self).compile_select(query)

        if query.unions:
            sql = '(%s) %s' % (sql, self._compile_unions(query))

        return sql
1008293
static int mysqlToJavaType(int type, final int meta, boolean isBinary) {
        int javaType;

        if (type == LogEvent.MYSQL_TYPE_STRING) {
            if (meta >= 256) {
                int byte0 = meta >> 8;
                if ((byte0 & 0x30) != 0x30) {
                    /* a long CHAR() field: see #37426 */
                    type = byte0 | 0x30;
                } else {
                    switch (byte0) {
                        case LogEvent.MYSQL_TYPE_SET:
                        case LogEvent.MYSQL_TYPE_ENUM:
                        case LogEvent.MYSQL_TYPE_STRING:
                            type = byte0;
                    }
                }
            }
        }

        switch (type) {
            case LogEvent.MYSQL_TYPE_LONG:
                javaType = Types.INTEGER;
                break;

            case LogEvent.MYSQL_TYPE_TINY:
                javaType = Types.TINYINT;
                break;

            case LogEvent.MYSQL_TYPE_SHORT:
                javaType = Types.SMALLINT;
                break;

            case LogEvent.MYSQL_TYPE_INT24:
                javaType = Types.INTEGER;
                break;

            case LogEvent.MYSQL_TYPE_LONGLONG:
                javaType = Types.BIGINT;
                break;

            case LogEvent.MYSQL_TYPE_DECIMAL:
                javaType = Types.DECIMAL;
                break;

            case LogEvent.MYSQL_TYPE_NEWDECIMAL:
                javaType = Types.DECIMAL;
                break;

            case LogEvent.MYSQL_TYPE_FLOAT:
                javaType = Types.REAL; // Types.FLOAT;
                break;

            case LogEvent.MYSQL_TYPE_DOUBLE:
                javaType = Types.DOUBLE;
                break;

            case LogEvent.MYSQL_TYPE_BIT:
                javaType = Types.BIT;
                break;

            case LogEvent.MYSQL_TYPE_TIMESTAMP:
            case LogEvent.MYSQL_TYPE_DATETIME:
            case LogEvent.MYSQL_TYPE_TIMESTAMP2:
            case LogEvent.MYSQL_TYPE_DATETIME2:
                javaType = Types.TIMESTAMP;
                break;

            case LogEvent.MYSQL_TYPE_TIME:
            case LogEvent.MYSQL_TYPE_TIME2:
                javaType = Types.TIME;
                break;

            case LogEvent.MYSQL_TYPE_NEWDATE:
            case LogEvent.MYSQL_TYPE_DATE:
                javaType = Types.DATE;
                break;

            case LogEvent.MYSQL_TYPE_YEAR:
                javaType = Types.VARCHAR;
                break;

            case LogEvent.MYSQL_TYPE_ENUM:
                javaType = Types.INTEGER;
                break;

            case LogEvent.MYSQL_TYPE_SET:
                javaType = Types.BINARY;
                break;

            case LogEvent.MYSQL_TYPE_TINY_BLOB:
            case LogEvent.MYSQL_TYPE_MEDIUM_BLOB:
            case LogEvent.MYSQL_TYPE_LONG_BLOB:
            case LogEvent.MYSQL_TYPE_BLOB:
                if (meta == 1) {
                    javaType = Types.VARBINARY;
                } else {
                    javaType = Types.LONGVARBINARY;
                }
                break;

            case LogEvent.MYSQL_TYPE_VARCHAR:
            case LogEvent.MYSQL_TYPE_VAR_STRING:
                if (isBinary) {
                    // varbinary在binlog中为var_string类型
                    javaType = Types.VARBINARY;
                } else {
                    javaType = Types.VARCHAR;
                }
                break;

            case LogEvent.MYSQL_TYPE_STRING:
                if (isBinary) {
                    // binary在binlog中为string类型
                    javaType = Types.BINARY;
                } else {
                    javaType = Types.CHAR;
                }
                break;

            case LogEvent.MYSQL_TYPE_GEOMETRY:
                javaType = Types.BINARY;
                break;

            // case LogEvent.MYSQL_TYPE_BINARY:
            // javaType = Types.BINARY;
            // break;
            //
            // case LogEvent.MYSQL_TYPE_VARBINARY:
            // javaType = Types.VARBINARY;
            // break;

            default:
                javaType = Types.OTHER;
        }

        return javaType;
    }
1254883
def _parse(self, e):
        """"""

        # MySQL
        matches = re.search(r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$", str(e))
        if matches:
            return matches.group(1)

        # PostgreSQL
        matches = re.search(r"^\(psycopg2\.OperationalError\) (.+)$", str(e))
        if matches:
            return matches.group(1)

        # SQLite
        matches = re.search(r"^\(sqlite3\.OperationalError\) (.+)$", str(e))
        if matches:
            return matches.group(1)

        # Default
        return str(e)