16 Temmuz 2021 Cuma

SpringData Liquibase

Giriş
Birden fazla veri tabanını migrate etmek istersek Flyway yetersiz. Liquibase gerekiyor. Açıklaması şöyle
Liquibase facilitates database migrations with database-agnostic formats including XML, YAML, and JSON. When we use non-SQL formats for database migrations, Liquibase generates the database-specific SQL for us. It also supports plain old SQL scripts. Liquibase takes care of variations in data types and SQL syntax for different databases.
Açıklaması şöyle
When you deploy changes, Liquibase creates/updates two tables in your database: DATABASECHANGELOG and DATABASECHANGELOGLOCK.

Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.liquibase</groupId>
  <artifactId>liquibase-core</artifactId>
  <version>${liquibase.version}</version>
</dependency>
application.properties
Bu dosyada master change log belirtilir. Master change log içinde diğer change log'lar yazılır. changelog içinde "change set" dosyaları bulunur

Örnek - master change log
Şöyle yaparız
spring:
  liquibase:
    change-log: classpath:/db/changelog/db.changelog-master.xml
    enabled: true
Örnek
Şöyle yaparız
spring:
  datasource:
    hikari:
      connectionTimeout: 20000
      maximumPoolSize: 2
      connectionTestQuery: SELECT 1
    url: jdbc:postgresql://localhost:5432/liquibase_demo_db
    username: postgres
    password: postgres
    driverClassName: org.postgresql.Driver
  liquibase:
    change-log: db/changelog/changelog.yaml
    enabled: true
changelog.yaml şöyledir. Buradaki AT-01-initial.sql ile bir tablo yaratırız. AT-02-alter-table.sql ile bir tabloda değişiklik yaparız
databaseChangeLog:
  - include:
       file: db/changelog/AT-01-initial.sql
  - include:
       file: db/changelog/AT-02-alter-table.sql
Eğer istersek change log dosyaları yerine her şeyi master change log içinde de yapabiliriz. Ancak bence bu tercih edilmemeli. Şöyle yaparız
- changeSet:
    id: 1
    author: leo
    tagDatabase:
      tag: v1
    changes:
      - createTable:
          tableName: one_more_test_table
          columns:
            - column:
                name: id
                type: int
                autoIncrement: true
                constraints:
                  primaryKey: true
                  nullable: false
            - column:
                name: name
                type: varchar(50)
- changeSet:
    id: 2
    author: leo
    tagDatabase:
      tag: v2
    changes:
      - addColumn:
          tableName: one_more_test_table
          columns:
            - column:
                name: age
                type: int
    rollback:
      - dropColumn:
          tableName: one_more_test_table
          columns:
            - column:
                name: age
Change Log Dosyaları
Örnek - db.changelog.xml
Şöyle yaparız. Burada tablo yoksa yaratma gösteriliyor.
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.1.xsd">

  <changeSet author="asadganiev" id="create-user-table">
    <preConditions onFail="MARK_RAN">
      <not>
       <tableExists tableName="users"/>
      </not>
    </preConditions>

    <createTable tableName="users">
      <column name="id" type="bigint" autoIncrement="true">
        <constraints primaryKey="true" nullable="false"/>
      </column>
      <column name="username" type="varchar(50)">
        <constraints unique="true" nullable="false"/>
      </column>
      <column name="email" type="varchar(50)">
        <constraints unique="true" nullable="false"/>
      </column>
      <column name="password" type="varchar(64)">
        <constraints nullable="false"/>
      </column>
      <column name="first_name" type="varchar(50)">
        <constraints nullable="false"/>
      </column>
      <column name="last_name" type="varchar(50)">
        <constraints nullable="true"/>
      </column>
      <column name="phone_number" type="varchar(13)">
        <constraints nullable="true"/>
      </column>
    </createTable>
  </changeSet>
</databaseChangeLog>
Örnek
Şöyle yaparız
//base for database migrations
@Slf4j
public class BaseDatabaseMigration {
  protected void migrateFlyway(String folder, DataSource ds) {
    try {
      // Create the Flyway instance and point it to the database
      Flyway flyway = Flyway.configure()
        .baselineOnMigrate(true) //required because of existing objects
        .dataSource(ds)
        .locations("db/"+folder)
        .load();
      // Start the migration
      flyway.migrate();   
            
    } catch (Exception e) {
      log.error("failed to migrate db (Flyway): "+folder, e);
      //need to stop the app
      System.exit(1);
    }
  }
  protected void migrateLiquibase(String folder, String schema, Connection con) {
    try {
      // Create the Liquibase Database and update
      Database database = DatabaseFactory.getInstance()
        .findCorrectDatabaseImplementation(new JdbcConnection(con));
      database.setDefaultSchemaName(schema);
      Liquibase liquibase = new 
        liquibase.Liquibase("db/"+folder+"/db.changelog-master.xml",
new ClassLoaderResourceAccessor(), database);
      liquibase.update(new Contexts(), new LabelExpression());
    } catch (Exception e) {
      log.error("failed to migrate db (Liquibase): "+folder, e);           
      //need to stop the app
      System.exit(1);
    }
  }   
}
lquibase komutu
Örnek - rollback
Şöyle yaparız
liquibase 
  -url=jdbc:postgresql://localhost:5432/liquibase_demo_db 
  -changeLogFile=db/changelog/changelog.yml 
  rollback v1


Hiç yorum yok:

Yorum Gönder