@Override
  public Sql[] generateSql(
      CreateDatabaseChangeLogTableStatement statement,
      Database database,
      SqlGeneratorChain sqlGeneratorChain) {
    /* Because Informix has some limitations on the primary key column cumulative size (same is for unique indices),
     * the ID's column has been made the sole primary key, and also has a reduced size.
     *
     * The original configuration provided by the base class causes the database changelog table not to be created.
     */

    CreateTableStatement createTableStatement =
        new CreateTableStatement(
                database.getLiquibaseCatalogName(),
                database.getLiquibaseSchemaName(),
                database.getDatabaseChangeLogTableName())
            .addPrimaryKeyColumn(
                "ID",
                DataTypeFactory.getInstance().fromDescription("VARCHAR(" + getIdColumnSize() + ")"),
                null,
                null,
                null,
                new NotNullConstraint())
            .addColumn(
                "AUTHOR",
                DataTypeFactory.getInstance()
                    .fromDescription("VARCHAR(" + getAuthorColumnSize() + ")"),
                null,
                null,
                null,
                new NotNullConstraint())
            .addColumn(
                "FILENAME",
                DataTypeFactory.getInstance()
                    .fromDescription("VARCHAR(" + getFilenameColumnSize() + ")"),
                null,
                null,
                null,
                new NotNullConstraint())
            .addColumn(
                "DATEEXECUTED",
                DataTypeFactory.getInstance().fromDescription("datetime"),
                null,
                new NotNullConstraint())
            .addColumn(
                "ORDEREXECUTED",
                DataTypeFactory.getInstance().fromDescription("INT"),
                new NotNullConstraint())
            .addColumn(
                "EXECTYPE",
                DataTypeFactory.getInstance().fromDescription("VARCHAR(10)"),
                new NotNullConstraint())
            .addColumn("MD5SUM", DataTypeFactory.getInstance().fromDescription("VARCHAR(35)"))
            .addColumn("DESCRIPTION", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)"))
            .addColumn("COMMENTS", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)"))
            .addColumn("TAG", DataTypeFactory.getInstance().fromDescription("VARCHAR(255)"))
            .addColumn("LIQUIBASE", DataTypeFactory.getInstance().fromDescription("VARCHAR(20)"));

    return SqlGeneratorFactory.getInstance().generateSql(createTableStatement, database);
  }
