Copy all database info to a given directory.
        Used primarily for testing; production users
        should just pull a backup db from ~/.blockstack-server/backups
        (or whatever the working directory is)
344340
def export_db(self, dirpath):
        
        if self.db is not None:
            self.db.commit()
            
        import virtualchain_hooks
        
        db_path = os.path.join(dirpath, os.path.basename(self.get_db_path()))
        snapshots_path = os.path.join(dirpath, os.path.basename(virtualchain.get_snapshots_filename(virtualchain_hooks, self.working_dir)))
        atlas_path = os.path.join(dirpath, 'atlas.db')
        subdomain_path = os.path.join(dirpath, 'subdomains.db')
        subdomain_queue_path = os.path.join(dirpath, 'subdomains.db.queue')

        src_atlas_path = os.path.join(self.working_dir, 'atlas.db')
        src_subdomain_path = os.path.join(self.working_dir, 'subdomains.db')
        src_subdomain_queue_path = os.path.join(self.working_dir, 'subdomains.db.queue')
        
        virtualchain.sqlite3_backup(self.get_db_path(), db_path)
        virtualchain.sqlite3_backup(virtualchain.get_snapshots_filename(virtualchain_hooks, self.working_dir), snapshots_path)

        if os.path.exists(src_atlas_path):
            virtualchain.sqlite3_backup(src_atlas_path, atlas_path)

        if os.path.exists(src_subdomain_path):
            virtualchain.sqlite3_backup(src_subdomain_path, subdomain_path)

        if os.path.exists(src_subdomain_queue_path):
            virtualchain.sqlite3_backup(src_subdomain_queue_path, subdomain_queue_path)
1100157
function db_dump(config, output_paths) {

        var cmd;

        grunt.file.mkdir(output_paths.dir);


        // 2) Compile MYSQL cmd via Lo-Dash template string
        var tpl_mysqldump = grunt.template.process(tpls.mysqldump, {
            data: {
                user: config.user,
                pass: config.pass,
                database: config.database,
                host: config.host
            }
        });


        // 3) Test whether MYSQL DB is local or whether requires remote access via SSH
        if (typeof config.ssh_host === "undefined") { // it's a local connection
            grunt.log.writeln("Creating DUMP of local database");
            cmd = tpl_mysqldump;

        } else { // it's a remote connection
            var tpl_ssh = grunt.template.process(tpls.ssh, {
                data: {
                    host: config.ssh_host
                }
            });
            grunt.log.writeln("Creating DUMP of remote database");

            cmd = tpl_ssh + " \\ " + tpl_mysqldump;
        }

        // Capture output...
        var output = shell.exec(cmd, {silent: true}).output;

        // Write output to file using native Grunt methods
        grunt.file.write( output_paths.file, output );

        grunt.log.oklns("Database DUMP succesfully exported to: " + output_paths.file);

    }
954404
def _copy_database_data_serverside(self, source, destination, tables):
        """"""
        for table in tqdm(tables, total=len(tables), desc='Copying table data (optimized)'):
            self.execute('INSERT INTO {0}.{1} SELECT * FROM {2}.{1}'.format(destination, wrap(table), source))
50366
public function digipolisDatabaseBackup($database = 'default', $opts = [
      'file-system-config|fsconf' => null,
      'database-config|dbconf' => null,
      'compression|c' => 'gzip',
      'destination|d' => null,
      'destination-type|dtype' => 'local',
    ])
    {
        if (is_callable([$this, 'readProperties'])) {
            $this->readProperties();
        }
        $destination = $opts['destination']
            ? $opts['destination']
            : realpath(getcwd()) . '/project.tar.gz';
        if (!$opts['file-system-config']) {
            $opts['file-system-config'] = [
                $opts['destination-type'] => [
                    'type' => ucfirst($opts['destination-type']),
                    'root' => realpath(dirname($destination)),
                ],
            ];
            $destination = basename($destination);
        }
        return $this->createDbTask('taskDatabaseBackup', $database, $opts)
            ->destination($destination, $opts['destination-type'])
            ->run();
    }
903449
def create_diamond_db(self):
        '''
        '''
        base = self.unaligned_sequence_database_path()
        cmd = "diamond makedb --in '%s' -d '%s'" % (self.unaligned_sequence_database_path(), base)
        extern.run(cmd)
        diamondb = '%s.dmnd' % base
        # Mostly this moves a file to it's current location because Create
        # follows this same logic, but there's a specially crafted
        # test/data/mcrA.gpkg which is slightly different.
        os.rename(diamondb, self.diamond_database_path())
        return diamondb
