Java Code Examples for liquibase.exception.LiquibaseException

The following examples show how to use liquibase.exception.LiquibaseException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jweb-cms   Source File: Launcher.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void start() {
    try {
        if (isMigrationNeeded()) {
            migrate();
        }
    } catch (LiquibaseException | SQLException e) {
        throw new ApplicationException("failed to migrate database", e);
    }
    app = new UndertowApp(dir);
    ServiceLoader<AbstractModule> modules = ServiceLoader.load(AbstractModule.class);
    for (AbstractModule module : modules) {
        app.install(module);
    }

    app.start();
}
 
Example 2
@Override
public void execute(final SqlStatement[] statements, final List<SqlVisitor> sqlVisitors) throws LiquibaseException {
    for (SqlStatement statement : statements) {
        if (statement.skipOnUnsupported() && !SqlGeneratorFactory.getInstance().supports(statement, this)) {
            continue;
        }
        LogService.getLog(getClass()).debug(LogType.LOG, "Executing Statement: " + statement);
        try {
            ExecutorService.getInstance().getExecutor(this).execute(statement, sqlVisitors);
        } catch (DatabaseException e) {
            if (statement.continueOnError()) {
                LogService.getLog(getClass()).severe(LogType.LOG, "Error executing statement '" + statement.toString() + "', but continuing", e);
            } else {
                throw e;
            }
        }
    }
}
 
Example 3
Source Project: expper   Source File: AsyncSpringLiquibase.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws LiquibaseException {
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_HEROKU)) {
        taskExecutor.execute(() -> {
            try {
                log.warn("Starting Liquibase asynchronously, your database might not be ready at startup!");
                initDb();
            } catch (LiquibaseException e) {
                log.error("Liquibase could not start correctly, your database is NOT ready: {}", e.getMessage(), e);
            }
        });
    } else {
        log.debug("Starting Liquibase synchronously");
        initDb();
    }
}
 
Example 4
Source Project: trellis   Source File: DBTestUtils.java    License: Apache License 2.0 6 votes vote down vote up
static EmbeddedPostgres setupDatabase(final String directory) {
    try {
        final EmbeddedPostgres pg = EmbeddedPostgres.builder()
            .setDataDirectory(directory + separator + "pgdata-" + new RandomStringGenerator
                        .Builder().withinRange('a', 'z').build().generate(10)).start();

        // Set up database migrations
        try (final Connection c = pg.getPostgresDatabase().getConnection()) {
            final Liquibase liquibase = new Liquibase("org/trellisldp/jdbc/migrations.yml",
                    new ClassLoaderResourceAccessor(),
                    new JdbcConnection(c));
            final Contexts ctx = null;
            liquibase.update(ctx);
        }
        return pg;
    } catch (final IOException | SQLException | LiquibaseException ex) {
        LOGGER.error("Error setting up tests", ex);
    }
    return null;
}
 
Example 5
@Override
public void afterPropertiesSet() throws LiquibaseException {
    if (!env.acceptsProfiles(Constants.SPRING_PROFILE_NO_LIQUIBASE)) {
        if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_HEROKU)) {
            taskExecutor.execute(() -> {
                try {
                    log.warn("Starting Liquibase asynchronously, your database might not be ready at startup!");
                    initDb();
                } catch (LiquibaseException e) {
                    log.error("Liquibase could not start correctly, your database is NOT ready: {}", e.getMessage(), e);
                }
            });
        } else {
            log.debug("Starting Liquibase synchronously");
            initDb();
        }
    } else {
        log.debug("Liquibase is disabled");
    }
}
 
Example 6
@Override
public void afterPropertiesSet() throws LiquibaseException {
    if (!env.acceptsProfiles(Constants.SPRING_PROFILE_NO_LIQUIBASE)) {
        if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_HEROKU)) {
            taskExecutor.execute(() -> {
                try {
                    log.warn("Starting Liquibase asynchronously, your database might not be ready at startup!");
                    initDb();
                } catch (LiquibaseException e) {
                    log.error("Liquibase could not start correctly, your database is NOT ready: {}", e.getMessage(), e);
                }
            });
        } else {
            log.debug("Starting Liquibase synchronously");
            initDb();
        }
    } else {
        log.debug("Liquibase is disabled");
    }
}
 