Esempio n. 2
0
  public boolean isDatabaseChangeLogLockTableInitialized(final boolean tableJustCreated)
      throws DatabaseException {
    if (!isDatabaseChangeLogLockTableInitialized) {
      Executor executor = ExecutorService.getInstance().getExecutor(database);

      try {
        isDatabaseChangeLogLockTableInitialized =
            executor.queryForInt(
                    new RawSqlStatement(
                        "select count(*) from "
                            + database.escapeTableName(
                                database.getLiquibaseCatalogName(),
                                database.getLiquibaseSchemaName(),
                                database.getDatabaseChangeLogLockTableName())))
                > 0;
      } catch (LiquibaseException e) {
        if (executor.updatesDatabase()) {
          throw new UnexpectedLiquibaseException(e);
        } else {
          // probably didn't actually create the table yet.
          isDatabaseChangeLogLockTableInitialized = !tableJustCreated;
        }
      }
    }
    return isDatabaseChangeLogLockTableInitialized;
  }
  public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet)
      throws PreconditionFailedException, PreconditionErrorException {
    Column example = new Column();
    if (StringUtils.trimToNull(getTableName()) != null) {
      example.setRelation(
          new Table()
              .setName(database.correctObjectName(getTableName(), Table.class))
              .setSchema(new Schema(getCatalogName(), getSchemaName())));
    }
    example.setName(database.correctObjectName(getColumnName(), Column.class));

    try {
      if (!SnapshotGeneratorFactory.getInstance().has(example, database)) {
        throw new PreconditionFailedException(
            "Column '"
                + database.escapeColumnName(
                    catalogName, schemaName, getTableName(), getColumnName())
                + "' does not exist",
            changeLog,
            this);
      }
    } catch (LiquibaseException e) {
      throw new PreconditionErrorException(e, changeLog, this);
    }
  }
  /**
   * Builds the command line arguments that will be executed.
   *
   * @param database the database - needed to get the connection info.
   * @return the command line arguments including {@link #COMMAND}
   */
  List<String> buildCommand(Database database) {
    List<String> commands = new ArrayList<String>();
    commands.add(PTOnlineSchemaChangeStatement.COMMAND);

    if (!Configuration.getAdditionalOptions().isEmpty()) {
      commands.addAll(tokenize(Configuration.getAdditionalOptions()));
    }

    commands.add("--alter=" + alterStatement);
    commands.add("--alter-foreign-keys-method=auto");

    if (database.getConnection() != null) {
      DatabaseConnectionUtil connection = new DatabaseConnectionUtil(database.getConnection());
      commands.add("--host=" + connection.getHost());
      commands.add("--port=" + connection.getPort());
      commands.add("--user="******"--password="******"--execute");
    commands.add("D=" + database.getLiquibaseSchemaName() + ",t=" + tableName);
    return commands;
  }
  public Sql[] generateSql(
      SelectFromDatabaseChangeLogStatement statement,
      Database database,
      SqlGeneratorChain sqlGeneratorChain) {
    String sql =
        "SELECT "
            + StringUtils.join(statement.getColumnsToSelect(), ",").toUpperCase()
            + " FROM "
            + database.escapeTableName(
                database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName());

    SelectFromDatabaseChangeLogStatement.WhereClause whereClause = statement.getWhereClause();
    if (whereClause != null) {
      if (whereClause instanceof SelectFromDatabaseChangeLogStatement.ByTag) {
        sql +=
            " WHERE TAG='"
                + ((SelectFromDatabaseChangeLogStatement.ByTag) whereClause).getTagName()
                + "'";
      } else if (whereClause instanceof SelectFromDatabaseChangeLogStatement.ByNotNullCheckSum) {
        sql += " WHERE MD5SUM IS NOT NULL";
      } else {
        throw new UnexpectedLiquibaseException(
            "Unknown where clause type: " + whereClause.getClass().getName());
      }
    }

    if (statement.getOrderByColumns() != null && statement.getOrderByColumns().length > 0) {
      sql += " ORDER BY " + StringUtils.join(statement.getOrderByColumns(), ", ").toUpperCase();
    }

    return new Sql[] {new UnparsedSql(sql)};
  }
  @Override
  public Sql[] generateSql(
      GetViewDefinitionStatement statement,
      Database database,
      SqlGeneratorChain sqlGeneratorChain) {
    try {
      String sql =
          "select isnull(object_definition(OBJECT_ID(object_id)), view_definition) from sys.objects, sys.schemas, INFORMATION_SCHEMA.VIEWS where objects.type='v' and upper(objects.name)='"
              + statement.getViewName().toUpperCase()
              + "'";
      sql +=
          " and objects.schema_id=schemas.schema_id and schemas.name='"
              + database.convertRequestedSchemaToSchema(statement.getSchemaName())
              + "'";
      sql += " AND upper(table_name)='" + statement.getViewName().toUpperCase() + "'";
      //        if (StringUtils.trimToNull(schemaName) != null) {
      sql +=
          " and table_schema='"
              + database.convertRequestedSchemaToSchema(statement.getSchemaName())
              + "'";
      sql += " and table_catalog='" + database.getDefaultCatalogName() + "'";

      //        log.info("GetViewDefinitionSQL: "+sql);

      return new Sql[] {new UnparsedSql(sql)};
    } catch (DatabaseException e) {
      throw new UnexpectedLiquibaseException(e);
    }
  }
Esempio n. 7
0
  public DatabaseChangeLogLock[] listLocks() throws DatabaseException {
    try {
      if (!database.hasDatabaseChangeLogLockTable()) {
        return new DatabaseChangeLogLock[0];
      }

      List<DatabaseChangeLogLock> allLocks = new ArrayList<DatabaseChangeLogLock>();
      SqlStatement sqlStatement =
          new SelectFromDatabaseChangeLogLockStatement("ID", "LOCKED", "LOCKGRANTED", "LOCKEDBY");
      List<Map> rows =
          ExecutorService.getInstance().getExecutor(database).queryForList(sqlStatement);
      for (Map columnMap : rows) {
        Object lockedValue = columnMap.get("LOCKED");
        Boolean locked;
        if (lockedValue instanceof Number) {
          locked = ((Number) lockedValue).intValue() == 1;
        } else {
          locked = (Boolean) lockedValue;
        }
        if (locked != null && locked) {
          allLocks.add(
              new DatabaseChangeLogLock(
                  ((Number) columnMap.get("ID")).intValue(),
                  (Date) columnMap.get("LOCKGRANTED"),
                  (String) columnMap.get("LOCKEDBY")));
        }
      }
      return allLocks.toArray(new DatabaseChangeLogLock[allLocks.size()]);
    } finally {
      database
          .rollback(); // Rollback to make sure any database explicitly imposed lock from the above
                       // SELECT statement gets released. CORE-1219 incident.
    }
  }
  @Override
  public Sql[] generateSql(
      AddDefaultValueStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {

    Object defaultValue = statement.getDefaultValue();
    StringBuffer sql = new StringBuffer("ALTER TABLE ");
    sql.append(
        database.escapeTableName(
            statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()));
    sql.append(" MODIFY (");
    sql.append(
        database.escapeColumnName(
            statement.getCatalogName(),
            statement.getSchemaName(),
            statement.getTableName(),
            statement.getColumnName()));
    sql.append(" ");
    sql.append(
        DataTypeFactory.getInstance().fromDescription(statement.getColumnDataType(), database));
    sql.append(" DEFAULT ");
    sql.append(
        DataTypeFactory.getInstance()
            .fromObject(defaultValue, database)
            .objectToSql(defaultValue, database));
    sql.append(")");
    UnparsedSql unparsedSql = new UnparsedSql(sql.toString(), getAffectedColumn(statement));
    return new Sql[] {unparsedSql};
  }
  @Override
  protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot)
      throws DatabaseException {
    Database database = snapshot.getDatabase();
    String objectName = example.getName();
    Schema schema = example.getSchema();

    List<CachedRow> rs = null;
    try {
      JdbcDatabaseSnapshot.CachingDatabaseMetaData metaData =
          ((JdbcDatabaseSnapshot) snapshot).getMetaData();
      rs =
          metaData.getTables(
              ((AbstractJdbcDatabase) database).getJdbcCatalogName(schema),
              ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema),
              database.correctObjectName(objectName, Table.class),
              new String[] {"TABLE"});

      Table table;
      if (rs.size() > 0) {
        table = readTable(rs.get(0), database);
      } else {
        return null;
      }

      return table;
    } catch (SQLException e) {
      throw new DatabaseException(e);
    }
  }