119733
protected File initRecoveryDb(String dbName) {
    Preconditions.checkNotNull(_recoveryPath,
      "recovery path should not be null if NM recovery is enabled");

    File recoveryFile = new File(_recoveryPath.toUri().getPath(), dbName);
    if (recoveryFile.exists()) {
      return recoveryFile;
    }

    // db doesn't exist in recovery path go check local dirs for it
    String[] localDirs = _conf.getTrimmedStrings("yarn.nodemanager.local-dirs");
    for (String dir : localDirs) {
      File f = new File(new Path(dir).toUri().getPath(), dbName);
      if (f.exists()) {
        // If the recovery path is set then either NM recovery is enabled or another recovery
        // DB has been initialized. If NM recovery is enabled and had set the recovery path
        // make sure to move all DBs to the recovery path from the old NM local dirs.
        // If another DB was initialized first just make sure all the DBs are in the same
        // location.
        Path newLoc = new Path(_recoveryPath, dbName);
        Path copyFrom = new Path(f.toURI());
        if (!newLoc.equals(copyFrom)) {
          logger.info("Moving " + copyFrom + " to: " + newLoc);
          try {
            // The move here needs to handle moving non-empty directories across NFS mounts
            FileSystem fs = FileSystem.getLocal(_conf);
            fs.rename(copyFrom, newLoc);
          } catch (Exception e) {
            // Fail to move recovery file to new path, just continue on with new DB location
            logger.error("Failed to move recovery file {} to the path {}",
              dbName, _recoveryPath.toString(), e);
          }
        }
        return new File(newLoc.toUri().getPath());
      }
    }

    return new File(_recoveryPath.toUri().getPath(), dbName);
  }
228189
function copydir(from, to, options, callback) {
  if (typeof options === 'function') {
    if(!callback) {
      callback = options;
      options = {};
    }
    options = {
      filter: options
    };
  }
  if(typeof callback !== 'function') {
    callback = function() {};
  }
  if(typeof options.cover === 'undefined') {
    options.cover = true;
  }
  options.filter = typeof options.filter === 'function' ? options.filter : function(state, filepath, filename) {
    return options.filter;
  };
  fs.lstat(from, function(err, stats) {
    if (err) {
      callback(err);
    } else {
      var statsname = stats.isDirectory() ? 'directory' :
        stats.isFile() ? 'file' :
        stats.isSymbolicLink() ? 'symbolicLink' :
        '';
      var valid = options.filter(statsname, from, path.dirname(from), path.basename(from));
      if (statsname === 'directory' || statsname === 'symbolicLink') {
        // Directory or SymbolicLink
        if(valid) {
          fs.stat(to, function(err) {
            if(err) {
              if(err.code === 'ENOENT') {
                fs.mkdir(to, function(err) {
                  if(err) {
                    callback(err);
                  } else {
                    options.debug && console.log('>> ' + to);
                    rewrite(to, options, stats, function(err) {
                      if(err) {
                        callback(err);
                      } else {
                        listDirectory(from, to, options, callback);
                      }
                    });
                  }
                });
              } else {
                callback(err);
              }
            } else {
              rewrite(to, options, stats, function(err) {
                if(err) {
                  callback(err);
                } else {
                  listDirectory(from, to, options, callback);
                }
              });
            }
          });
        } else {
          callback();
        }
      } else if(stats.isFile()) {
        // File
        if(valid) {
          if(options.cover) {
            writeFile(from, to, options, stats, callback);
          } else {
            fs.stat(to, function(err) {
              if(err) {
                if(err.code === 'ENOENT') {
                  writeFile(from, to, options, stats, callback);
                } else {
                  callback(err);
                }
              } else {
                callback();
              }
            });
          }
        } else {
          callback();
        }
      } else {
        callback(new Error('stats invalid: '+ from));
      }
    }
  });
}
803157
def copy_to(_, directory)
      # Delete the directory to make sure no pervious version remains
      FileUtils.rm_rf(directory) if directory.exist?

      # Create parent directory
      FileUtils.mkdir_p(directory.parent)

      # Create symlink
      FileUtils.ln_s(@dir.expand_path, directory)

      nil
    end
528458
def makeblastdb(self):
        
        # Iterate through the samples to set the bait file.
        for sample in self.runmetadata.samples:
            if sample.general.bestassemblyfile != 'NA':
                # Remove the file extension
                db = os.path.splitext(sample[self.analysistype].baitfile)[0]
                # Add '.nhr' for searching below
                nhr = '{}.nhr'.format(db)
                # Check for already existing database files
                if not os.path.isfile(str(nhr)):
                    # Create the databases
                    command = 'makeblastdb -in {} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {}'\
                        .format(sample[self.analysistype].baitfile, db)
                    out, err = run_subprocess(command)
                    write_to_logfile(command,
                                     command,
                                     self.logfile, sample.general.logout, sample.general.logerr,
                                     sample[self.analysistype].logout, sample[self.analysistype].logerr)
                    write_to_logfile(out,
                                     err,
                                     self.logfile, sample.general.logout, sample.general.logerr,
                                     sample[self.analysistype].logout, sample[self.analysistype].logerr)
