Search in sources :

Example 26 with OracleDatabase

use of liquibase.database.core.OracleDatabase in project liquibase by liquibase.

the class InsertOrUpdateGenerator method getUpdateStatement.

/**
     * 
     * @param insertOrUpdateStatement
     * @param database
     * @param whereClause
     * @param sqlGeneratorChain
     * @return the update statement, if there is nothing to update return null
     */
protected String getUpdateStatement(InsertOrUpdateStatement insertOrUpdateStatement, Database database, String whereClause, SqlGeneratorChain sqlGeneratorChain) throws LiquibaseException {
    StringBuffer updateSqlString = new StringBuffer();
    UpdateGenerator update = new UpdateGenerator();
    UpdateStatement updateStatement = new UpdateStatement(insertOrUpdateStatement.getCatalogName(), insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName());
    if (!(database instanceof OracleDatabase && insertOrUpdateStatement.getOnlyUpdate() != null && insertOrUpdateStatement.getOnlyUpdate())) {
        whereClause += ";\n";
    }
    updateStatement.setWhereClause(whereClause);
    String[] pkFields = insertOrUpdateStatement.getPrimaryKey().split(",");
    HashSet<String> hashPkFields = new HashSet<String>(Arrays.asList(pkFields));
    for (String columnKey : insertOrUpdateStatement.getColumnValues().keySet()) {
        if (!hashPkFields.contains(columnKey)) {
            updateStatement.addNewColumnValue(columnKey, insertOrUpdateStatement.getColumnValue(columnKey));
        }
    }
    // this isn't very elegant but the code fails above without any columns to update
    if (updateStatement.getNewColumnValues().isEmpty()) {
        throw new LiquibaseException("No fields to update in set clause");
    }
    Sql[] updateSql = update.generateSql(updateStatement, database, sqlGeneratorChain);
    for (Sql s : updateSql) {
        updateSqlString.append(s.toSql());
        updateSqlString.append(";");
    }
    updateSqlString.deleteCharAt(updateSqlString.lastIndexOf(";"));
    updateSqlString.append("\n");
    return updateSqlString.toString();
}
Also used : OracleDatabase(liquibase.database.core.OracleDatabase) InsertOrUpdateStatement(liquibase.statement.core.InsertOrUpdateStatement) UpdateStatement(liquibase.statement.core.UpdateStatement) LiquibaseException(liquibase.exception.LiquibaseException) HashSet(java.util.HashSet) Sql(liquibase.sql.Sql) UnparsedSql(liquibase.sql.UnparsedSql)

Example 27 with OracleDatabase

use of liquibase.database.core.OracleDatabase in project liquibase by liquibase.

the class InsertOrUpdateGeneratorOracleTest method testInsertSequenceValWithSchema.

@Test
public void testInsertSequenceValWithSchema() {
    OracleDatabase database = new OracleDatabase();
    InsertGenerator generator = new InsertGenerator();
    InsertStatement statement = new InsertStatement("mycatalog", "myschema", "mytable");
    ColumnConfig columnConfig = new ColumnConfig();
    columnConfig.setValueSequenceNext(new SequenceNextValueFunction("myschema.my_seq"));
    columnConfig.setName("col3");
    statement.addColumn(columnConfig);
    Sql[] sql = generator.generateSql(statement, database, null);
    String theSql = sql[0].toSql();
    assertEquals("INSERT INTO mycatalog.mytable (col3) VALUES (\"myschema\".\"my_seq\".nextval)", theSql);
}
Also used : OracleDatabase(liquibase.database.core.OracleDatabase) ColumnConfig(liquibase.change.ColumnConfig) SequenceNextValueFunction(liquibase.statement.SequenceNextValueFunction) InsertStatement(liquibase.statement.core.InsertStatement) Sql(liquibase.sql.Sql) Test(org.junit.Test)

Example 28 with OracleDatabase

use of liquibase.database.core.OracleDatabase in project liquibase by liquibase.

the class InsertOrUpdateGeneratorOracleTest method testOnlyUpdateFlag.