Esempio n. 10
0
 @Override
 @Test
 public void escapeTableName_withSchema() {
   Database database = getDatabase();
   assertEquals(
       "catalogName.tableName",
       database.escapeTableName("catalogName", "schemaName", "tableName"));
 }
Esempio n. 11
0
  public void testGetDefaultDriver() {
    Database database = new MySQLDatabase();

    assertEquals(
        "com.mysql.jdbc.Driver", database.getDefaultDriver("jdbc:mysql://localhost/liquibase"));

    assertNull(database.getDefaultDriver("jdbc:db2://localhost;databaseName=liquibase"));
  }
Esempio n. 12
0
  public void testGetDefaultDriver() {
    Database database = new OracleDatabase();

    assertEquals(
        "oracle.jdbc.OracleDriver", database.getDefaultDriver("jdbc:oracle:thin:@localhost/XE"));

    assertNull(database.getDefaultDriver("jdbc:db2://localhost;databaseName=liquibase"));
  }
Esempio n. 13
0
  public void testGetDefaultDriver() {
    Database database = new DerbyDatabase();

    assertEquals(
        "org.apache.derby.jdbc.EmbeddedDriver",
        database.getDefaultDriver("jdbc:derby:liquibase;create=true"));

    assertNull(database.getDefaultDriver("jdbc:oracle://localhost;databaseName=liquibase"));
  }
  @Override
  public List<ForeignKey> getAdditionalForeignKeys(String schemaName, Database database)
      throws DatabaseException {
    List<ForeignKey> foreignKeys = super.getAdditionalForeignKeys(schemaName, database);

    // Setting default schema name. Needed for correct statement generation
    if (schemaName == null) {
      schemaName = database.convertRequestedSchemaToSchema(schemaName);
    }

    // Create SQL statement to select all FKs in database which referenced to unique columns
    String query =
        "select uc_fk.constraint_name FK_NAME,uc_fk.owner FKTABLE_SCHEM,ucc_fk.table_name FKTABLE_NAME,ucc_fk.column_name FKCOLUMN_NAME,decode(uc_fk.deferrable, 'DEFERRABLE', 5 ,'NOT DEFERRABLE', 7 , 'DEFERRED', 6 ) DEFERRABILITY, decode(uc_fk.delete_rule, 'CASCADE', 0,'NO ACTION', 3) DELETE_RULE,ucc_rf.table_name PKTABLE_NAME,ucc_rf.column_name PKCOLUMN_NAME from all_cons_columns ucc_fk,all_constraints uc_fk,all_cons_columns ucc_rf,all_constraints uc_rf where uc_fk.CONSTRAINT_NAME = ucc_fk.CONSTRAINT_NAME and uc_fk.constraint_type='R' and uc_fk.r_constraint_name=ucc_rf.CONSTRAINT_NAME and uc_rf.constraint_name = ucc_rf.constraint_name and uc_rf.constraint_type = 'U' and uc_fk.owner = '"
            + schemaName
            + "' and ucc_fk.owner = '"
            + schemaName
            + "' and uc_rf.owner = '"
            + schemaName
            + "' and ucc_rf.owner = '"
            + schemaName
            + "'";
    Statement statement = null;
    ResultSet rs = null;
    try {
      statement =
          ((JdbcConnection) database.getConnection()).getUnderlyingConnection().createStatement();
      rs = statement.executeQuery(query);
      while (rs.next()) {
        ForeignKeyInfo fkInfo = new ForeignKeyInfo();
        fkInfo.setReferencesUniqueColumn(true);
        fkInfo.setFkName(convertFromDatabaseName(rs.getString("FK_NAME")));
        fkInfo.setFkSchema(convertFromDatabaseName(rs.getString("FKTABLE_SCHEM")));
        fkInfo.setFkTableName(convertFromDatabaseName(rs.getString("FKTABLE_NAME")));
        fkInfo.setFkColumn(convertFromDatabaseName(rs.getString("FKCOLUMN_NAME")));

        fkInfo.setPkTableName(convertFromDatabaseName(rs.getString("PKTABLE_NAME")));
        fkInfo.setPkColumn(convertFromDatabaseName(rs.getString("PKCOLUMN_NAME")));

        fkInfo.setDeferrablility(rs.getShort("DEFERRABILITY"));
        ForeignKeyConstraintType deleteRule =
            convertToForeignKeyConstraintType(rs.getInt("DELETE_RULE"));
        if (rs.wasNull()) {
          deleteRule = null;
        }
        fkInfo.setDeleteRule(deleteRule);
        foreignKeys.add(generateForeignKey(fkInfo, database, foreignKeys));
      }
    } catch (SQLException e) {
      throw new DatabaseException(
          "Can't execute selection query to generate list of foreign keys", e);
    } finally {
      JdbcUtils.closeResultSet(rs);
      JdbcUtils.closeStatement(statement);
    }
    return foreignKeys;
  }
  @Test
  public void accepts() throws DatabaseException {
    ArrayList<RanChangeSet> ranChanges = new ArrayList<RanChangeSet>();
    ranChanges.add(
        new RanChangeSet(
            "path/changelog", "1", "testAuthor", CheckSum.parse("12345"), new Date(), null, null));
    ranChanges.add(
        new RanChangeSet(
            "path/changelog", "2", "testAuthor", CheckSum.parse("12345"), new Date(), null, null));

    Database database = createMock(Database.class);
    expect(database.getRanChangeSetList()).andReturn(ranChanges);
    expect(database.getDatabaseChangeLogTableName()).andReturn("DATABASECHANGELOG").anyTimes();
    expect(database.getDefaultSchemaName()).andReturn(null).anyTimes();

    Executor template = createMock(Executor.class);
    expect(template.update(isA(UpdateStatement.class))).andReturn(1).anyTimes();
    //        template.comment("Lock Database");
    //        expectLastCall();

    replay(database);
    replay(template);
    ExecutorService.getInstance().setExecutor(database, template);

    ShouldRunChangeSetFilter filter = new ShouldRunChangeSetFilter(database);

    // everything same
    assertFalse(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, false, "path/changelog", null, null)));

    // alwaysRun
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", true, false, "path/changelog", null, null)));

    // run on change
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, true, "path/changelog", null, null)));

    // different id
    assertTrue(
        filter.accepts(
            new ChangeSet("3", "testAuthor", false, false, "path/changelog", null, null)));

    // different author
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "otherAuthor", false, false, "path/changelog", null, null)));

    // different path
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, false, "other/changelog", null, null)));
  }
  protected void dropSequenceIfExists(String schemaName, String sequenceName, Database database)
      throws SQLException {
    if (schemaName != null && !database.supportsSchemas()) {
      return;
    }

    if (!database.getAutoCommitMode()) {
      database.getConnection().commit();
    }

    try {
      new JdbcTemplate(database).execute(new DropSequenceStatement(schemaName, sequenceName));

      if (!database.getAutoCommitMode()) {
        database.getConnection().commit();
      }

    } catch (JDBCException e) {
      //            System.out.println("Error dropping sequence
      // "+database.escapeSequenceName(schemaName, sequenceName));
      //            e.printStackTrace();
      if (!database.getConnection().getAutoCommit()) {
        database.getConnection().rollback();
      }
    }
    if (!database.getAutoCommitMode()) {
      database.getConnection().commit();
    }
  }
  protected void dropViewIfExists(String schemaName, String viewName, Database database)
      throws SQLException {
    if (schemaName != null && !database.supportsSchemas()) {
      return;
    }

    if (!database.getAutoCommitMode()) {
      database.getConnection().commit();
    }

    String schema = "";
    if (schemaName != null) {
      schema = schemaName + ".";
    }

    try {
      new JdbcTemplate(database).execute(new RawSqlStatement("drop view " + schema + viewName));

      if (!database.getAutoCommitMode()) {
        database.getConnection().commit();
      }

    } catch (JDBCException e) {
      //            System.out.println("Cannot drop view "+database.escapeViewName(schemaName,
      // viewName)+" on "+database);
      //            e.printStackTrace();
      if (!database.getConnection().getAutoCommit()) {
        database.getConnection().rollback();
      }
    }

    if (!database.getAutoCommitMode()) {
      database.getConnection().commit();
    }
  }
