Replace your remote db with your local

    Example:
        sync_remote_to_local:force=yes
183754
def sync_remote_to_local(force="no"):
    

    assert "local_wp_dir" in env, "Missing local_wp_dir in env"

    if force != "yes":
        message = "This will replace your local database with your "\
            "remote, are you sure [y/n]"
        answer = prompt(message, "y")

        if answer != "y":
            logger.info("Sync stopped")
            return

    init_tasks()  # Bootstrap fabrik

    remote_file = "sync_%s.sql" % int(time.time()*1000)
    remote_path = "/tmp/%s" % remote_file

    with env.cd(paths.get_current_path()):
        env.run("wp db export %s" % remote_path)

    local_wp_dir = env.local_wp_dir
    local_path = "/tmp/%s" % remote_file

    # Download sync file
    get(remote_path, local_path)

    with lcd(local_wp_dir):
        elocal("wp db import %s" % local_path)

    # Cleanup
    env.run("rm %s" % remote_path)
    elocal("rm %s" % local_path)
1040677
def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None):
    """"""
    if remote_files is None:
        remote_files = command.map_files_raw(remote_dir=remote_dir)
    for local_file in to_sync:
        _sync_local_file(local_file, remote_dir, remote_files)
1303288
def sync(client=None, force=False, verbose=True):
    
    from mediasync import backends
    from mediasync.conf import msettings
    from mediasync.signals import pre_sync, post_sync

    # create client connection
    if client is None:
        client = backends.client()

    client.open()
    client.serve_remote = True

    # send pre-sync signal
    pre_sync.send(sender=client)

    #
    # sync joined media
    #

    for joinfile, sourcefiles in msettings['JOINED'].iteritems():
        
        filedata = combine_files(joinfile, sourcefiles, client)
        if filedata is None:
            # combine_files() is only interested in CSS/JS files.
            continue
        filedata, dirname = filedata

        content_type = mimetypes.guess_type(joinfile)[0] or msettings['DEFAULT_MIMETYPE']

        remote_path = joinfile
        if dirname:
            remote_path = "%s/%s" % (dirname, remote_path)

        if client.process_and_put(filedata, content_type, remote_path, force=force):
            if verbose:
                print "[%s] %s" % (content_type, remote_path)

    #
    # sync static media
    #

    for dirname in os.listdir(client.media_root):

        dirpath = os.path.abspath(os.path.join(client.media_root, dirname))

        if os.path.isdir(dirpath):

            for filename in listdir_recursive(dirpath):

                # calculate local and remote paths
                filepath = os.path.join(dirpath, filename)
                remote_path = "%s/%s" % (dirname, filename)

                content_type = mimetypes.guess_type(filepath)[0] or msettings['DEFAULT_MIMETYPE']

                if not is_syncable_file(os.path.basename(filename)) or not os.path.isfile(filepath):
                    continue # hidden file or directory, do not upload

                filedata = open(filepath, 'rb').read()

                if client.process_and_put(filedata, content_type, remote_path, force=force):
                    if verbose:
                        print "[%s] %s" % (content_type, remote_path)
    
    # send post-sync signal while client is still open
    post_sync.send(sender=client)
    
    client.close()
859652
function connect (state) {
  return Promise.resolve(state.remote)

  .then(function (remote) {
    if (state.replication) {
      return
    }

    state.replication = state.db.sync(remote, {
      create_target: true,
      live: true,
      retry: true
    })

    state.replication.on('error', function (error) {
      state.emitter.emit('error', error)
    })

    state.replication.on('change', function (change) {
      for (var i = 0; i < change.change.docs.length; i++) {
        state.emitter.emit(change.direction, change.change.docs[i])
      }
    })

    state.emitter.emit('connect')
  })
}
1100196
def copy_heroku_to_local(id):
    """"""
    heroku_app = HerokuApp(dallinger_uid=id)
    try:
        subprocess.call(["dropdb", heroku_app.name])
    except Exception:
        pass

    heroku_app.pg_pull()
