backup the current database version. automatically called by importGenome(). Returns the filename of the backup
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
769932
def _backup_previous_version(func: Callable = None):
    """"""

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        self.old_path = None
        if self.is_local:
            self.old_path = join(gettempdir(), self.name)
            if exists(self.old_path):
                rmtree(self.old_path)
            shutil.copytree(self.path, self.old_path)
        try:
            func(self, *args, **kwargs)

        # Modified skill or GitError should not restore working copy
        except (SkillModified, GitError, GitException):
            raise
        except Exception:
            LOG.info('Problem performing action. Restoring skill to '
                     'previous state...')
            if exists(self.path):
                rmtree(self.path)
            if self.old_path and exists(self.old_path):
                shutil.copytree(self.old_path, self.path)
            self.is_local = exists(self.path)
            raise

    return wrapper
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
958782
def namedb_read_version(path):
    
    con = sqlite3.connect( path, isolation_level=None, timeout=2**30 )
    con.row_factory = namedb_row_factory

    sql = 'SELECT version FROM db_version;'
    args = ()

    try:
        rowdata = namedb_query_execute(con, sql, args, abort=False)
        row = rowdata.fetchone()
        return row['version']
    except:
        # no version defined
        return '0.0.0.0'
    finally:
        con.close()
807587
def update_version_records(self):
        
        from .__init__ import __version__ as version
        with self.connection(commit=True) as connection:
            for vrec in self.get_version_records():
                if (vrec.rash_version == version and
                    vrec.schema_version == schema_version):
                    return  # no need to insert the new one!
            connection.execute(
                'INSERT INTO rash_info (rash_version, schema_version) '
                'VALUES (?, ?)',
                [version, schema_version])
991413
private void dbUpgrade()
    {
        DbConn cnx = this.getConn();
        Map<String, Object> rs = null;
        int db_schema_version = 0;
        try
        {
            rs = cnx.runSelectSingleRow("version_select_latest");
            db_schema_version = (Integer) rs.get("VERSION_D1");
        }
        catch (Exception e)
        {
            // Database is to be created, so version 0 is OK.
        }
        cnx.rollback();

        if (SCHEMA_VERSION > db_schema_version)
        {
            jqmlogger.warn("Database is being upgraded from version {} to version {}", db_schema_version, SCHEMA_VERSION);

            // Upgrade scripts are named from_to.sql with 5 padding (e.g. 00000_00003.sql)
            // We try to find the fastest path (e.g. a direct 00000_00005.sql for creating a version 5 schema from nothing)
            // This is a simplistic and non-optimal algorithm as we try only a single path (no going back)

            int loop_from = db_schema_version;
            int to = db_schema_version;
            List<String> toApply = new ArrayList<>();
            toApply.addAll(adapter.preSchemaCreationScripts());

            while (to != SCHEMA_VERSION)
            {
                boolean progressed = false;
                for (int loop_to = SCHEMA_VERSION; loop_to > db_schema_version; loop_to--)
                {
                    String migrationFileName = String.format("/sql/%05d_%05d.sql", loop_from, loop_to);
                    jqmlogger.debug("Trying migration script {}", migrationFileName);
                    if (Db.class.getResource(migrationFileName) != null)
                    {
                        toApply.add(migrationFileName);
                        to = loop_to;
                        loop_from = loop_to;
                        progressed = true;
                        break;
                    }
                }

                if (!progressed)
                {
                    break;
                }
            }
            if (to != SCHEMA_VERSION)
            {
                throw new DatabaseException(
                        "There is no migration path from version " + db_schema_version + " to version " + SCHEMA_VERSION);
            }

            for (String s : toApply)
            {
                jqmlogger.info("Running migration script {}", s);
                ScriptRunner.run(cnx, s);
            }
            cnx.commit(); // Yes, really. For advanced DB!

            cnx.close(); // HSQLDB does not refresh its schema without this.
            cnx = getConn();

            cnx.runUpdate("version_insert", SCHEMA_VERSION, SCHEMA_COMPATIBLE_VERSION);
            cnx.commit();
            jqmlogger.info("Database is now up to date");
        }
        else
        {
            jqmlogger.info("Database is already up to date");
        }
        cnx.close();
    }
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)
379254
def _cleanup_old_backups(self, database=None, servername=None):
        
        self.storage.clean_old_backups(encrypted=self.encrypt,
                                       compressed=self.compress,
                                       content_type=self.content_type,
                                       database=database,
                                       servername=servername)