Esempio n. 18
0
  protected String generateSingleColumnSQL(AddColumnStatement statement, Database database) {
    DatabaseDataType columnType =
        DataTypeFactory.getInstance()
            .fromDescription(
                statement.getColumnType()
                    + (statement.isAutoIncrement() ? "{autoIncrement:true}" : ""),
                database)
            .toDatabaseDataType(database);

    String alterTable =
        " ADD "
            + database.escapeColumnName(
                statement.getCatalogName(),
                statement.getSchemaName(),
                statement.getTableName(),
                statement.getColumnName())
            + " "
            + columnType;

    if (statement.isAutoIncrement() && database.supportsAutoIncrement()) {
      AutoIncrementConstraint autoIncrementConstraint = statement.getAutoIncrementConstraint();
      alterTable +=
          " "
              + database.getAutoIncrementClause(
                  autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy());
    }

    alterTable += getDefaultClause(statement, database);

    if (!statement.isNullable()) {
      alterTable += " NOT NULL";
    } else {
      if (database instanceof SybaseDatabase
          || database instanceof SybaseASADatabase
          || database instanceof MySQLDatabase
          || (database instanceof MSSQLDatabase
              && columnType.toString().equalsIgnoreCase("timestamp"))) {
        alterTable += " NULL";
      }
    }

    if (statement.isPrimaryKey()) {
      alterTable += " PRIMARY KEY";
    }

    if (database instanceof MySQLDatabase && statement.getRemarks() != null) {
      alterTable += " COMMENT '" + statement.getRemarks() + "' ";
    }

    if (statement.getAddAfterColumn() != null && !statement.getAddAfterColumn().isEmpty()) {
      alterTable += " AFTER `" + statement.getAddAfterColumn() + "` ";
    }

    return alterTable;
  }
  @Override
  protected void readColumns(
      DatabaseSnapshot snapshot, String schema, DatabaseMetaData databaseMetaData)
      throws SQLException, DatabaseException {
    findIntegerColumns(snapshot, schema);
    super.readColumns(snapshot, schema, databaseMetaData);

    /*
     * Code Description:
     * Finding all 'tablespace' attributes of column's PKs
     * */
    Database database = snapshot.getDatabase();
    Statement statement = null;
    ResultSet rs = null;
    try {
      statement =
          ((JdbcConnection) database.getConnection()).getUnderlyingConnection().createStatement();

      // Setting default schema name. Needed for correct statement generation
      if (schema == null) schema = database.convertRequestedSchemaToSchema(schema);

      String query =
          "select ui.tablespace_name TABLESPACE, ucc.table_name TABLE_NAME, ucc.column_name COLUMN_NAME FROM all_indexes ui , all_constraints uc , all_cons_columns ucc where uc.constraint_type = 'P' and ucc.constraint_name = uc.constraint_name and uc.index_name = ui.index_name and uc.owner = '"
              + schema
              + "' and ui.table_owner = '"
              + schema
              + "' and ucc.owner = '"
              + schema
              + "'";
      rs = statement.executeQuery(query);

      while (rs.next()) {
        Column column = snapshot.getColumn(rs.getString("TABLE_NAME"), rs.getString("COLUMN_NAME"));
        // setting up tablespace property to column, to configure it's PK-index
        if (column == null) {
          continue; // probably a different schema
        }
        column.setTablespace(rs.getString("TABLESPACE"));
      }
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException ignore) {
        }
      }
      if (statement != null) {
        try {
          statement.close();
        } catch (SQLException ignore) {
        }
      }
    }
  }
