/*
Get the straight mysqldump command using pantheon connection info
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
    ];
  }
404186
def _get_serv(ret=None, commit=False):
    '''
    
    '''
    _options = _get_options(ret)

    connect = True
    if __context__ and 'mysql_returner_conn' in __context__:
        try:
            log.debug('Trying to reuse MySQL connection pool')
            conn = __context__['mysql_returner_conn']
            conn.ping()
            connect = False
        except OperationalError as exc:
            log.debug('OperationalError on ping: %s', exc)

    if connect:
        log.debug('Generating new MySQL connection pool')
        try:
            # An empty ssl_options dictionary passed to MySQLdb.connect will
            # effectively connect w/o SSL.
            ssl_options = {}
            if _options.get('ssl_ca'):
                ssl_options['ca'] = _options.get('ssl_ca')
            if _options.get('ssl_cert'):
                ssl_options['cert'] = _options.get('ssl_cert')
            if _options.get('ssl_key'):
                ssl_options['key'] = _options.get('ssl_key')
            conn = MySQLdb.connect(host=_options.get('host'),
                                   user=_options.get('user'),
                                   passwd=_options.get('pass'),
                                   db=_options.get('db'),
                                   port=_options.get('port'),
                                   ssl=ssl_options)

            try:
                __context__['mysql_returner_conn'] = conn
            except TypeError:
                pass
        except OperationalError as exc:
            raise salt.exceptions.SaltMasterError('MySQL returner could not connect to database: {exc}'.format(exc=exc))

    cursor = conn.cursor()

    try:
        yield cursor
    except MySQLdb.DatabaseError as err:
        error = err.args
        sys.stderr.write(six.text_type(error))
        cursor.execute("ROLLBACK")
        raise err
    else:
        if commit:
            cursor.execute("COMMIT")
        else:
            cursor.execute("ROLLBACK")
624171
public function getDumpCommand(string $dumpFile, string $temporaryCredentialsFile): string
    {
        $quote = $this->determineQuote();

        $command = [
            "{$quote}{$this->dumpBinaryPath}mysqldump{$quote}",
            "--defaults-extra-file=\"{$temporaryCredentialsFile}\"",
        ];

        if (! $this->createTables) {
            $command[] = '--no-create-info';
        }

        if ($this->skipComments) {
            $command[] = '--skip-comments';
        }

        $command[] = $this->useExtendedInserts ? '--extended-insert' : '--skip-extended-insert';

        if ($this->useSingleTransaction) {
            $command[] = '--single-transaction';
        }

        if ($this->skipLockTables) {
            $command[] = '--skip-lock-tables';
        }

        if ($this->useQuick) {
            $command[] = '--quick';
        }

        if ($this->socket !== '') {
            $command[] = "--socket={$this->socket}";
        }

        foreach ($this->excludeTables as $tableName) {
            $command[] = "--ignore-table={$this->dbName}.{$tableName}";
        }

        if (! empty($this->defaultCharacterSet)) {
            $command[] = '--default-character-set='.$this->defaultCharacterSet;
        }

        foreach ($this->extraOptions as $extraOption) {
            $command[] = $extraOption;
        }

        if ($this->setGtidPurged !== 'AUTO') {
            $command[] = '--set-gtid-purged='.$this->setGtidPurged;
        }

        if (! $this->dbNameWasSetAsExtraOption) {
            $command[] = $this->dbName;
        }

        if (! empty($this->includeTables)) {
            $includeTables = implode(' ', $this->includeTables);
            $command[] = "--tables {$includeTables}";
        }

        return $this->echoToFile(implode(' ', $command), $dumpFile);
    }
975364
public function dump()
	{
		$pdo = $this->pdo();

		$sql = '';

		foreach ($this->list_tables() as $table)
		{
			$query = $pdo->query("SELECT * FROM `{$table}`");

			while ($row = $query->fetch(\PDO::FETCH_NUM)) 
			{
				$values = array();

				foreach ($row as $column) 
				{
					$values[] = is_null($column) ? 'NULL' : $pdo->quote($column);
				}

				$sql .= "INSERT INTO `{$table}` VALUES (".join(',', $values). ");\n";
			}
		}

		return $sql;
	}
52899
def get_mysql_credentials(cfg_file):
    """"""

    try:
        parser = ConfigParser.ConfigParser()
        cfg_fp = open(cfg_file)
        parser.readfp(cfg_fp)
        cfg_fp.close()
    except ConfigParser.NoOptionError:
        cfg_fp.close()
        print('Failed to find mysql connections credentials.')
        sys.exit(1)
    except IOError:
        print('ERROR: Cannot open %s.', cfg_file)
        sys.exit(1)

    value = parser.get('dfa_mysql', 'connection')

    try:
        # Find location of pattern in connection parameter as shown below:
        # http://username:password@host/databasename?characterset=encoding'
        sobj = re.search(r"(://).*(@).*(/).*(\?)", value)

        # The list parameter contains:
        # indices[0], is the index of '://'
        # indices[1], is the index of '@'
        # indices[2], is the index of '/'
        # indices[3], is the index of '?'
        indices = [sobj.start(1), sobj.start(2), sobj.start(3), sobj.start(4)]

        # Get the credentials
        cred = value[indices[0] + 3:indices[1]].split(':')

        # Get the host name
        host = value[indices[1] + 1:indices[2]]

        # Get the database name
        db_name = value[indices[2] + 1:indices[3]]

        # Get the character encoding
        charset = value[indices[3] + 1:].split('=')[1]

        return cred[0], cred[1], host, db_name, charset
    except (ValueError, IndexError, AttributeError):
        print('Failed to find mysql connections credentials.')
        sys.exit(1)
866331
def version(**connection_args):
    '''
    
    '''
    dbc = _connect(**connection_args)
    if dbc is None:
        return ''
    cur = dbc.cursor()
    qry = 'SELECT VERSION()'
    try:
        _execute(cur, qry)
    except MySQLdb.OperationalError as exc:
        err = 'MySQL Error {0}: {1}'.format(*exc.args)
        __context__['mysql.error'] = err
        log.error(err)
        return ''

    try:
        return salt.utils.data.decode(cur.fetchone()[0])
    except IndexError:
        return ''
242235
public function getDbConnectionCmd()
    {
        $dbParams = $this->getDbConnectionParams();
        
        $dbConnectionCmd = 'mysql -u ' . $dbParams['user']
                         . ' -h ' . $dbParams['host']
                         . ' -P ' . $dbParams['port'];
        
        if (strlen($dbParams['password']) > 0) {
            $dbConnectionCmd .= ' -p"' . $dbParams['password'] . '"';
        }
        
        return $dbConnectionCmd;
    }
16353
def get_output(self):
        '''
        
        '''
        if self.is_hostname:
            # short circuit for hostame with internal method
            return determine_hostname()

        # all commands should timeout after a long interval so the client does not hang
        # prepend native nix 'timeout' implementation
        timeout_command = 'timeout -s KILL %s %s' % (
            self.config.cmd_timeout, self.command)

        # ensure consistent locale for collected command output
        cmd_env = {'LC_ALL': 'C',
                   'PATH': '/sbin:/bin:/usr/sbin:/usr/bin',
                   'PYTHONPATH': os.getenv('PYTHONPATH')}
        args = shlex.split(timeout_command)

        # never execute this stuff
        if set.intersection(set(args), constants.command_blacklist):
            raise RuntimeError("Command Blacklist: " + self.command)

        try:
            logger.debug('Executing: %s', args)
            proc0 = Popen(args, shell=False, stdout=PIPE, stderr=STDOUT,
                          bufsize=-1, env=cmd_env, close_fds=True)
        except OSError as err:
            if err.errno == errno.ENOENT:
                logger.debug('Command %s not found', self.command)
                return
            else:
                raise err

        dirty = False

        cmd = "sed -rf " + constants.default_sed_file
        sedcmd = Popen(shlex.split(cmd),
                       stdin=proc0.stdout,
                       stdout=PIPE)
        proc0.stdout.close()
        proc0 = sedcmd

        if self.exclude is not None:
            exclude_file = NamedTemporaryFile()
            exclude_file.write("\n".join(self.exclude).encode('utf-8'))
            exclude_file.flush()
            cmd = "grep -F -v -f %s" % exclude_file.name
            proc1 = Popen(shlex.split(cmd),
                          stdin=proc0.stdout,
                          stdout=PIPE)
            proc0.stdout.close()
            stderr = None
            if self.pattern is None or len(self.pattern) == 0:
                stdout, stderr = proc1.communicate()

            # always log return codes for debug
            logger.debug('Proc1 Status: %s', proc1.returncode)
            logger.debug('Proc1 stderr: %s', stderr)
            proc0 = proc1

            dirty = True

        if self.pattern is not None and len(self.pattern):
            pattern_file = NamedTemporaryFile()
            pattern_file.write("\n".join(self.pattern).encode('utf-8'))
            pattern_file.flush()
            cmd = "grep -F -f %s" % pattern_file.name
            proc2 = Popen(shlex.split(cmd),
                          stdin=proc0.stdout,
                          stdout=PIPE)
            proc0.stdout.close()
            stdout, stderr = proc2.communicate()

            # always log return codes for debug
            logger.debug('Proc2 Status: %s', proc2.returncode)
            logger.debug('Proc2 stderr: %s', stderr)
            proc0 = proc2

            dirty = True

        if not dirty:
            stdout, stderr = proc0.communicate()

        # Required hack while we still pass shell=True to Popen; a Popen
        # call with shell=False for a non-existant binary will raise OSError.
        if proc0.returncode == 126 or proc0.returncode == 127:
            stdout = "Could not find cmd: %s", self.command

        logger.debug("Proc0 Status: %s", proc0.returncode)
        logger.debug("Proc0 stderr: %s", stderr)
        return stdout.decode('utf-8', 'ignore').strip()
55341
private function command($database)
    {
        $mysqldumpPath = $this->config->get('backup::config')['BACKUP_MYSQLDUMP_PATH'];
        $mysqldumpOptions = ' \
            --quote-names \
            --quick \
            --add-drop-table \
            --add-locks \
            --allow-keywords \
            --disable-keys \
            --extended-insert \
            --single-transaction \
            --create-options \
            --comments \
            --net_buffer_length=16384';
        $host = $this->config->get('backup::config')['BACKUP_MYSQL_HOST'];
        $user = $this->config->get('backup::config')['BACKUP_MYSQL_USER'];
        $password = $this->config->get('backup::config')['BACKUP_MYSQL_PASSWORD'];
        $folder = storage_path($this->config->get('backup::config')['BACKUP_STORAGE_PATH']);
        $file = $database.'-backup.sql.gz';

        return $mysqldumpPath.$mysqldumpOptions.' --host='.$host.' --user='.$user.' --password='.$password.' '.
            $database.' | gzip > '.$folder.$file;
    }
754213
def flushdb(host=None, port=None, db=None, password=None):
    '''
    
    '''
    server = _connect(host, port, db, password)
    return server.flushdb()
1105715
function exec($cmds,$args=NULL,$ttl=0,$log=TRUE,$stamp=FALSE) {
		$tag='';
		if (is_array($ttl))
			list($ttl,$tag)=$ttl;
		$auto=FALSE;
		if (is_null($args))
			$args=[];
		elseif (is_scalar($args))
			$args=[1=>$args];
		if (is_array($cmds)) {
			if (count($args)<($count=count($cmds)))
				// Apply arguments to SQL commands
				$args=array_fill(0,$count,$args);
			if (!$this->trans) {
				$this->begin();
				$auto=TRUE;
			}
		}
		else {
			$count=1;
			$cmds=[$cmds];
			$args=[$args];
		}
		if ($this->log===FALSE)
			$log=FALSE;
		$fw=\Base::instance();
		$cache=\Cache::instance();
		$result=FALSE;
		for ($i=0;$i<$count;$i++) {
			$cmd=$cmds[$i];
			$arg=$args[$i];
			// ensure 1-based arguments
			if (array_key_exists(0,$arg)) {
				array_unshift($arg,'');
				unset($arg[0]);
			}
			if (!preg_replace('/(^\s+|[\s;]+$)/','',$cmd))
				continue;
			$now=microtime(TRUE);
			$keys=$vals=[];
			if ($fw->CACHE && $ttl && ($cached=$cache->exists(
				$hash=$fw->hash($this->dsn.$cmd.
				$fw->stringify($arg)).($tag?'.'.$tag:'').'.sql',$result)) &&
				$cached[0]+$ttl>microtime(TRUE)) {
				foreach ($arg as $key=>$val) {
					$vals[]=$fw->stringify(is_array($val)?$val[0]:$val);
					$keys[]='/'.preg_quote(is_numeric($key)?chr(0).'?':$key).
						'/';
				}
				if ($log)
					$this->log.=($stamp?(date('r').' '):'').'('.
						sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
						'[CACHED] '.
						preg_replace($keys,$vals,
							str_replace('?',chr(0).'?',$cmd),1).PHP_EOL;
			}
			elseif (is_object($query=$this->pdo->prepare($cmd))) {
				foreach ($arg as $key=>$val) {
					if (is_array($val)) {
						// User-specified data type
						$query->bindvalue($key,$val[0],
							$val[1]==self::PARAM_FLOAT?\PDO::PARAM_STR:$val[1]);
						$vals[]=$fw->stringify($this->value($val[1],$val[0]));
					}
					else {
						// Convert to PDO data type
						$query->bindvalue($key,$val,
							($type=$this->type($val))==self::PARAM_FLOAT?
								\PDO::PARAM_STR:$type);
						$vals[]=$fw->stringify($this->value($type,$val));
					}
					$keys[]='/'.preg_quote(is_numeric($key)?chr(0).'?':$key).
						'/';
				}
				if ($log)
					$this->log.=($stamp?(date('r').' '):'').'(-0ms) '.
						preg_replace($keys,$vals,
							str_replace('?',chr(0).'?',$cmd),1).PHP_EOL;
				$query->execute();
				if ($log)
					$this->log=str_replace('(-0ms)',
						'('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms)',
						$this->log);
				if (($error=$query->errorinfo()) && $error[0]!=\PDO::ERR_NONE) {
					// Statement-level error occurred
					if ($this->trans)
						$this->rollback();
					user_error('PDOStatement: '.$error[2],E_USER_ERROR);
				}
				if (preg_match('/(?:^[\s\(]*'.
					'(?:WITH|EXPLAIN|SELECT|PRAGMA|SHOW)|RETURNING)\b/is',$cmd) ||
					(preg_match('/^\s*(?:CALL|EXEC)\b/is',$cmd) &&
						$query->columnCount())) {
					$result=$query->fetchall(\PDO::FETCH_ASSOC);
					// Work around SQLite quote bug
					if (preg_match('/sqlite2?/',$this->engine))
						foreach ($result as $pos=>$rec) {
							unset($result[$pos]);
							$result[$pos]=[];
							foreach ($rec as $key=>$val)
								$result[$pos][trim($key,'\'"[]`')]=$val;
						}
					$this->rows=count($result);
					if ($fw->CACHE && $ttl)
						// Save to cache backend
						$cache->set($hash,$result,$ttl);
				}
				else
					$this->rows=$result=$query->rowcount();
				$query->closecursor();
				unset($query);
			}
			elseif (($error=$this->errorinfo()) && $error[0]!=\PDO::ERR_NONE) {
				// PDO-level error occurred
				if ($this->trans)
					$this->rollback();
				user_error('PDO: '.$error[2],E_USER_ERROR);
			}

		}
		if ($this->trans && $auto)
			$this->commit();
		return $result;
	}
330534
def dump_commands(self, commands):
        """"""
        # Get base directory
        directory = os.path.join(os.path.dirname(self.sql_script), 'fails')

        # Get file name to be used for folder name
        fname = os.path.basename(self.sql_script.rsplit('.')[0])

        return dump_commands(commands, directory, fname)
754494
public static function database()
    {
        $path = static::$root.'Database/';

        //--------------------------------------------------------
        // Calling drivers
        //--------------------------------------------------------

        $files = ['Driver', 'MysqlDriver'];
        $folder = $path.'Drivers'.'/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling exporters
        //--------------------------------------------------------

        $files = ['Exporter', 'Importer'];
        $folder = $path.'InOut/Mysql/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling Connectors
        //--------------------------------------------------------

        $files = ['MysqlConnector'];
        $folder = $path.'Connectors'.'/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling Exceptions
        //--------------------------------------------------------

        $files = ['ConnectorException', 'QueryException', 'SeedersEmptyException', 'DatabaseArgumentsException', 'DatabaseConnectionException', 'SchemaTableExistsException', 'SchemaTableNotExistException'];
        $folder = $path.'Exceptions'.'/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling Schemas
        //--------------------------------------------------------

        $files = ['Schema', 'MysqlSchema'];
        $folder = $path.'Schemas'.'/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling Database parts
        //--------------------------------------------------------

        $files = ['Migration', 'Seeder', 'DBTable', 'Query', 'Row', 'Database'];
        $folder = $path;

        self::call($files, $folder);
    }
617784
def backup_db(release=None, limit=5):
    

    assert "mysql_user" in env, "Missing mysqL_user in env"
    assert "mysql_password" in env, "Missing mysql_password in env"
    assert "mysql_host" in env, "Missing mysql_host in env"
    assert "mysql_db" in env, "Missing mysql_db in env"

    if not release:
        release = paths.get_current_release_name()

    max_versions = limit+1

    if not release:
        return

    env.run("mkdir -p %s" % paths.get_backup_path("mysql"))

    backup_file = "mysql/%s.sql.gz" % release
    backup_path = paths.get_backup_path(backup_file)

    env.run("mysqldump -u %s -p%s -h %s %s | gzip -c > %s" %
            (env.mysql_user, env.mysql_password, env.mysql_host, env.mysql_db,
             backup_path))

    # Remove older releases
    env.run("ls -dt %s/* | tail -n +%s | xargs rm -rf" % (
        paths.get_backup_path("mysql"),
        max_versions)
    )
715617
def get_mysql_args(db_config):
    
    db = db_config['NAME']

    mapping = [('--user={0}', db_config.get('USER')),
               ('--password={0}', db_config.get('PASSWORD')),
               ('--host={0}', db_config.get('HOST')),
               ('--port={0}', db_config.get('PORT'))]
    args = apply_arg_values(mapping)
    args.append(db)

    return args
802385
protected function dumpData($outputPath)
    {
        $tables = Arr::get($this->installConfig, 'dataTables', []);

        /**
         *  Do not attempt to create an empty data install file if no tables are to be exported.
         *  Otherwise all tables will be exported.
         */
        if (! count($tables)) {
            return;
        }

        $command = sprintf(
            'mysqldump %s %s -u %s -p%s --no-create-info > %s',
            escapeshellarg($this->dbConfig['database']),
            implode(' ', $tables),
            escapeshellarg($this->dbConfig['username']),
            escapeshellarg($this->dbConfig['password']),
            escapeshellarg($outputPath.'/'.self::DATA_FILE)
        );

        return shell_exec($command);
    }
304428
function(site, env) {

    // Get the dump command
    return sqlDumpCmd(site, env)

    // Add the pipe and return the command
    .then(function(cmd) {
      cmd.push('|');
      cmd.push('mysql');
      cmd.push('-A');
      cmd.push('-u');
      cmd.push('$DB_USER');
      cmd.push('-p$DB_PASSWORD');
      cmd.push('-h');
      cmd.push('$DB_HOST');
      cmd.push('$DB_NAME');
      return run('usermap', cmd, terminusContainer());
    });

  }