Prepare a database name and a file dump name for mysqldump command
979430
protected function prepareFileName()
    {
        if ($this->params['all_databases']) {
            $this->database = '--all-databases';
            $this->fileName = 'all-databases.sql';
        } else {
            $this->database = $this->params['database'];
            $this->fileName = $this->database . '.sql';
        }
    }
976664
def cli(
    paths,
    dbname,
    separator,
    quoting,
    skip_errors,
    replace_tables,
    table,
    extract_column,
    date,
    datetime,
    datetime_format,
    primary_key,
    fts,
    index,
    shape,
    filename_column,
    no_index_fks,
    no_fulltext_fks,
):
    
    # make plural for more readable code:
    extract_columns = extract_column
    del extract_column

    if extract_columns:
        click.echo("extract_columns={}".format(extract_columns))
    if dbname.endswith(".csv"):
        raise click.BadParameter("dbname must not end with .csv")
    if "." not in dbname:
        dbname += ".db"

    db_existed = os.path.exists(dbname)

    conn = sqlite3.connect(dbname)

    dataframes = []
    csvs = csvs_from_paths(paths)
    sql_type_overrides = None
    for name, path in csvs.items():
        try:
            df = load_csv(path, separator, skip_errors, quoting, shape)
            df.table_name = table or name
            if filename_column:
                df[filename_column] = name
                if shape:
                    shape += ",{}".format(filename_column)
            sql_type_overrides = apply_shape(df, shape)
            apply_dates_and_datetimes(df, date, datetime, datetime_format)
            dataframes.append(df)
        except LoadCsvError as e:
            click.echo("Could not load {}: {}".format(path, e), err=True)

    click.echo("Loaded {} dataframes".format(len(dataframes)))

    # Use extract_columns to build a column:(table,label) dictionary
    foreign_keys = {}
    for col in extract_columns:
        bits = col.split(":")
        if len(bits) == 3:
            foreign_keys[bits[0]] = (bits[1], bits[2])
        elif len(bits) == 2:
            foreign_keys[bits[0]] = (bits[1], "value")
        else:
            foreign_keys[bits[0]] = (bits[0], "value")

    # Now we have loaded the dataframes, we can refactor them
    created_tables = {}
    refactored = refactor_dataframes(
        conn, dataframes, foreign_keys, not no_fulltext_fks
    )
    for df in refactored:
        # This is a bit trickier because we need to
        # create the table with extra SQL for foreign keys
        if replace_tables and table_exists(conn, df.table_name):
            drop_table(conn, df.table_name)
        if table_exists(conn, df.table_name):
            df.to_sql(df.table_name, conn, if_exists="append", index=False)
        else:
            to_sql_with_foreign_keys(
                conn,
                df,
                df.table_name,
                foreign_keys,
                sql_type_overrides,
                primary_keys=primary_key,
                index_fks=not no_index_fks,
            )
            created_tables[df.table_name] = df
        if index:
            for index_defn in index:
                add_index(conn, df.table_name, index_defn)

    # Create FTS tables
    if fts:
        fts_version = best_fts_version()
        if not fts_version:
            conn.close()
            raise click.BadParameter(
                "Your SQLite version does not support any variant of FTS"
            )
        # Check that columns make sense
        for table, df in created_tables.items():
            for fts_column in fts:
                if fts_column not in df.columns:
                    raise click.BadParameter(
                        'FTS column "{}" does not exist'.format(fts_column)
                    )

        generate_and_populate_fts(conn, created_tables.keys(), fts, foreign_keys)

    conn.close()

    if db_existed:
        click.echo(
            "Added {} CSV file{} to {}".format(
                len(csvs), "" if len(csvs) == 1 else "s", dbname
            )
        )
    else:
        click.echo(
            "Created {} from {} CSV file{}".format(
                dbname, len(csvs), "" if len(csvs) == 1 else "s"
            )
        )
244469
public function Backup_Init()
    {
        $sql = "-- -----------------------------\n";
        $sql .= "-- Think MySQL Data Transfer \n";
        $sql .= "-- \n";
        $sql .= "-- Host     : " . $this->dbconfig['hostname'] . "\n";
        $sql .= "-- Port     : " . $this->dbconfig['hostport'] . "\n";
        $sql .= "-- Database : " . $this->dbconfig['database'] . "\n";
        $sql .= "-- \n";
        $sql .= "-- Part : #{$this->file['part']}\n";
        $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
        $sql .= "-- -----------------------------\n\n";
        $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
        return $this->write($sql);
    }