Esempio n. 20
0
 @Override
 protected StringClauses generateSql(RenameColumnAction action, Scope scope) {
   Database database = scope.getDatabase();
   return new StringClauses()
       .append("ALTER TABLE")
       .append(database.quoteObjectName(action.relation, scope))
       .append("RENAME")
       .append("COLUMN")
       .append(database.quoteObjectName(action.oldName, Column.class, scope))
       .append("TO")
       .append(database.quoteObjectName(action.newName, Column.class, scope));
 }
 @Before
 public void setupAvailableDatabases() throws Exception {
   for (Database database : TestContext.getInstance().getAvailableDatabases()) {
     if (generateTestStatement().supportsDatabase(database)) {
       if (database.supportsSchemas()) {
         database.dropDatabaseObjects(TestContext.ALT_SCHEMA);
       }
       database.dropDatabaseObjects(null);
       setupDatabase(database);
     }
   }
 }
  @Test
  public void accepts_noneRun() throws DatabaseException {
    Database database = createMock(Database.class);
    expect(database.getRanChangeSetList()).andReturn(new ArrayList<RanChangeSet>());
    replay(database);

    ShouldRunChangeSetFilter filter = new ShouldRunChangeSetFilter(database);

    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, false, "path/changelog", null, null)));
  }
 @Override
 public boolean supports(Database database) {
   if (database == null || database.getConnection() == null) {
     return false;
   }
   try {
     return super.supports(database)
         && (database.getDatabaseMajorVersion() * 10 + database.getDatabaseMinorVersion() >= 83);
   } catch (DatabaseException e) {
     return false;
   }
 }
  protected void dropAndCreateSequence(CreateSequenceStatement statement, Database database)
      throws SQLException, JDBCException {
    if (statement.getSchemaName() != null && !database.supportsSchemas()) {
      return;
    }

    dropSequenceIfExists(statement.getSchemaName(), statement.getSequenceName(), database);

    new JdbcTemplate(database).execute(statement);

    if (!database.getAutoCommitMode()) {
      database.getConnection().commit();
    }
  }
