Liquibase, how to set default schema programmatically in Java

14,746

Solution 1

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>

Solution 2

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.

Share:
14,746
Kamil Grabowski
Author by

Kamil Grabowski

Updated on June 18, 2022

Comments

  • Kamil Grabowski
    Kamil Grabowski almost 2 years

    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) {
    
                }
            }
        }