Example 7
@Override
public void afterPropertiesSet() throws LiquibaseException {
    if (!env.acceptsProfiles(Constants.SPRING_PROFILE_NO_LIQUIBASE)) {
        if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_HEROKU)) {
            taskExecutor.execute(() -> {
                try {
                    log.warn("Starting Liquibase asynchronously, your database might not be ready at startup!");
                    initDb();
                } catch (LiquibaseException e) {
                    log.error("Liquibase could not start correctly, your database is NOT ready: {}", e.getMessage(), e);
                }
            });
        } else {
            log.debug("Starting Liquibase synchronously");
            initDb();
        }
    } else {
        log.debug("Liquibase is disabled");
    }
}
 
Example 8
@Override
public void afterPropertiesSet() throws LiquibaseException {
    if (!env.acceptsProfiles(Constants.SPRING_PROFILE_NO_LIQUIBASE)) {
        if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_HEROKU)) {
            taskExecutor.execute(() -> {
                try {
                    log.warn("Starting Liquibase asynchronously, your database might not be ready at startup!");
                    initDb();
                } catch (LiquibaseException e) {
                    log.error("Liquibase could not start correctly, your database is NOT ready: {}", e.getMessage(), e);
                }
            });
        } else {
            log.debug("Starting Liquibase synchronously");
            initDb();
        }
    } else {
        log.debug("Liquibase is disabled");
    }
}
 
Example 9
Source Project: OpenIoE   Source File: AsyncSpringLiquibase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws LiquibaseException {
    if (!env.acceptsProfiles(Constants.SPRING_PROFILE_NO_LIQUIBASE)) {
        if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_HEROKU)) {
            taskExecutor.execute(() -> {
                try {
                    log.warn("Starting Liquibase asynchronously, your database might not be ready at startup!");
                    initDb();
                } catch (LiquibaseException e) {
                    log.error("Liquibase could not start correctly, your database is NOT ready: {}", e.getMessage(), e);
                }
            });
        } else {
            log.debug("Starting Liquibase synchronously");
            initDb();
        }
    } else {
        log.debug("Liquibase is disabled");
    }
}
 
Example 10
@Before
public void resetDB() throws SQLException, LiquibaseException {
    // We call resetDB to return it back to it's vanilla state
    roomDB.resetDB();

    // We then create a Room object to send to the roomDB
    Room room = new Room(101,
            "Twin",
            false,
            "https://www.mwtestconsultancy.co.uk/img/room1.jpg",
            "Aenean porttitor mauris sit amet lacinia molestie",
            new String[]{"Wifi", "TV", "Safe"},
            100);

    // With the room created we can send it to the RoomDB to be created
    Room createdRoom = roomDB.create(room);

    // Finally we need the current room ID to use in our tests
    // so we save it currentRoomId
    currentRoomId = createdRoom.getRoomid();
}
 
Example 11
@Before
public void resetDb() throws SQLException, LiquibaseException {
    // We call resetDB to return it back to it's vanilla state
    bookingDB.resetDB();

    // We then create a new Booking using the data builder pattern
    Booking booking = new Booking.BookingBuilder()
            .setRoomid(1)
            .setFirstname("James")
            .setLastname("Dean")
            .setDepositpaid(true)
            .setCheckin(LocalDate.of(2018, Month.FEBRUARY, 26))
            .setCheckout(LocalDate.of(2018, Month.FEBRUARY, 26))
            .build();

    // With the booking created we can send it to the BookingDb to be created
    CreatedBooking createdBooking = bookingDB.create(booking);

    // Finally we need the current booking ID to use in our tests
    // so we save it currentBookingId
    currentBookingId = createdBooking.getBookingid();
}
 