Esempio n. 25
0
  @Override
  public boolean acquireLock() throws LockException {
    if (hasChangeLogLock) {
      return true;
    }

    Executor executor = ExecutorService.getInstance().getExecutor(database);

    try {
      database.rollback();
      this.init();

      Boolean locked =
          (Boolean)
              ExecutorService.getInstance()
                  .getExecutor(database)
                  .queryForObject(
                      new SelectFromDatabaseChangeLogLockStatement("LOCKED"), Boolean.class);

      if (locked) {
        return false;
      } else {

        executor.comment("Lock Database");
        int rowsUpdated = executor.update(new LockDatabaseChangeLogStatement());
        if (rowsUpdated > 1) {
          throw new LockException("Did not update change log lock correctly");
        }
        if (rowsUpdated == 0) {
          // another node was faster
          return false;
        }
        database.commit();
        LogFactory.getLogger().info("Successfully acquired change log lock");

        hasChangeLogLock = true;

        database.setCanCacheLiquibaseTableInfo(true);
        return true;
      }
    } catch (Exception e) {
      throw new LockException(e);
    } finally {
      try {
        database.rollback();
      } catch (DatabaseException e) {;
      }
    }
  }
  @Test
  public void runLiquibase() throws Exception {
    Database database = createDatabase();
    Assert.assertNotNull(database.getConnection());

    File basedir = new File(System.getProperty("project.basedir"));
    FileSystemResourceAccessor resourceAccessor =
        new FileSystemResourceAccessor(basedir.getAbsolutePath());

    URL url = getClass().getResource("/changelog.xml");
    File changeLog = new File(url.toURI());

    Liquibase liquibase = new Liquibase(changeLog.getAbsolutePath(), resourceAccessor, database);
    liquibase.update(null);
  }
  @Test
  public void lessThanMinimumFails() throws Exception {
    ChangeFactory changeFactory = ChangeFactory.getInstance();
    for (String changeName : changeFactory.getDefinedChanges()) {
      for (Database database : DatabaseFactory.getInstance().getImplementedDatabases()) {
        if (database.getShortName() == null) {
          continue;
        }

        Change change = changeFactory.create(changeName);
        if (!change.supports(database)) {
          continue;
        }
        if (change.generateStatementsVolatile(database)) {
          continue;
        }
        ChangeMetaData changeMetaData = ChangeFactory.getInstance().getChangeMetaData(change);

        change.setResourceAccessor(new JUnitResourceAccessor());

        ArrayList<String> requiredParams =
            new ArrayList<String>(changeMetaData.getRequiredParameters(database).keySet());
        for (String paramName : requiredParams) {
          ChangeParameterMetaData param = changeMetaData.getParameters().get(paramName);
          Object paramValue = param.getExampleValue();
          param.setValue(change, paramValue);
        }

        for (int i = 0; i < requiredParams.size(); i++) {
          String paramToRemove = requiredParams.get(i);
          ChangeParameterMetaData paramToRemoveMetadata =
              changeMetaData.getParameters().get(paramToRemove);
          Object currentValue = paramToRemoveMetadata.getCurrentValue(change);
          paramToRemoveMetadata.setValue(change, null);

          assertTrue(
              "No errors even with "
                  + changeMetaData.getName()
                  + " with a null "
                  + paramToRemove
                  + " on "
                  + database.getShortName(),
              change.validate(database).hasErrors());
          paramToRemoveMetadata.setValue(change, currentValue);
        }
      }
    }
  }
