Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Liquibase, how to set default schema programmatically in Java

I am trying to run Liquibase in my appliction code. The problem is that new table ale created in public schema, how can I point liquibase to different schema in my Postgres.

    Liquibase liquibase = null;
    Connection connection = null;
    try {

        connection = DB.getConnection();
        liquibase = new Liquibase(CHANGELOG_FILE, new FileSystemResourceAccessor(), new JdbcConnection(connection));

        //change default schema here

        liquibase.update(STAGE);

    } catch (LiquibaseException e) {

    } finally {
        if (connection != null) {
            try {
                connection.rollback();
                connection.close();
            } catch (SQLException e) {

            }
        }
    }
like image 554
Kamil Grabowski Avatar asked Feb 09 '23 23:02

Kamil Grabowski


2 Answers

You can specify the schema in the changeset using schemaName attribute. So you don't need to write it programaticaly.

Here you can review official documentation for every refactor/changeset you can do. Take a while and see how you can specify what schema is the target for every refactor.

For example, add column changeset:

<changeSet author="liquibase-docs" id="addColumn-example">
  <addColumn catalogName="cat"
        schemaName="public"
        tableName="person">
    <column name="address" type="varchar(255)"/>
  </addColumn>
</changeSet>
like image 90
malaguna Avatar answered Feb 11 '23 14:02

malaguna


This can be done using the liqubase.database.Database::setDefaultSchema method. For example:

        val dbUrl = "jdbc:h2:~/aviary-db/dev;MODE=MySQL;DATABASE_TO_UPPER=false;IGNORECASE=TRUE;INIT=create schema if not exists aviary;DB_CLOSE_DELAY=-1;TRACE_LEVEL_SYSTEM_OUT=2"
        Connection conn = DriverManager.getConnection(dbUrl, user, password)
        val dbConnection = JdbcConnection(conn)
        val database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(dbConnection)
        database.defaultSchemaName = "schema_name"
        val liquibase = Liquibase("db/db-changelog.xml", ClassLoaderResourceAccessor(), database)
        liquibase.update("")

It's also worth noting that you can use setLiquibaseSchemaName to decide which schema liquibase will use for it's internal tables databasechangelog and databasechangeloglock.

like image 36
jasiek.miko Avatar answered Feb 11 '23 16:02

jasiek.miko