private void readMigrations(
      SortedMap<Long, List<ConfigMigrationStategy>> configMigrations, URL url) throws IOException {
    InputStreamReader r = null;
    try {
      r = new InputStreamReader(url.openStream(), ConfigUtilConstants.DEFAULT_TEXT_ENCODING);
      XStream x = createXStream();
      ConfigManagerMigrations migrations = (ConfigManagerMigrations) x.fromXML(r);

      for (Migration m : migrations.getMigrationList()) {
        long versionTarget = m.getTargetVersion();
        String className = m.getMigrationClass();
        String[] constructorArguments = m.getArguments();

        List<ConfigMigrationStategy> configMigrationForVersionTarget =
            configMigrations.get(versionTarget);
        if (configMigrationForVersionTarget == null) {
          configMigrationForVersionTarget = new ArrayList();
          configMigrations.put(versionTarget, configMigrationForVersionTarget);
        }

        ConfigMigrationStategy configMigration =
            createMigrationStrategy(versionTarget, className, constructorArguments);
        configMigrationForVersionTarget.add(configMigration);
      }
    } finally {
      try {
        if (r != null) r.close();
      } catch (IOException e) {
        ConfigLogImplementation.logMethods.error(
            "Failed to close ConfigMigration InputStream from URL " + url, e);
      }
    }
  }
 /**
  * Register in the database all of the migrations in the <code>config</code> parameter as run.
  *
  * @param config Configuration with the migrations that need to be marked as run.
  */
 public static void markAsMigrated(Configuration config) {
   configuration = config;
   ensureMigrationDao();
   List<String> actual = migrationDao.getAllMigrations();
   for (Migration m : config.getMigrations())
     if (!actual.contains(m.getMigration())) markAsMigrated(m);
 }
 /**
  * Runs all the migrations in the configuration which version key is not already present in the
  * database. The migration will get run in the same order they are in the list.
  *
  * @param configuration Configuration with the database and all the migrations.
  */
 public static void migrate(Configuration configuration) {
   Migrate4Droid.configuration = configuration;
   ensureMigrationDao();
   List<Migration> migrations = configuration.getMigrations();
   List<String> actual = migrationDao.getAllMigrations();
   for (Migration m : migrations) if (!actual.contains(m.getMigration())) runMigration(m);
 }
 /**
  * Moves the database to the <code>migration</code> specified, using the migrations in the <code>
  * configuration</code>, iterating them and checking:
  *
  * <ul>
  *   <li>If the migration's key is smaller than or equal to the desired <code>migration</code>'s
  *       key parameterized and it's not present in the database, the migration will get upgraded.
  *       That is, its method {@link Migration#up()} will be called. The order will be the same as
  *       the migrations are in the <code>configuration</code>.
  *   <li>If the migration's key is greater than the desired <code>migration</code>'s key
  *       parameterized and it IS present in the database, the migration will get downgraded. That
  *       is, its method {@link Migration#down()} will be called. The order will be the opposite
  *       the migrations are in the <code>configuration</code>.
  * </ul>
  *
  * @param configuration Configuration with the database and all the migrations that have to be
  *     considered during the migration.
  * @param migration String key of the migration the database is desired to be.
  */
 public static void migrate(Configuration configuration, String migration) {
   Migrate4Droid.configuration = configuration;
   ensureMigrationDao();
   List<Migration> migrations = configuration.getMigrations();
   List<Migration> downs = new ArrayList<Migration>();
   List<String> actual = migrationDao.getAllMigrations();
   for (Migration m : migrations) {
     String mig = m.getMigration();
     if (mig.compareTo(migration) <= 0 && !actual.contains(mig)) runMigration(m);
     else if (mig.compareTo(migration) > 0 && actual.contains(mig)) downs.add(0, m);
   }
   for (Migration m : downs) runMigration(m, false);
 }
 /**
  * Executes the migration in the database. If <code>up</code> is set to <code>true</code>, then
  * the method {@link Migration#up()} will be called. Otherwise, the method {@link
  * Migration#down()} will get called.
  *
  * @param m The migration to run.
  * @param up If <code>true</code>, it will upgrade. Otherwise, it will downgrade.
  */
 private static void runMigration(Migration m, boolean up) {
   SQLiteDatabase db = configuration.getDatabase();
   db.beginTransaction();
   try {
     if (up) {
       m.up();
       markAsMigrated(m);
     } else {
       m.down();
       migrationDao.delete(m.getMigration());
     }
     db.setTransactionSuccessful();
   } catch (Exception e) {
     Logger.e("Exception when migrating " + m.getClass().getName(), e);
   } finally {
     db.endTransaction();
   }
 }