@Test
public void testOnlyUpdateFlag() {
    OracleDatabase database = new OracleDatabase();
    InsertOrUpdateGeneratorOracle generator = new InsertOrUpdateGeneratorOracle();
    InsertOrUpdateStatement statement = new InsertOrUpdateStatement("mycatalog", "myschema", "mytable", "pk_col1", true);
    statement.addColumnValue("pk_col1", "value1");
    statement.addColumnValue("col2", "value2");
    Sql[] sql = generator.generateSql(statement, database, null);
    String theSql = sql[0].toSql();
    assertFalse("should not have had insert statement", theSql.contains("INSERT INTO mycatalog.mytable (pk_col1, col2) VALUES ('value1', 'value2');"));
    assertTrue("missing update statement", theSql.contains("UPDATE mycatalog.mytable"));
    String[] sqlLines = theSql.split("\n");
    int lineToCheck = 0;
    assertEquals("UPDATE mycatalog.mytable SET col2 = 'value2' WHERE pk_col1 = 'value1'", sqlLines[lineToCheck].trim());
    lineToCheck++;
    assertEquals("Wrong number of lines", 1, sqlLines.length);
}
Also used : OracleDatabase(liquibase.database.core.OracleDatabase) InsertOrUpdateStatement(liquibase.statement.core.InsertOrUpdateStatement) Sql(liquibase.sql.Sql) Test(org.junit.Test)

Example 29 with OracleDatabase

use of liquibase.database.core.OracleDatabase in project liquibase by liquibase.

the class AbstractIntegrationTest method testRerunDiffChangeLog.

@Test
public void testRerunDiffChangeLog() throws Exception {
    if (database == null) {
        return;
    }
    for (int run = 0; run < 2; run++) {
        //run once outputting data as insert, once as csv
        boolean outputCsv = run == 1;
        runCompleteChangeLog();
        SnapshotControl snapshotControl = new SnapshotControl(database);
        //todo            compareControl.setDiffData(true);
        DatabaseSnapshot originalSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, snapshotControl);
        CompareControl compareControl = new CompareControl();
        //database returns different data even if the same
        compareControl.addSuppressedField(Column.class, "defaultValue");
        //database returns different data even if the same
        compareControl.addSuppressedField(Column.class, "autoIncrementInformation");
        if (database instanceof OracleDatabase) {
            //database returns different nvarchar2 info even though they are the same
            compareControl.addSuppressedField(Column.class, "type");
        }
        DiffOutputControl diffOutputControl = new DiffOutputControl();
        File tempFile = File.createTempFile("liquibase-test", ".xml");
        deleteOnExit(tempFile);
        if (outputCsv) {
            diffOutputControl.setDataDir(new File(tempFile.getParentFile(), "liquibase-data").getCanonicalPath().replaceFirst("\\w:", ""));
        }
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(database, null, compareControl);
        FileOutputStream output = new FileOutputStream(tempFile);
        try {
            new DiffToChangeLog(diffResult, new DiffOutputControl()).print(new PrintStream(output));
            output.flush();
        } finally {
            output.close();
        }
        Liquibase liquibase = createLiquibase(tempFile.getName());
        clearDatabase(liquibase);
        DatabaseSnapshot emptySnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
        //run again to test changelog testing logic
        liquibase = createLiquibase(tempFile.getName());
        try {
            liquibase.update(this.contexts);
        } catch (ValidationFailedException e) {
            e.printDescriptiveError(System.out);
            throw e;
        }
        //            tempFile.deleteOnExit();
        DatabaseSnapshot migratedSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
        DiffResult finalDiffResult = DiffGeneratorFactory.getInstance().compare(originalSnapshot, migratedSnapshot, compareControl);
        try {
            assertTrue(finalDiffResult.areEqual());
        } catch (AssertionError e) {
            new DiffToReport(finalDiffResult, System.err).print();
            throw e;
        }
        //diff to empty and drop all
        DiffResult emptyDiffResult = DiffGeneratorFactory.getInstance().compare(emptySnapshot, migratedSnapshot, compareControl);
        output = new FileOutputStream(tempFile);
        try {
            new DiffToChangeLog(emptyDiffResult, new DiffOutputControl(true, true, true, null)).print(new PrintStream(output));
            output.flush();
        } finally {
            output.close();
        }
        liquibase = createLiquibase(tempFile.getName());
        System.out.println("updating from " + tempFile.getCanonicalPath());
        try {
            liquibase.update(this.contexts);
        } catch (LiquibaseException e) {
            throw e;
        }
        DatabaseSnapshot emptyAgainSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
        assertEquals(2, emptyAgainSnapshot.get(Table.class).size());
        assertEquals(0, emptyAgainSnapshot.get(View.class).size());
    }
}
Also used : DiffOutputControl(liquibase.diff.output.DiffOutputControl) OracleDatabase(liquibase.database.core.OracleDatabase) Liquibase(liquibase.Liquibase) ValidationFailedException(liquibase.exception.ValidationFailedException) DiffToReport(liquibase.diff.output.report.DiffToReport) CompareControl(liquibase.diff.compare.CompareControl) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DiffResult(liquibase.diff.DiffResult) LiquibaseException(liquibase.exception.LiquibaseException) SnapshotControl(liquibase.snapshot.SnapshotControl) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) Test(org.junit.Test)

