Enterprise Java

Creating PostgreSQL Schema Before Liquibase Execution

1. Enhancing PostgreSQL Schema Management

In PostgreSQL database management, organizing database entities into separate schemas is a best practice for maintaining clarity and security in multi-tenant or large-scale applications. While PostgreSQL defaults to the public schema, this can become cluttered in complex systems. This article explores how to leverage Liquibase, a database schema migration tool, to manage database changes within a custom schema and tackle the challenge of how to create a Java PostgreSQL schema before Liquibase execution. Moreover, we’ll demonstrate these concepts using a simple Spring Boot application connected to a PostgreSQL database.

2. Java Spring Boot Application Setup with Liquibase for PostgreSQL Schema Evolution

Liquibase is a powerful open-source tool designed for managing database schema changes in a flexible and efficient manner. It supports various database platforms, including PostgreSQL, and provides developers with a declarative approach to version control and execute database changes.

To integrate Liquibase into your Spring Boot project for managing PostgreSQL schema changes, Begin by setting up a Spring Boot application with Liquibase for managing database migrations. Ensure Liquibase is included as a dependency in your pom.xml (for Maven) or build.gradle (for Gradle) file.

Add the following dependency to your pom.xml file within the <dependencies> section:

<dependency>
    <groupId>org.liquibase</groupId>
    <artifactId>liquibase-core</artifactId>
    <version>4.8.0</version> <!-- Replace with the latest version -->
</dependency>

Add the following dependency to your build.gradle file under the dependencies block:

implementation 'org.liquibase:liquibase-core:4.8.0' // Replace with the latest version

After adding the Liquibase dependency, you can start utilizing Liquibase within your Java project to manage PostgreSQL schema changes effectively.

3. Operating Liquibase Within a Custom PostgreSQL Schema

To use a custom schema with Liquibase in a Spring Boot application:

3.1. Define PostgreSQL Schema in Change Sets

Explicitly specify the schema name in your Liquibase changelog YAML file db.changelog-master.yaml for all database objects and migrations.

  - changeSet:
      id: 1
      author: assar
      schemaName: my_schema
      changes:
        - createTable:
            tableName: item
            columns:
              - column:
                  name: id
                  type: UUID
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: name
                  type: varchar(255)
              - column:
                  name: unit_price
                  type: decimal(19,2)

3.2. Configuring Liquibase in Spring Boot for Custom Schema Operations

Update your application.properties or application.yml to specify the default schema for Liquibase operations.

spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.yaml
spring.liquibase.default-schema=my_schema

3.3. Executing Liquibase Commands in a Custom Schema Context

When running Liquibase commands within your Spring Boot application, ensure the specified schema is considered.

For example, using the Liquibase Maven plugin:

mvn liquibase:update

4. Create Java PostgreSQL Schema Before Liquibase Execution

To create the target Java PostgreSQL schema before Liquibase attempts to apply changes, integrate schema creation into your Spring Boot application setup process.

Using Spring Boot’s ApplicationRunner or CommandLineRunner, execute the following SQL script on application startup to create the desired schema:

CREATE SCHEMA IF NOT EXISTS my_schema;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class SchemaInitializer implements ApplicationRunner {

    private final JdbcTemplate jdbcTemplate;

    public SchemaInitializer(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        jdbcTemplate.execute("CREATE SCHEMA IF NOT EXISTS my_schema");
    }

5. Conclusion

By leveraging Liquibase within a Spring Boot application and incorporating a custom schema, you can effectively manage PostgreSQL database schema changes. The integration enhances database organization and supports scalability and security in your Spring Boot applications. Ensure schema creation scripts are part of your deployment pipeline to maintain consistency and reliability in database migrations with Liquibase.

Ashraf Sarhan

With over 8 years of experience in the field, I have developed and maintained large-scale distributed applications for various domains, including library, audio books, and quant trading. I am passionate about OpenSource, CNCF/DevOps, Microservices, and BigData, and I constantly seek to learn new technologies and tools. I hold two Oracle certifications in Java programming and business component development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button