512974
public function restore(&$dump) {
        $this->_adjustDumpToEnvironment($dump);
        //$dump         = $this->_lowerCaseTableAndViewNames($dump);
        $this->_removeDefinerCalls($dump);
        $dbConfig       = $this->getDbConfigParams();
        $restoreFile    = $this->getRestoreFilePath();
        $restoreDir     = $this->getBackupDir();

        $executeFile    = new Garp_Shell_Command_CreateDatabase($dbConfig);
        $this->shellExec($executeFile);

        if (!$this->_validateDump($dump)) {
            throw new Exception("The fetched database seems invalid.");
        }

        $createRestoreDir = new Garp_Shell_Command_CreateDir($restoreDir);
        $this->shellExec($createRestoreDir);

        if ($this->store($restoreFile, $dump)) {
            $executeFile = new Garp_Shell_Command_ExecuteDatabaseDumpFile($dbConfig, $restoreFile);
            $this->shellExec($executeFile);

            $removeFile = new Garp_Shell_Command_RemoveFile($restoreFile);
            $this->shellExec($removeFile);
        }
    }
531418
def db_export(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit):
    """"""

    internal_backup(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit)
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());
    });

  }
892995
public function dumpDB($dumpName = 'test')
    {
        $tables = $this->getDbTables();

        if (empty($tables)) {
            $dbName = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('dbName');
            throw new Exception("no tables on '$dbName'' database");
        }

        $columns = $this->getTableColumns($tables);
        $data = $this->getTableData($tables);
        $checksum = $this->getTableChecksum($tables);

        $this->dbDump[$dumpName] = array('columns' => $columns, 'data' => $data, 'checksum' => $checksum);
    }
547897
private function getDumpFileHeader()
    {
        $header = '';
        if (!$this->dumpSettings['skip-comments']) {
            // Some info about software, source and time
            $header = "-- mysqldump-php https://github.com/ifsnop/mysqldump-php".PHP_EOL.
                    "--".PHP_EOL.
                    "-- Host: {$this->host}\tDatabase: {$this->dbName}".PHP_EOL.
                    "-- ------------------------------------------------------".PHP_EOL;

            if (!empty($this->version)) {
                $header .= "-- Server version \t".$this->version.PHP_EOL;
            }

            if (!$this->dumpSettings['skip-dump-date']) {
                $header .= "-- Date: ".date('r').PHP_EOL.PHP_EOL;
            }
        }
        return $header;
    }
718903
def pg_dump(db_name, backup_path):
    """"""

    logger.info("Dumping %s to %s", repr(db_name), repr(backup_path))
    return shell(
        'pg_dump "{db_name}" -U "{USER}" -h "{HOST}" '
        "--schema=public --file={backup_path}".format(
            db_name=db_name, backup_path=backup_path, **DB
        )
    )
626821
public function backupDb($filename, $tables = '*')
    {
        $data = [];

        // get all of the tables
        if ($tables == '*') {
            $tables = array();
            $result = $this->connection->prepare('SHOW TABLES');
            $result->execute();
            while ($row = $result->fetch(PDO::FETCH_NUM)) {
                $tables[] = $row[0];
            }
        } else {
            $tables = \is_array($tables) ? $tables : explode(',', $tables);
        }

        $data[] = "\n";
        $data[] = 'SET foreign_key_checks=0;';
        $data[] = "\n\n";

        foreach ($tables as $table) {
            if (!preg_match("/^[\w_\-]+$/", $table)) {
                Tlog::getInstance()->alert(
                    sprintf(
                        "Attempt to backup the db with this invalid table name: '%s'",
                        $table
                    )
                );

                continue;
            }

            $result = $this->execute('SELECT * FROM `' . $table . '`');

            $fieldCount = $result->columnCount();

            $data[] = 'DROP TABLE `' . $table . '`;';

            $resultStruct = $this->execute('SHOW CREATE TABLE `' . $table . '`');

            $rowStruct = $resultStruct->fetch(PDO::FETCH_NUM);

            $data[] = "\n\n";
            $data[] = $rowStruct[1];
            $data[] = ";\n\n";

            for ($i = 0; $i < $fieldCount; $i++) {
                while ($row = $result->fetch(PDO::FETCH_NUM)) {
                    $data[] = 'INSERT INTO `' . $table . '` VALUES(';
                    for ($j = 0; $j < $fieldCount; $j++) {
                        $row[$j] = addslashes($row[$j]);
                        $row[$j] = str_replace("\n", "\\n", $row[$j]);
                        if (isset($row[$j])) {
                            $data[] = '"' . $row[$j] . '"';
                        } else {
                            $data[] = '""';
                        }
                        if ($j < ($fieldCount - 1)) {
                            $data[] = ',';
                        }
                    }
                    $data[] = ");\n";
                }
            }
            $data[] = "\n\n\n";
        }

        $data[] = 'SET foreign_key_checks=1;';

        //save filename
        $this->writeFilename($filename, $data);
    }