785124
def _dbdir():
    
    global dbdir
    from os import mkdir, path, getcwd, chdir
    
    if dbdir is None:
        from acorn.config import settings
        config = settings("acorn")
        if (config.has_section("database") and
            config.has_option("database", "folder")):
            dbdir = config.get("database", "folder")
        else: # pragma: no cover
            raise ValueError("The folder to save DBs in must be configured"
                             "  in 'acorn.cfg'")

    #It is possible to specify the database path relative to the repository
    #root. path.abspath will map it correctly if we are in the root directory.
    from acorn.utility import abspath
    if not path.isabs(dbdir):
        #We want absolute paths to make it easier to port this to other OS.
        dbdir = abspath(dbdir)
        
    if not path.isdir(dbdir): # pragma: no cover
        mkdir(dbdir)
        
    return dbdir
724175
def backup_database(args):
    '''
    
    '''
    username = args.get('<user>')
    password = args.get('<password>')
    database = args['<database>']
    host = args.get('<host>') or '127.0.0.1'
    path = args.get('--path') or os.getcwd()
    s3 = args.get('--upload_s3')
    glacier = args.get('--upload_glacier')
    dropbox = args.get('--upload_dropbox')
    swift = args.get('--upload_swift')
    encrypt = args.get('--encrypt') or 'Y'

    if not database:
        raise SystemExit(_error_codes.get(101))
    if path and not os.path.isdir(path):
        raise SystemExit(_error_codes.get(105))

    query = 'mongodump -d {database} --host {host} '
    if username:
        query += '-u {username} '
    if password:
        query += '-p {password} '
    if path:
        query += '-o {path}/dump'

    local(query.format(username=username,
                       password=password,
                       database=database,
                       host=host,
                       path=path))

    compress_file = compress_folder_dump(
        normalize_path(path) + 'dump', normalize_path(path))

    shutil.rmtree(normalize_path(path) + 'dump')

    optional_actions(encrypt, path, compress_file,
                     s3=s3, glacier=glacier, dropbox=dropbox,
                     swift=swift)
201184
def _get_db():
    
    with cd(env.remote_path):
        file_path = '/tmp/' + _sql_paths('remote', str(base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', ''))
        run(env.python + ' manage.py dump_database | gzip > ' + file_path)
        local_file_path = './backups/' + _sql_paths('remote', datetime.now())
    get(file_path, local_file_path)
    run('rm ' + file_path)
    return local_file_path
569701
def set_dump_directory(base=None, sub_dir=None):
    """"""
    # Set current timestamp
    timestamp = datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H-%M-%S')

    # Clean sub_dir
    if sub_dir and '.' in sub_dir:
        sub_dir = sub_dir.rsplit('.', 1)[0]

    # Create a directory to save fail SQL scripts
    # TODO: Replace with function that recursively creates directories until path exists
    if not os.path.exists(base):
        os.mkdir(base)
    dump_dir = os.path.join(base, sub_dir) if sub_dir else base
    if not os.path.exists(dump_dir):
        os.mkdir(dump_dir)
    dump_dir = os.path.join(dump_dir, timestamp)
    if not os.path.exists(dump_dir):
        os.mkdir(dump_dir)
        return dump_dir
1322741
def exportdb():
    '''
    
    '''

    cmd = 'udevadm info --export-db'
    udev_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')

    if udev_result['retcode']:
        raise CommandExecutionError(udev_result['stderr'])

    return _parse_udevadm_info(udev_result['stdout'])
1092288
def load_database
      if dir_exists?
        config = {
          'adapter' => 'sqlite3',
          'database' => File.join(config_dir, DATABASE_FILE),
          'pool' => 5,
          'timeout' => 5000
        }

        begin
          ActiveRecord::Base.establish_connection(config)
          ActiveRecord::Migrator.migrate(File.join(File.dirname(__FILE__), \
            '../../db/migrate'), ENV['VERSION'] ? ENV['VERSION'].to_i : nil )

        rescue StandardError => e
          raise DatabaseAccessError, e.message
        end
      else
        raise ConfigDirMissingError, 'Config dir missing. Run init command'
      end
    end
279240
def get_db_filename(impl, working_dir):
    
    db_filename = impl.get_virtual_chain_name() + ".db"
    return os.path.join(working_dir, db_filename)
207883
def copy(dest)
      raise ArgumentError, "doc.database required to copy" unless database
      result = database.copy_doc(self, dest)
      result['ok']
    end