Example 12
Source Project: attic-polygene-java   Source File: LiquibaseService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void applyChangelog( Map<String, Object> parameters )
    throws SQLException, LiquibaseException
{
    Liquibase liquibase = null;
    try
    {
        liquibase = newConnectedLiquibase();
        for( Map.Entry<String, Object> entry : parameters.entrySet() )
        {
            liquibase.getChangeLogParameters().set( entry.getKey(), entry.getValue() );
        }
        liquibase.update( config.get().contexts().get() );
    }
    finally
    {
        if( liquibase != null )
        {
            liquibase.getDatabase().close();
        }
    }
}
 
Example 13
Source Project: hmdm-server   Source File: AbstractLiquibaseModule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Configures this module. Applies the recent changes from the {@link #getChangeLogResourcePath()} change log to
 * database.</p>
 */
protected final void configure() {
    try (Connection connection = this.getConnection()) {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        Liquibase liquibase = new Liquibase(getChangeLogResourcePath(), getResourceAccessor(), database);
        String usageScenario = this.context.getInitParameter("usage.scenario");
        String contexts = getContexts(usageScenario);
        liquibase.update(contexts);
    } catch (LiquibaseException | SQLException e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 14
Source Project: quarkus   Source File: LiquibaseProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds all resource files for the given change log file
 */
private Set<String> findAllChangeLogs(String file, ChangeLogParserFactory changeLogParserFactory,
        ClassLoaderResourceAccessor classLoaderResourceAccessor,
        ChangeLogParameters changeLogParameters) {
    try {
        ChangeLogParser parser = changeLogParserFactory.getParser(file, classLoaderResourceAccessor);
        DatabaseChangeLog changelog = parser.parse(file, changeLogParameters, classLoaderResourceAccessor);

        if (changelog != null) {
            Set<String> result = new LinkedHashSet<>();
            // get all changeSet files
            for (ChangeSet changeSet : changelog.getChangeSets()) {
                result.add(changeSet.getFilePath());

                // get all parents of the changeSet
                DatabaseChangeLog parent = changeSet.getChangeLog();
                while (parent != null) {
                    result.add(parent.getFilePath());
                    parent = parent.getParentChangeLog();
                }
            }
            result.add(changelog.getFilePath());
            return result;
        }
    } catch (LiquibaseException ex) {
        throw new IllegalStateException(ex);
    }
    return Collections.emptySet();
}
 
Example 15
Source Project: attic-polygene-java   Source File: SQLEntityStoreMixin.java    License: Apache License 2.0 5 votes vote down vote up
private void applyLiquibaseChangelog( SQLDialect dialect ) throws SQLException, LiquibaseException
{
    Liquibase liquibase = liquibaseService.newConnectedLiquibase();
    Database db = liquibase.getDatabase();
    db.setObjectQuotingStrategy( ObjectQuotingStrategy.QUOTE_ALL_OBJECTS );
    try
    {
        if( !dialect.equals( SQLDialect.SQLITE ) )
        {
            if( db.supportsSchemas() )
            {
                db.setDefaultSchemaName( schema.getName() );
                db.setLiquibaseSchemaName( schema.getName() );
            }
            if( db.supportsCatalogs() )
            {
                db.setDefaultCatalogName( schema.getName() );
                db.setLiquibaseCatalogName( schema.getName() );
            }
        }
        liquibase.getChangeLogParameters().set( TABLE_NAME_LIQUIBASE_PARAMETER, table.getName() );
        liquibase.update( new Contexts() );
    }
    finally
    {
        db.close();
    }
}
 
Example 16
Source Project: jweb-cms   Source File: Launcher.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean isMigrationNeeded() throws SQLException, LiquibaseException {
    App app = new App(dir);
    DataSource dataSource = new DataSourceFactory(app.options("database", DatabaseOptions.class)).setDir(dir).build();
    try (Connection connection = dataSource.getConnection()) {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        Liquibase liquibase = new Liquibase("conf/db/change-logs.yml", new ClassLoaderResourceAccessor(), database);
        return !liquibase.tagExists("0.9.0");
    }
}
 
Example 17
Source Project: jweb-cms   Source File: Launcher.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public void migrate() throws SQLException, LiquibaseException {
    logger.info("migrating database");
    App app = new App(dir);
    DataSource dataSource = new DataSourceFactory(app.options("database", DatabaseOptions.class)).setDir(dir).build();
    try (Connection connection = dataSource.getConnection()) {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        Liquibase liquibase = new Liquibase("conf/db/change-logs.yml", new ClassLoaderResourceAccessor(), database);
        liquibase.update("");
        liquibase.tag("0.9.0");
    }
}
 
Example 18
@Override
public void saveRollbackStatement(final Change change, final List<SqlVisitor> sqlVisitors, final Writer writer) throws IOException, LiquibaseException {
    SqlStatement[] statements = change.generateRollbackStatements(this);
    for (SqlStatement statement : statements) {
        for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, this)) {
            writer.append(sql.toSql()).append(sql.getEndDelimiter()).append("\n\n");
        }
    }
}
 
Example 19
Source Project: jweb-cms   Source File: Main.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws LiquibaseException, SQLException, IOException, ParserConfigurationException {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mysql://localhost:3306/main?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUsername("root");

    java.sql.Connection connection = dataSource.getConnection();
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
    Liquibase liquibase = new Liquibase("db-changes.yml", new ClassLoaderResourceAccessor(), database);

    CatalogAndSchema catalogAndSchema = new CatalogAndSchema(null, "main");
    DiffToChangeLog changeLog = new DiffToChangeLog(new DiffOutputControl(false, false, true, null));

    liquibase.generateChangeLog(catalogAndSchema, changeLog, new PrintStream(new FileOutputStream("./change-logs.yml")), new YamlChangeLogSerializer(), snapTypes());
}
 
Example 20
Source Project: airsonic   Source File: SpringLiquibase.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws LiquibaseException {
    LOG.trace("Starting Liquibase Update");
    try {
        super.afterPropertiesSet();
    } catch (Exception e) {
        LOG.error("===============================================");
        LOG.error("An exception occurred during database migration");
        LOG.error("A rollback file has been generated at " + rollbackFile);
        LOG.error("Execute it within your database to rollback any changes");
        LOG.error("The exception is as follows\n", e);
        LOG.error("===============================================");
        throw(e);
    }
}
 
Example 21
@Override
public Sql[] generateSql(MarkChangeSetRanStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();

    SqlStatement runStatement;
    try {
        if (statement.getExecType().equals(ChangeSet.ExecType.FAILED) || statement.getExecType().equals(ChangeSet.ExecType.SKIPPED)) {
            return new Sql[0]; //don't mark
        }

        String tag = null;
        for (Change change : changeSet.getChanges()) {
            if (change instanceof TagDatabaseChange) {
                TagDatabaseChange tagChange = (TagDatabaseChange) change;
                tag = tagChange.getTag();
            }
        }

        runStatement = new HiveInsertStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName())
                .addColumnValue(changeSet.getId())
                .addColumnValue(changeSet.getAuthor())
                .addColumnValue(changeSet.getFilePath())
                .addColumnValue(DateTimeUtils.getCurrentTS("yyyy-MM-dd HH:mm:ss"))
                .addColumnValue(ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getNextSequenceValue())
                .addColumnValue(statement.getExecType().value)
                .addColumnValue(changeSet.generateCheckSum().toString())
                .addColumnValue(changeSet.getDescription())
                .addColumnValue(StringUtils.trimToEmpty(changeSet.getComments()))
                .addColumnValue(tag == null ? "NULL" : tag)
                .addColumnValue(ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getDeploymentId())
                .addColumnValue(changeSet.getContexts() == null || changeSet.getContexts().isEmpty() ? null : changeSet.getContexts().toString())
                .addColumnValue(changeSet.getLabels() == null || changeSet.getLabels().isEmpty() ? null : changeSet.getLabels().toString())
                .addColumnValue(LiquibaseUtil.getBuildVersion());
    } catch (LiquibaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }

    return SqlGeneratorFactory.getInstance().generateSql(runStatement, database);
}
 