Esempio n. 28
0
 public String createKey(Database database, String... params) {
   String key = StringUtils.join(params, ":");
   if (!database.isCaseSensitive()) {
     return key.toLowerCase();
   }
   return key;
 }
Esempio n. 29
0
 public String createSchemaKey(Database database) {
   if (!database.supportsCatalogs() && !database.supportsSchemas()) {
     return "all";
   } else if (database.supportsCatalogs() && database.supportsSchemas()) {
     return (catalog + "." + schema).toLowerCase();
   } else {
     if (catalog == null && schema != null) {
       return schema.toLowerCase();
     } else {
       if (catalog == null) {
         return "all";
       }
       return catalog.toLowerCase();
     }
   }
 }
Esempio n. 30
0
  /**
   * Generates one or more SqlStatements depending on how the SQL should be parsed. If split
   * statements is set to true then the SQL is split and each cpommand is made a separate
   * SqlStatement.
   *
   * <p>If stripping comments is true then any comments are removed before the splitting is
   * executed.
   */
  public SqlStatement[] generateStatements(Database database) {

    List<SqlStatement> returnStatements = new ArrayList<SqlStatement>();

    if (StringUtils.trimToNull(getSql()) == null) {
      return new SqlStatement[0];
    }

    String processedSQL = getSql().replaceAll("\r\n", "\n").replaceAll("\r", "\n");
    for (String statement :
        StringUtils.processMutliLineSQL(
            processedSQL, isStrippingComments(), isSplittingStatements(), getEndDelimiter())) {
      if (database instanceof MSSQLDatabase) {
        statement = statement.replaceAll("\n", "\r\n");
      }

      String escapedStatement;
      try {
        escapedStatement = database.getConnection().nativeSQL(statement);
      } catch (DatabaseException e) {
        escapedStatement = statement;
      }

      returnStatements.add(new RawSqlStatement(escapedStatement, getEndDelimiter()));
    }

    return returnStatements.toArray(new SqlStatement[returnStatements.size()]);
  }