741393
def current_db_version(self):
        

        query = """
        SELECT version from {} WHERE success = TRUE ORDER BY version DESC
        """.format(self.upgrades_table)

        self.cursor.execute(query)

        return self.cursor.fetchone()[0]
641369
def get_version(self):
        # type: () -> str
        
        # Get the version value
        version = getattr(self.__module, "__version__", None)
        if version:
            return version

        # Convert the __version_info__ entry
        info = getattr(self.__module, "__version_info__", None)
        if info:
            return ".".join(str(part) for part in __version_info__)

        # No version
        return "0.0.0"
1169102
def _update_version(connection, version):
    
    if connection.engine.name == 'sqlite':
        connection.execute('PRAGMA user_version = {}'.format(version))

    elif connection.engine.name == 'postgresql':

        connection.execute(DDL('CREATE SCHEMA IF NOT EXISTS {};'.format(POSTGRES_SCHEMA_NAME)))
        connection.execute(DDL('CREATE SCHEMA IF NOT EXISTS {};'.format(POSTGRES_PARTITION_SCHEMA_NAME)))

        connection.execute('CREATE TABLE IF NOT EXISTS {}.user_version(version INTEGER NOT NULL);'
                           .format(POSTGRES_SCHEMA_NAME))

        # upsert.
        if connection.execute('SELECT * FROM {}.user_version;'.format(POSTGRES_SCHEMA_NAME)).fetchone():
            # update
            connection.execute('UPDATE {}.user_version SET version = {};'
                               .format(POSTGRES_SCHEMA_NAME, version))
        else:
            # insert
            connection.execute('INSERT INTO {}.user_version (version) VALUES ({})'
                               .format(POSTGRES_SCHEMA_NAME, version))
    else:
        raise DatabaseMissingError('Do not know how to migrate {} engine.'
                                   .format(connection.engine.driver))
172047
@Exported
    public String getBackupVersion() {
        File backup = getBackupFile();
        if (backup.exists()) {
            try {
                try (JarFile backupPlugin = new JarFile(backup)) {
                    return backupPlugin.getManifest().getMainAttributes().getValue("Plugin-Version");
                }
            } catch (IOException e) {
                LOGGER.log(WARNING, "Failed to get backup version from " + backup, e);
                return null;
            }
        } else {
            return null;
        }
    }
98860
def _get_data_versions(data):
    
    genome_dir = install.get_genome_dir(data["genome_build"], data["dirs"].get("galaxy"), data)
    if genome_dir:
        version_file = os.path.join(genome_dir, "versions.csv")
        if version_file and os.path.exists(version_file):
            return version_file
    return None
630232
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
  public String getDatabaseSchemaVersion()
  {
    try
    {

      List<Map<String, Object>> result = getJdbcTemplate().
        queryForList(
          "SELECT \"value\" FROM repository_metadata WHERE \"name\"='schema-version'");

      String schema
        = result.size() > 0 ? (String) result.get(0).get("value") : "";
      return schema;
    }
    catch (DataAccessException ex)
    {
      String error = "Wrong database schema (too old to get the exact number), "
        + "please initialize the database.";
      log.error(error);
    }
    return "";
  }
949754
def existing_versions(self):
        
        import glob
        pattern = self.fname + '_*' + self.ext
        for fname in glob.glob1(self.dpath, pattern):
            fpath = join(self.dpath, fname)
            yield fpath
464917
def upgrade(self):
        
        warn('Upgrading ' + self.filename)
        if self.backup_config(self.filename):
            return self.write_default_config(self.filename)
        return False
102907
def runSql(self, migrationName, version):
        
        sys.stdout.write("Running migration %s to version %s: ..."%(migrationName, version))
        sqlPath = os.path.join(self.migrationDirectory, migrationName)
        sql = open(sqlPath, "r").read()
        try:
            if self.session.is_active:
                print "session is active"
                self.session.commit()
            self.session.begin()
            executeBatch(self.session, sql)
            self.session.add(models.Migration(version, migrationName))
        except:
            print "\n"
            self.session.rollback()
            raise
        else:
            self.session.commit()
        sys.stdout.write("\r")
        sys.stdout.flush()
        sys.stdout.write("Running migration %s to version %s: SUCCESS!\n"%(migrationName, version))