Example 22
private boolean hasDatabaseChangeLogTable() throws DatabaseException {
    if (hasDatabaseChangeLogTable == null) {
        try {
            hasDatabaseChangeLogTable = SnapshotGeneratorFactory.getInstance().hasDatabaseChangeLogTable(getDatabase());
        } catch (LiquibaseException e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }
    return hasDatabaseChangeLogTable;
}
 
Example 23
@Override
public int getNextSequenceValue() throws LiquibaseException {
    if (lastChangeSetSequenceValue == null) {
        if (getDatabase().getConnection() == null) {
            lastChangeSetSequenceValue = 0;
        } else {
            lastChangeSetSequenceValue = ExecutorService.getInstance().getExecutor(getDatabase()).queryForInt(new GetNextChangeSetSequenceValueStatement());
        }
    }

    return ++lastChangeSetSequenceValue;
}
 
Example 24
Source Project: expper   Source File: AsyncSpringLiquibase.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected void initDb() throws LiquibaseException {
    StopWatch watch = new StopWatch();
    watch.start();
    super.afterPropertiesSet();
    watch.stop();
    log.debug("Started Liquibase in {} ms", watch.getTotalTimeMillis());
}
 
Example 25
Source Project: liquibase-impala   Source File: ImpalaDatabase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SqlStatement[] statements, List<SqlVisitor> sqlVisitors) throws LiquibaseException {
    if (syncDdl) {
        List<SqlStatement> sqlStatementList = new ArrayList<SqlStatement>();
        sqlStatementList.add(UserSessionSettings.syncDdlStart());
        sqlStatementList.addAll(Arrays.asList(statements));
        sqlStatementList.add(UserSessionSettings.syncDdlStop());
        SqlStatement[] wrappedStatements = new SqlStatement[sqlStatementList.size()];
        sqlStatementList.toArray(wrappedStatements);
        super.execute(wrappedStatements, sqlVisitors);
    } else {
        super.execute(statements, sqlVisitors);
    }
}
 