218486
def drop_db():
    """"""
    local_machine()
    with fab_settings(warn_only=True):
        local('psql {0} -c "DROP DATABASE {1}"'.format(
            USER_AND_HOST, env.db_name))
        local('psql {0} -c "DROP USER {1}"'.format(
            USER_AND_HOST, env.db_role))
1028719
def local_async(self, *args, **kwargs):
        '''
        
        '''
        local = salt.client.get_local_client(mopts=self.opts)
        ret = local.run_job(*args, **kwargs)
        return ret
1314210
def configure_db(self, hostname, database, username, admin=False):
        """"""
        self.connect(password=self.get_mysql_root_password())
        if not self.database_exists(database):
            self.create_database(database)

        remote_ip = self.normalize_address(hostname)
        password = self.get_mysql_password(username)
        if not self.grant_exists(database, username, remote_ip):
            if not admin:
                self.create_grant(database, username, remote_ip, password)
            else:
                self.create_admin_grant(username, remote_ip, password)
            self.flush_priviledges()

        return password
714749
def chput(local_path=None, remote_path=None, user=None, group=None,
          mode=None, use_sudo=True, mirror_local_mode=False, check=True):
    """"""
    # pylint: disable=R0913
    result = None
    if env.get('full') or not check or diff(local_path, remote_path):
        result = put(local_path, remote_path, use_sudo,
                     mirror_local_mode, mode)
    with hide('commands'):
        chown(remote_path, user, group)
    return result
469870
def update(self):
        
        # Fetch remotes, so we know we're dealing with latest remote
        yield from self.update_remotes()

        # Rename local untracked files that might be overwritten by pull
        yield from self.rename_local_untracked()

        # Reset local files that have been deleted. We don't actually expect users to
        # delete something that's present upstream and expect to keep it. This prevents
        # unnecessary conflicts, and also allows users to click the link again to get
        # a fresh copy of a file they might have screwed up.
        yield from self.reset_deleted_files()

        # If there are local changes, make a commit so we can do merges when pulling
        # We also allow empty commits. On NFS (at least), sometimes repo_is_dirty returns a false
        # positive, returning True even when there are no local changes (git diff-files seems to return
        # bogus output?). While ideally that would not happen, allowing empty commits keeps us
        # resilient to that issue.
        if self.repo_is_dirty():
            yield from self.ensure_lock()
            yield from execute_cmd(['git', 'commit', '-am', 'WIP', '--allow-empty'], cwd=self.repo_dir)

        # Merge master into local!
        yield from self.ensure_lock()
        yield from execute_cmd(['git', 'merge', '-Xours', 'origin/{}'.format(self.branch_name)], cwd=self.repo_dir)
143449
def refresh_db(**kwargs):
    '''
    
    '''
    # Remove rtag file to keep multiple refreshes from happening in pkg states
    salt.utils.pkg.clear_rtag(__opts__)
    cmd = 'xbps-install -Sy'
    call = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
    if call['retcode'] != 0:
        comment = ''
        if 'stderr' in call:
            comment += call['stderr']

        raise CommandExecutionError(comment)

    return True
1207584
def put(self, local_path, path, atomic=True):
        
        self._connect()

        if self.sftp:
            self._sftp_put(local_path, path, atomic)
        else:
            self._ftp_put(local_path, path, atomic)

        self._close()
926429
public function syncDb() {
    $local_alias = '@' . $this->getConfigValue('drush.aliases.local');
    $remote_alias = '@' . $this->getConfigValue('drush.aliases.remote');

    $task = $this->taskDrush()
      ->alias('')
      ->drush('cache-clear drush')
      ->drush('sql-sync')
      ->arg($remote_alias)
      ->arg($local_alias)
      ->option('--target-dump', sys_get_temp_dir() . '/tmp.target.sql.gz')
      ->option('structure-tables-key', 'lightweight')
      ->option('create-db');

    if ($this->getConfigValue('drush.sanitize')) {
      $task->drush('sql-sanitize');
    }

    $task->drush('cr');
    $task->drush('sqlq "TRUNCATE cache_entity"');

    $result = $task->run();

    return $result;
  }