Example 30 with OracleDatabase

use of liquibase.database.core.OracleDatabase in project liquibase by liquibase.

the class AddColumnGeneratorTest method isValid.

@Override
public void isValid() throws Exception {
    super.isValid();
    AddColumnStatement addPKColumn = new AddColumnStatement(null, null, TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, null, new PrimaryKeyConstraint("pk_name"));
    assertFalse(generatorUnderTest.validate(addPKColumn, new OracleDatabase(), new MockSqlGeneratorChain()).hasErrors());
    assertTrue(generatorUnderTest.validate(addPKColumn, new H2Database(), new MockSqlGeneratorChain()).getErrorMessages().contains("Cannot add a primary key column"));
    assertTrue(generatorUnderTest.validate(addPKColumn, new DB2Database(), new MockSqlGeneratorChain()).getErrorMessages().contains("Cannot add a primary key column"));
    assertTrue(generatorUnderTest.validate(addPKColumn, new DerbyDatabase(), new MockSqlGeneratorChain()).getErrorMessages().contains("Cannot add a primary key column"));
    assertTrue(generatorUnderTest.validate(addPKColumn, new SQLiteDatabase(), new MockSqlGeneratorChain()).getErrorMessages().contains("Cannot add a primary key column"));
    assertTrue(generatorUnderTest.validate(new AddColumnStatement(null, null, null, null, null, null, new AutoIncrementConstraint()), new MySQLDatabase(), new MockSqlGeneratorChain()).getErrorMessages().contains("Cannot add a non-primary key identity column"));
    assertTrue(generatorUnderTest.validate(new AddColumnStatement(null, null, null, null, null, null, new AutoIncrementConstraint()), new MySQLDatabase(), new MockSqlGeneratorChain()).getErrorMessages().contains("Cannot add a non-primary key identity column"));
    assertTrue(generatorUnderTest.validate(new AddColumnStatement(new AddColumnStatement(null, null, TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, null), new AddColumnStatement(null, null, "other_table", "other_column", COLUMN_TYPE, null)), new MySQLDatabase(), new MockSqlGeneratorChain()).getErrorMessages().contains("All columns must be targeted at the same table"));
}
Also used : OracleDatabase(liquibase.database.core.OracleDatabase) DB2Database(liquibase.database.core.DB2Database) AutoIncrementConstraint(liquibase.statement.AutoIncrementConstraint) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DerbyDatabase(liquibase.database.core.DerbyDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) H2Database(liquibase.database.core.H2Database) AddColumnStatement(liquibase.statement.core.AddColumnStatement) PrimaryKeyConstraint(liquibase.statement.PrimaryKeyConstraint) MockSqlGeneratorChain(liquibase.sqlgenerator.MockSqlGeneratorChain)

Aggregations

OracleDatabase (liquibase.database.core.OracleDatabase)31 Test (org.junit.Test)11 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)9 DB2Database (liquibase.database.core.DB2Database)8 MySQLDatabase (liquibase.database.core.MySQLDatabase)7 Change (liquibase.change.Change)6 ArrayList (java.util.ArrayList)5 Database (liquibase.database.Database)5 H2Database (liquibase.database.core.H2Database)4 Sql (liquibase.sql.Sql)4 HashSet (java.util.HashSet)3 PostgresDatabase (liquibase.database.core.PostgresDatabase)3 DatabaseException (liquibase.exception.DatabaseException)3 LiquibaseException (liquibase.exception.LiquibaseException)3 IOException (java.io.IOException)2 CatalogAndSchema (liquibase.CatalogAndSchema)2 ColumnConfig (liquibase.change.ColumnConfig)2 AddPrimaryKeyChange (liquibase.change.core.AddPrimaryKeyChange)2 AddUniqueConstraintChange (liquibase.change.core.AddUniqueConstraintChange)2 CreateViewChange (liquibase.change.core.CreateViewChange)2