455969
public function restoreDB($dumpName = 'test')
    {
        $this->setDumpName($dumpName);

        $data = $this->getDumpData();
        $tables = $this->getDbTables();

        foreach ($tables as $table) {
            if (!isset($data[$table])) {
                $this->dropTable($table);
            } else {
                $this->restoreTable($table);
            }
        }
        $this->setDumpName('test');
    }
839455
public function dump($dst) {
		$host = $this->config['host'];
		$user = $this->config['user'];
		$pwd = $this->config['password'];
		$db = $this->config['database'];

		\Asgard\File\FileSystem::mkdir(dirname($dst));
		$cmd = 'mysqldump --user='.$user.' --password='.$pwd.' --host='.$host.' '.$db.' > '.$dst;
		$process = proc_open($cmd,
			[
				0 => ["pipe", "r"],
				1 => ["pipe", "w"],
				2 => ["pipe", "w"],
			],
			$pipes
		);
		return proc_close($process) === 0;
	}
968197
def backUpDB() :
    """"""
    st = time.ctime().replace(' ', '_')
    fn = conf.pyGeno_RABA_DBFILE.replace('.db', '_%s-bck.db' % st)
    shutil.copy2(conf.pyGeno_RABA_DBFILE, fn)

    return fn
278101
def create_db(name, owner=None, encoding=u'UTF-8', template='template1',
              **kwargs):
    """"""

    flags = u''
    if encoding:
        flags = u'-E %s' % encoding
    if owner:
        flags = u'%s -O %s' % (flags, owner)
    if template and template != 'template1':
        flags = u'%s --template=%s' % (flags, template)
    sudo('createdb %s %s' % (flags, name), user='postgres', **kwargs)
430545
def dump2sqlite(records, output_file):
    """"""
    results_keys = list(records.results[0].keys())
    pad_data = []

    for key in REQUIRED_KEYS:
        if key not in results_keys:
            results_keys.append(key)
            pad_data.append("")

    conn = sqlite3.connect(os.path.expanduser(output_file), detect_types=sqlite3.PARSE_DECLTYPES)

    # in each row there needs to be data for every column
    # last column is current time
    pad_data.append(datetime.datetime.utcnow())

    to_db = [list(row.values()) + pad_data for row in records.results]

    cur = conn.cursor()
    cur.execute(
        "CREATE TABLE testcases ({},sqltime TIMESTAMP)".format(
            ",".join("{} TEXT".format(key) for key in results_keys)
        )
    )
    cur.executemany(
        "INSERT INTO testcases VALUES ({},?)".format(",".join(["?"] * len(results_keys))), to_db
    )

    if records.testrun:
        cur.execute("CREATE TABLE testrun (testrun TEXT)")
        cur.execute("INSERT INTO testrun VALUES (?)", (records.testrun,))

    conn.commit()
    conn.close()

    logger.info("Data written to '%s'", output_file)
87716
public function dbRestore($args){

        $path = '/app/db/';
        if(isset($args[0])){
            $path = $args[0];
        }//if

        $path = \App::path() . '/' . trim($path,'/') . '/';

        $fileName = \App::config('DB_DB');
        if(isset($args[1])){
            $fileName = $args[1];
        }//if

        $fileName = $path . $fileName . '.sql';

        if(!is_file($fileName)){
            echo "Backup `{$fileName}` does not exist, exiting." . PHP_EOL;
            exit;
        }//if

        $e = "mysql -u %1\$s -p'%2\$s' -h %3\$s %4\$s < %5\$s;";
        $e = sprintf($e,
            \App::config('DB_USER'),
            \App::config('DB_PASSWORD'),
            \App::config('DB_HOST'),
            \App::config('DB_DB'),
            $fileName
        );

        $error = exec($e);

        if(!$error){
            echo 'DB `' . \App::config('DB_DB') . "` successfully restored from `{$fileName}`";
        } else {
            echo 'Unable to restore! : ' . $error;
        }//el

        echo PHP_EOL;

    }
500491
def table_dump(self, table):
        """"""
        if not table: raise ValueError("no table")

        cmds = []
        logger.info('------- dumping table {}'.format(table))
        cmd = self._get_args(
            "pg_dump",
            "--table={}".format(table),
            #"--data-only",
            "--clean",
            "--no-owner",
            "--column-inserts",
        )
        cmds.append((cmd, {}))

        outfile_path = self._get_outfile_path(table)
        cmds.append(('gzip > "{}"'.format(outfile_path), {"shell": True}))

        #cmd += ' | {}'.format(' | '.join(pipes))
        #cmd += ' > {}'.format(outfile_path)

        self._run_cmds(cmds)
        logger.info('------- dumped table {}'.format(table))
        return True