838462
def sync_db():
    
    with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
        venv = '/'.join([deployment_root(),'env',env.project_fullname,'bin','activate'])
        sites = _get_django_sites()
        site_ids = sites.keys()
        site_ids.sort()
        for site in site_ids:
            for settings_file in _sitesettings_files():
                site_settings = '.'.join([env.project_package_name,'sitesettings',settings_file.replace('.py','')])
                if env.verbosity:
                    print " * django-admin.py syncdb --noinput --settings=%s"% site_settings
                output = sudo(' '.join(['source',venv,'&&',"django-admin.py syncdb --noinput --settings=%s"% site_settings]),
                              user='site_%s'% site)
                if env.verbosity:
                    print output
82030
def Remote(path=None, loader=Notebook, **globals):
    

    class Remote(RemoteMixin, loader):
        ...

    return Remote(path=path, **globals)
392201
def deploy_db(rollback=False):
    
    if not rollback:

        if env.DEFAULT_DATABASE_ENGINE=='django.db.backends.sqlite3':
            db_dir = '/'.join([deployment_root(),'database'])
            db_name = ''.join([env.project_name,'_','site_1','.db'])
            dest_db_path = '/'.join([db_dir,db_name])
            if exists(dest_db_path): return
            if env.verbosity:
                print env.host,"DEPLOYING DEFAULT SQLITE DATABASE"
            if not env.DEFAULT_DATABASE_NAME:
                print "ERROR: A database name has not been defined in your Django settings file"
                sys.exit(1)

            if env.DEFAULT_DATABASE_NAME[0] not in [os.path.sep,'.']: #relative path
                db_path = os.path.join(os.getcwd(),env.project_package_name,env.DEFAULT_DATABASE_NAME)

            elif env.DEFAULT_DATABASE_NAME[:2] == '..':
                print "ERROR: Use a full expanded path to the database in your Django settings"
                sys.exit(1)
            else:
                db_path = env.DEFAULT_DATABASE_NAME

            if not db_path or not os.path.exists(db_path):
                print "ERROR: the database %s does not exist. \nRun python manage.py syncdb to create your database locally first, or check your settings."% db_path
                sys.exit(1)

            db_name = os.path.split(db_path)[1]  
            run('mkdir -p '+db_dir)
            put(db_path,dest_db_path)
            #directory and file must be writable by webserver
            sudo("chown -R %s:www-data %s"% (env.user,db_dir))
            sudo("chmod -R ug+w %s"% db_dir)
        
        elif env.DEFAULT_DATABASE_ENGINE=='django.db.backends.':
            print "ERROR: The default database engine has not been defined in your Django settings file"
            print "At a minimum you must define an sqlite3 database for woven to deploy, or define a database that is managed outside of woven."
            sys.exit(1)
    elif rollback and env.DEFAULT_DATABASE_ENGINE=='django.db.backends.sqlite3':
        if env.INTERACTIVE:
            delete = confirm('DELETE the database on the host?',default=False)
            if delete:
                run('rm -f '+db_name)
    return
1358197
def sync(self, force=None):
        """"""

        try:
            if force:
                sd = force
            else:
                sd = self.sync_dir()

            if sd == self.SYNC_DIR.FILE_TO_RECORD:

                if force and not self.exists():
                    return None

                self.fs_to_record()

            elif sd == self.SYNC_DIR.RECORD_TO_FILE:
                self.record_to_fs()

            else:
                return None

            self._dataset.config.sync[self.file_const][sd] = time.time()
            return sd
        except Exception as e:
            self._bundle.rollback()
            self._bundle.error("Failed to sync '{}': {}".format(self.file_const, e))
            raise