Exemple #6
0
 private void apply(DataSource ds, Migration migration, Optional<Integer> version) {
   Jdbc.inTransaction(
       ds,
       connection -> {
         Migrater.current.set(connection);
         log.info("Applying {}: {}", migration.getClass().getSimpleName(), migration.toString());
         // Set the updater in case any history triggers are listening
         Jdbc.update(connection, "set @updater=?", migration.getClass().getSimpleName());
         try {
           migration.apply();
         } catch (SQLException se) {
           throw new JdbcException(se);
         }
         // Tick to the current version number
         version.ifPresent(v -> this.schemaInfoTable.updateVersionNumber(connection, v));
         Jdbc.update(connection, "set @updater=null");
         return null;
       });
 }
 private void sqlInsert(String id, String groupName, Integer shown, Integer showInHierarchy) {
   System.out.println(Migration.getThisBlock() + " Insert Group [" + id + "] - " + groupName);
   try {
     this.insertPreparedStatement.setString(1, id);
     this.insertPreparedStatement.setString(2, groupName);
     this.insertPreparedStatement.setInt(3, shown);
     this.insertPreparedStatement.setInt(4, showInHierarchy);
     this.insertPreparedStatement.executeUpdate();
   } catch (SQLException ex) {
     Logger.getLogger(MigrationShopGroups.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
  public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException {
    super(
        UUIDGen.makeType1UUIDFromHost(GossipUtilities.getLocalAddress()),
        NodeDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = NodeDescriptor.getTableDefinition(cfm.ksName);

    if (ksm == null) throw new ConfigurationException("No such keyspace: " + cfm.ksName);
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
      throw new ConfigurationException(
          String.format("%s already exists in keyspace %s", cfm.cfName, cfm.ksName));
    else if (!Migration.isLegalName(cfm.cfName))
      throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    for (Map.Entry<ByteBuffer, ColumnDefinition> entry : cfm.getColumn_metadata().entrySet()) {
      String indexName = entry.getValue().getIndexName();
      if (indexName != null && !Migration.isLegalName(indexName))
        throw new ConfigurationException("Invalid index name: " + indexName);
    }

    // clone ksm but include the new cf def.
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);

    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
  }
  public DropColumnFamily(String tableName, String cfName)
      throws ConfigurationException, IOException {
    super(
        UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()),
        DatabaseDescriptor.getDefsVersion());
    this.tableName = tableName;
    this.cfName = cfName;

    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(tableName);
    if (ksm == null) throw new ConfigurationException("Keyspace does not already exist.");
    else if (!ksm.cfMetaData().containsKey(cfName))
      throw new ConfigurationException("CF is not defined in that keyspace.");

    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
  }
  @Override
  public void applyModels() throws IOException {
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(name);
    // remove the table from the static instances.
    Table table = Table.clear(ksm.name);
    if (table == null) throw new IOException("Table is not active. " + ksm.name);

    // remove all cfs from the table instance.
    for (CFMetaData cfm : ksm.cfMetaData().values()) {
      CFMetaData.purge(cfm);
      table.dropCf(cfm.cfId);
      SystemTable.markForRemoval(cfm);
    }

    // reset defs.
    DatabaseDescriptor.clearTableDefinition(ksm, newVersion);
    CommitLog.instance().forceNewSegment();
    Migration.cleanupDeadFiles(blockOnFileDeletion);

    // clear up any local hinted data for this keyspace.
    HintedHandOffManager.renameHints(name, null);
  }
 protected static void markAsMigrated(Migration m) {
   DbMigration mig = new DbMigration();
   mig.setMigration(m.getMigration());
   migrationDao.save(mig);
 }