Multi Tenant Database Migration with Liquibase

Hey guys,

I’m developing a SaaS and I want to use the Schema-per-Tenant pattern, I read that Liquibase provided this support, I just don’t know how to run the changelog in the newly created schema. Does the the code below is the best approach? Could anyone help?

 public void runLiquibase(String schema) throws Exception {
        Map<String, Object> scopeValues = new HashMap<>();
        Scope.child(scopeValues, () -> {
            try (Connection connection = dataSource.getConnection()) {
                Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
                database.setDefaultSchemaName(schema);
                Liquibase liquibase = new Liquibase("db/db.changelog-tenant.yaml", new ClassLoaderResourceAccessor(), database);
                liquibase.update(""); // This will update the database to the latest changelog version
            } catch (Exception e) {
                // Handle exceptions
                throw new RuntimeException("Error running Liquibase", e);
            }
        });
    }

I improved the code above with:

    public void runLiquibase(String schema) {
        LOG.info(String.format("Running Liquibase for the new schema: %s", schema));
        try (Connection connection = dataSource.getConnection()) {
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            database.setDefaultSchemaName(schema);
            Liquibase liquibase = new Liquibase("db/db.changelog-tenant.yaml", new ClassLoaderResourceAccessor(), database);
            liquibase.update(new Contexts(), new LabelExpression());
            LOG.info(String.format("Liquibase update complete for schema: %s", schema));
        } catch (SQLException | LiquibaseException e) {
            LOG.error(String.format("Error running Liquibase for schema [%s]: %s", schema, e.getMessage()));
            throw new LiquibaseExecutionException("Error running Liquibase", e);
        }
    }