Example 26
@Override
public void subscribeTenant(final String tenantId) {
    String defaultSchemaName;
    try {
        Validate.isTrue(isValidTenantId(tenantId), String.format("Invalid tenant id: \"%s\"", tenantId));
        final String schemaName = TenantUtil.createSchemaName(tenantId);

        final Connection connection = dataSource.getConnection();
        final Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        try (Statement statement = connection.createStatement()) {
            statement.execute(String.format("CREATE SCHEMA IF NOT EXISTS \"%s\"", schemaName));
            connection.commit();

            defaultSchemaName = database.getDefaultSchemaName();
            database.setDefaultSchemaName(schemaName);

            final String filePath = LIQUIBASE_PATH;
            final Liquibase liquibase = new liquibase.Liquibase(filePath,
                    new ClassLoaderResourceAccessor(), database);

            liquibase.update(new Contexts(), new LabelExpression());
            database.setDefaultSchemaName(defaultSchemaName);
        }

    } catch (SQLException | LiquibaseException | IllegalArgumentException e) {
        final BadRequestException badRequestException = new BadRequestException();
        logger.error("Tenant subscription failed for {}.", tenantId, e);
        throw badRequestException;
    }
}
 
Example 27
protected void initDb() throws LiquibaseException {
    StopWatch watch = new StopWatch();
    watch.start();
    super.afterPropertiesSet();
    watch.stop();
    log.debug("Started Liquibase in {} ms", watch.getTotalTimeMillis());
}
 
Example 28
protected void initDb() throws LiquibaseException {
    StopWatch watch = new StopWatch();
    watch.start();
    super.afterPropertiesSet();
    watch.stop();
    log.debug("Started Liquibase in {} ms", watch.getTotalTimeMillis());
}
 
Example 29
protected void initDb() throws LiquibaseException {
    StopWatch watch = new StopWatch();
    watch.start();
    super.afterPropertiesSet();
    watch.stop();
    log.debug("Started Liquibase in {} ms", watch.getTotalTimeMillis());
}
 
Example 30
protected void initDb() throws LiquibaseException {
    StopWatch watch = new StopWatch();
    watch.start();
    super.afterPropertiesSet();
    watch.stop();
    log.debug("Started Liquibase in {} ms", watch.getTotalTimeMillis());
}