The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

Usando o Flyway

Flyway é uma ferramenta popular de migração de banco de dados que é comumente usada em ambientes JVM.

O Quarkus oferece suporte de primeira classe para o uso do Flyway, como será explicado neste guia.

Configurando o suporte para o Flyway

Conforme mostrado na seção Desenvolvendo com o Flyway , para começar a usar o Flyway com seu projeto, você só precisa:

  • adicione suas migrações à pasta src/main/resources/db/migration como o você normalmente faz com o Flyway

  • ative a opção migrate-at-start para migrar o esquema automaticamente ou injete o objeto Flyway e execute sua migração como você normalmente faz

Em seu arquivo de build, adicione as seguintes dependências:

  • a extensão Flyway

  • sua extensão de driver JDBC ( quarkus-jdbc-postgresql , quarkus-jdbc-h2 , quarkus-jdbc-mariadb , …​)

  • unless you’re using in-memory or file databases (such as H2 or SQLite), you need to add a flyway module dependency corresponding to the database you’re using. (for more details)

pom.xml
<!-- Flyway specific dependencies -->
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-flyway</artifactId>
</dependency>

<!-- JDBC driver dependencies -->
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>

<!-- Flyway SQL Server specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-sqlserver</artifactId>
</dependency>

<!-- Flyway MariaDB/MySQL specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-mysql</artifactId>
</dependency>

<!-- Flyway Oracle specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-oracle</artifactId>
</dependency>

<!-- Flyway PostgreSQL specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-postgresql</artifactId>
</dependency>

<!-- Flyway DB2 specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-db2</artifactId>
</dependency>

<!-- Derby specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-derby</artifactId>
</dependency>

<!-- HSQLDB specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-hsqldb</artifactId>
</dependency>

<!-- Informix specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-informix</artifactId>
</dependency>

<!-- Redshift specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-redshift</artifactId>
</dependency>

<!-- Saphana specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-saphana</artifactId>
</dependency>

<!-- Snowflake specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-snowflake</artifactId>
</dependency>

<!-- Sybasease specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-database-sybasease</artifactId>
</dependency>

<!-- Firebird specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-firebird</artifactId>
</dependency>

<!-- BigQuery specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-gcp-bigquery</artifactId>
</dependency>

<!-- Spanner specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-gcp-spanner</artifactId>
</dependency>

<!-- Singlestore specific dependencies -->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-singlestore</artifactId>
</dependency>
build.gradle
// Flyway specific dependencies
implementation("io.quarkus:quarkus-flyway")
// JDBC driver dependencies
implementation("io.quarkus:quarkus-jdbc-postgresql")
// Flyway SQL Server specific dependencies
implementation("org.flywaydb:flyway-sqlserver")
// Flyway MariaDB/MySQL specific dependencies
implementation("org.flywaydb:flyway-mysql")
// Flyway Oracle specific dependencies
implementation("org.flywaydb:flyway-database-oracle")
// Flyway PostgreSQL specific dependencies
implementation("org.flywaydb:flyway-database-postgresql")
// Flyway DB2 specific dependencies
implementation("org.flywaydb:flyway-database-db2")
// Flyway Derby specific dependencies
implementation("org.flywaydb:flyway-database-derby")
// HSQLDB specific dependencies
implementation("org.flywaydb:flyway-database-hsqldb")
// Informix specific dependencies
implementation("org.flywaydb:flyway-database-informix")
// Redshift specific dependencies
implementation("org.flywaydb:flyway-database-redshift")
// Saphana specific dependencies
implementation("org.flywaydb:flyway-database-saphana")
// Snowflake specific dependencies
implementation("org.flywaydb:flyway-database-snowflake")
// Sybasease specific dependencies
implementation("org.flywaydb:flyway-database-sybasease")
// Firebird specific dependencies
implementation("org.flywaydb:flyway-firebird")
// BigQuery specific dependencies
implementation("org.flywaydb:flyway-gcp-bigquery")
// Spanner specific dependencies
implementation("org.flywaydb:flyway-gcp-spanner")
// Singlestore specific dependencies
implementation("org.flywaydb:flyway-singlestore:10.15.0")

O suporte ao Flyway depende da configuração do datasource do Quarkus. Ela pode ser personalizada para o datasource padrão, bem como para cada named datasource. Primeiro, você precisa adicionar a configuração do datasource ao arquivo application.properties para permitir que o Flyway gerencie o esquema. Além disso, você pode personalizar o comportamento do Flyway usando as seguintes propriedades:

Propriedade de Configuração Fixa no Momento da Compilação - Todas as outras propriedades de configuração podem ser sobrepostas em tempo de execução.

Configuration property

Tipo

Padrão

Whether Flyway is enabled during the build.

If Flyway is disabled, the Flyway beans won’t be created and Flyway won’t be usable.

Environment variable: QUARKUS_FLYWAY_ENABLED

Show more

boolean

true

Comma-separated list of locations to scan recursively for migrations. The location type is determined by its prefix.

Unprefixed locations or locations starting with classpath: point to a package on the classpath and may contain both SQL and Java-based migrations.

Locations starting with filesystem: point to a directory on the filesystem, may only contain SQL migrations and are only scanned recursively down non-hidden directories.

Environment variable: QUARKUS_FLYWAY_LOCATIONS

Show more

list of string

db/migration

Comma-separated list of fully qualified class names of Callback implementations to use to hook into the Flyway lifecycle. The org.flywaydb.core.api.callback.Callback subclass must have a no-args constructor and must not be abstract. These classes must also not have any fields that hold state (unless that state is initialized in the constructor).

Environment variable: QUARKUS_FLYWAY_CALLBACKS

Show more

list of string

Flag to activate/deactivate Flyway for a specific datasource at runtime.

Environment variable: QUARKUS_FLYWAY_ACTIVE

Show more

boolean

'true' if the datasource is active; 'false' otherwise

The maximum number of retries when attempting to connect to the database.

After each failed attempt, Flyway will wait up to the configured connect-retries-interval duration before attempting to connect again, up to the maximum number of times specified by connectRetries.

Environment variable: QUARKUS_FLYWAY_CONNECT_RETRIES

Show more

int

The maximum time between retries when attempting to connect to the database.

This will cap the interval between connect retries to the value provided.

Environment variable: QUARKUS_FLYWAY_CONNECT_RETRIES_INTERVAL

Show more

Duration 

120 seconds

Sets the default schema managed by Flyway. This schema name is case-sensitive. If not specified, but schemas is, Flyway uses the first schema in that list. If that is also not specified, Flyway uses the default schema for the database connection.

Consequences:

  • This schema will be the one containing the schema history table.

  • This schema will be the default for the database connection (provided the database supports this concept).

Environment variable: QUARKUS_FLYWAY_DEFAULT_SCHEMA

Show more

string

The JDBC URL that Flyway uses to connect to the database. Falls back to the datasource URL if not specified.

Environment variable: QUARKUS_FLYWAY_JDBC_URL

Show more

string

The username that Flyway uses to connect to the database. If no specific JDBC URL is configured, falls back to the datasource username if not specified.

Environment variable: QUARKUS_FLYWAY_USERNAME

Show more

string

The password that Flyway uses to connect to the database. If no specific JDBC URL is configured, falls back to the datasource password if not specified.

Environment variable: QUARKUS_FLYWAY_PASSWORD

Show more

string

Comma-separated case-sensitive list of schemas managed by Flyway. The first schema in the list will be automatically set as the default one during the migration. It will also be the one containing the schema history table.

Environment variable: QUARKUS_FLYWAY_SCHEMAS

Show more

list of string

The name of Flyway’s schema history table. By default (single-schema mode), the schema history table is placed in the default schema for the connection provided by the datasource. When the flyway.schemas property is set (multi-schema mode), the schema history table is placed in the first schema of the list.

Environment variable: QUARKUS_FLYWAY_TABLE

Show more

string

The file name prefix for versioned SQL migrations. Versioned SQL migrations have the following file name structure: prefixVERSIONseparatorDESCRIPTIONsuffix , which using the defaults translates to V1.1__My_description.sql

Environment variable: QUARKUS_FLYWAY_SQL_MIGRATION_PREFIX

Show more

string

The file name prefix for repeatable SQL migrations. Repeatable SQL migrations have the following file name structure: prefixSeparatorDESCRIPTIONsuffix , which using the defaults translates to R__My_description.sql

Environment variable: QUARKUS_FLYWAY_REPEATABLE_SQL_MIGRATION_PREFIX

Show more

string

true to execute Flyway clean command automatically when the application starts, false otherwise.

Environment variable: QUARKUS_FLYWAY_CLEAN_AT_START

Show more

boolean

false

true to prevent Flyway clean operations, false otherwise.

Environment variable: QUARKUS_FLYWAY_CLEAN_DISABLED

Show more

boolean

false

true to automatically call clean when a validation error occurs, false otherwise.

Environment variable: QUARKUS_FLYWAY_CLEAN_ON_VALIDATION_ERROR

Show more

boolean

false

true to execute Flyway automatically when the application starts, false otherwise.

Environment variable: QUARKUS_FLYWAY_MIGRATE_AT_START

Show more

boolean

false

true to execute a Flyway repair command when the application starts, false otherwise.

Environment variable: QUARKUS_FLYWAY_REPAIR_AT_START

Show more

boolean

false

true to execute a Flyway validate command when the application starts, false otherwise.

Environment variable: QUARKUS_FLYWAY_VALIDATE_AT_START

Show more

boolean

false

true to execute Flyway baseline before migrations This flag is ignored if the flyway_schema_history table exists in the current schema or if the current schema is empty. Note that this will not automatically call migrate, you must either enable baselineAtStart or programmatically call flyway.migrate().

Environment variable: QUARKUS_FLYWAY_BASELINE_ON_MIGRATE

Show more

boolean

false

true to execute Flyway baseline automatically when the application starts. This flag is ignored if the flyway_schema_history table exists in the current schema. This will work even if the current schema is empty.

Environment variable: QUARKUS_FLYWAY_BASELINE_AT_START

Show more

boolean

false

The initial baseline version.

Environment variable: QUARKUS_FLYWAY_BASELINE_VERSION

Show more

string

The description to tag an existing schema with when executing baseline.

Environment variable: QUARKUS_FLYWAY_BASELINE_DESCRIPTION

Show more

string

Whether to automatically call validate when performing a migration.

Environment variable: QUARKUS_FLYWAY_VALIDATE_ON_MIGRATE

Show more

boolean

true

Allows migrations to be run "out of order".

Environment variable: QUARKUS_FLYWAY_OUT_OF_ORDER

Show more

boolean

false

Ignore missing migrations when reading the history table. When set to true migrations from older versions present in the history table but absent in the configured locations will be ignored (and logged as a warning), when false (the default) the validation step will fail.

Environment variable: QUARKUS_FLYWAY_IGNORE_MISSING_MIGRATIONS

Show more

boolean

false

Ignore future migrations when reading the history table. When set to true migrations from newer versions present in the history table but absent in the configured locations will be ignored (and logged as a warning), when false (the default) the validation step will fail.

Environment variable: QUARKUS_FLYWAY_IGNORE_FUTURE_MIGRATIONS

Show more

boolean

false

Sets the placeholders to replace in SQL migration scripts.

Environment variable: QUARKUS_FLYWAY_PLACEHOLDERS__PLACEHOLDER_KEY_

Show more

Map<String,String>

Whether Flyway should attempt to create the schemas specified in the schemas property

Environment variable: QUARKUS_FLYWAY_CREATE_SCHEMAS

Show more

boolean

true

Prefix of every placeholder (default: ${ )

Environment variable: QUARKUS_FLYWAY_PLACEHOLDER_PREFIX

Show more

string

Suffix of every placeholder (default: } )

Environment variable: QUARKUS_FLYWAY_PLACEHOLDER_SUFFIX

Show more

string

The SQL statements to run to initialize a new database connection immediately after opening it.

Environment variable: QUARKUS_FLYWAY_INIT_SQL

Show more

string

Whether to validate migrations and callbacks whose scripts do not obey the correct naming convention. A failure can be useful to check that errors such as case sensitivity in migration prefixes have been corrected.

Environment variable: QUARKUS_FLYWAY_VALIDATE_MIGRATION_NAMING

Show more

boolean

false

Ignore migrations during validate and repair according to a given list of patterns (see https://flywaydb.org/documentation/configuration/parameters/ignoreMigrationPatterns for more information). When this configuration is set, the ignoreFutureMigrations and ignoreMissingMigrations settings are ignored. Patterns are comma separated.

Environment variable: QUARKUS_FLYWAY_IGNORE_MIGRATION_PATTERNS

Show more

list of string

Named datasources

Tipo

Padrão

Comma-separated list of locations to scan recursively for migrations. The location type is determined by its prefix.

Unprefixed locations or locations starting with classpath: point to a package on the classpath and may contain both SQL and Java-based migrations.

Locations starting with filesystem: point to a directory on the filesystem, may only contain SQL migrations and are only scanned recursively down non-hidden directories.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__LOCATIONS

Show more

list of string

db/migration

Comma-separated list of fully qualified class names of Callback implementations to use to hook into the Flyway lifecycle. The org.flywaydb.core.api.callback.Callback subclass must have a no-args constructor and must not be abstract. These classes must also not have any fields that hold state (unless that state is initialized in the constructor).

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__CALLBACKS

Show more

list of string

Flag to activate/deactivate Flyway for a specific datasource at runtime.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__ACTIVE

Show more

boolean

'true' if the datasource is active; 'false' otherwise

The maximum number of retries when attempting to connect to the database.

After each failed attempt, Flyway will wait up to the configured connect-retries-interval duration before attempting to connect again, up to the maximum number of times specified by connectRetries.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__CONNECT_RETRIES

Show more

int

The maximum time between retries when attempting to connect to the database.

This will cap the interval between connect retries to the value provided.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__CONNECT_RETRIES_INTERVAL

Show more

Duration 

120 seconds

Sets the default schema managed by Flyway. This schema name is case-sensitive. If not specified, but schemas is, Flyway uses the first schema in that list. If that is also not specified, Flyway uses the default schema for the database connection.

Consequences:

  • This schema will be the one containing the schema history table.

  • This schema will be the default for the database connection (provided the database supports this concept).

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__DEFAULT_SCHEMA

Show more

string

The JDBC URL that Flyway uses to connect to the database. Falls back to the datasource URL if not specified.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__JDBC_URL

Show more

string

The username that Flyway uses to connect to the database. If no specific JDBC URL is configured, falls back to the datasource username if not specified.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__USERNAME

Show more

string

The password that Flyway uses to connect to the database. If no specific JDBC URL is configured, falls back to the datasource password if not specified.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__PASSWORD

Show more

string

Comma-separated case-sensitive list of schemas managed by Flyway. The first schema in the list will be automatically set as the default one during the migration. It will also be the one containing the schema history table.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__SCHEMAS

Show more

list of string

The name of Flyway’s schema history table. By default (single-schema mode), the schema history table is placed in the default schema for the connection provided by the datasource. When the flyway.schemas property is set (multi-schema mode), the schema history table is placed in the first schema of the list.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__TABLE

Show more

string

The file name prefix for versioned SQL migrations. Versioned SQL migrations have the following file name structure: prefixVERSIONseparatorDESCRIPTIONsuffix , which using the defaults translates to V1.1__My_description.sql

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__SQL_MIGRATION_PREFIX

Show more

string

The file name prefix for repeatable SQL migrations. Repeatable SQL migrations have the following file name structure: prefixSeparatorDESCRIPTIONsuffix , which using the defaults translates to R__My_description.sql

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__REPEATABLE_SQL_MIGRATION_PREFIX

Show more

string

true to execute Flyway clean command automatically when the application starts, false otherwise.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__CLEAN_AT_START

Show more

boolean

false

true to prevent Flyway clean operations, false otherwise.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__CLEAN_DISABLED

Show more

boolean

false

true to automatically call clean when a validation error occurs, false otherwise.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__CLEAN_ON_VALIDATION_ERROR

Show more

boolean

false

true to execute Flyway automatically when the application starts, false otherwise.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__MIGRATE_AT_START

Show more

boolean

false

true to execute a Flyway repair command when the application starts, false otherwise.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__REPAIR_AT_START

Show more

boolean

false

true to execute a Flyway validate command when the application starts, false otherwise.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__VALIDATE_AT_START

Show more

boolean

false

true to execute Flyway baseline before migrations This flag is ignored if the flyway_schema_history table exists in the current schema or if the current schema is empty. Note that this will not automatically call migrate, you must either enable baselineAtStart or programmatically call flyway.migrate().

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__BASELINE_ON_MIGRATE

Show more

boolean

false

true to execute Flyway baseline automatically when the application starts. This flag is ignored if the flyway_schema_history table exists in the current schema. This will work even if the current schema is empty.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__BASELINE_AT_START

Show more

boolean

false

The initial baseline version.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__BASELINE_VERSION

Show more

string

The description to tag an existing schema with when executing baseline.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__BASELINE_DESCRIPTION

Show more

string

Whether to automatically call validate when performing a migration.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__VALIDATE_ON_MIGRATE

Show more

boolean

true

Allows migrations to be run "out of order".

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__OUT_OF_ORDER

Show more

boolean

false

Ignore missing migrations when reading the history table. When set to true migrations from older versions present in the history table but absent in the configured locations will be ignored (and logged as a warning), when false (the default) the validation step will fail.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__IGNORE_MISSING_MIGRATIONS

Show more

boolean

false

Ignore future migrations when reading the history table. When set to true migrations from newer versions present in the history table but absent in the configured locations will be ignored (and logged as a warning), when false (the default) the validation step will fail.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__IGNORE_FUTURE_MIGRATIONS

Show more

boolean

false

Sets the placeholders to replace in SQL migration scripts.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__PLACEHOLDERS__PLACEHOLDER_KEY_

Show more

Map<String,String>

Whether Flyway should attempt to create the schemas specified in the schemas property

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__CREATE_SCHEMAS

Show more

boolean

true

Prefix of every placeholder (default: ${ )

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__PLACEHOLDER_PREFIX

Show more

string

Suffix of every placeholder (default: } )

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__PLACEHOLDER_SUFFIX

Show more

string

The SQL statements to run to initialize a new database connection immediately after opening it.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__INIT_SQL

Show more

string

Whether to validate migrations and callbacks whose scripts do not obey the correct naming convention. A failure can be useful to check that errors such as case sensitivity in migration prefixes have been corrected.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__VALIDATE_MIGRATION_NAMING

Show more

boolean

false

Ignore migrations during validate and repair according to a given list of patterns (see https://flywaydb.org/documentation/configuration/parameters/ignoreMigrationPatterns for more information). When this configuration is set, the ignoreFutureMigrations and ignoreMissingMigrations settings are ignored. Patterns are comma separated.

Environment variable: QUARKUS_FLYWAY__DATASOURCE_NAME__IGNORE_MIGRATION_PATTERNS

Show more

list of string

About the Duration format

To write duration values, use the standard java.time.Duration format. See the Duration#parse() Java API documentation for more information.

Você também pode usar um formato simplificado, começando com um número:

  • Se o valor for apenas um número, ele representará o tempo em segundos.

  • Se o valor for um número seguido de 'ms', ele representa o tempo em milissegundos.

Em outros casos, o formato simplificado é traduzido para o formato 'java.time.Duration' para análise:

  • Se o valor for um número seguido de 'h', 'm' ou 's', ele é prefixado com 'PT'.

  • Se o valor for um número seguido de 'd', ele é prefixado com 'P'.

Desenvolvendo com o Flyway

A seguir, um exemplo do arquivo application.properties :

# configure your datasource
quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=sarah
quarkus.datasource.password=connor
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/mydatabase

# Run Flyway migrations automatically
quarkus.flyway.migrate-at-start=true

# More Flyway configuration options
# quarkus.flyway.baseline-on-migrate=true
# quarkus.flyway.baseline-version=1.0.0
# quarkus.flyway.baseline-description=Initial version
# quarkus.flyway.connect-retries=10
# quarkus.flyway.schemas=TEST_SCHEMA
# quarkus.flyway.table=flyway_quarkus_history
# quarkus.flyway.locations=db/location1,db/location2
# quarkus.flyway.sql-migration-prefix=X
# quarkus.flyway.repeatable-sql-migration-prefix=K

Adicione uma migração SQL à pasta padrão seguindo as convenções de nomenclatura do Flyway: src/main/resources/db/migration/V1.0.0__Quarkus.sql

CREATE TABLE quarkus
(
  id   INT,
  name VARCHAR(20)
);
INSERT INTO quarkus(id, name)
VALUES (1, 'QUARKED');

Agora, você pode iniciar sua aplicação e o Quarkus executará o método de migração do Flyway de acordo com sua configuração.

Com quarkus.flyway.migrate-at-start=true , como no exemplo acima, o Quarkus executará a migração do Flyway como parte da inicialização do aplicativo .
@ApplicationScoped
public class MigrationService {
    // You can Inject the object if you want to use it manually
    @Inject
    Flyway flyway; (1)

    public void checkMigration() {
        // This will print 1.0.0
        System.out.println(flyway.info().current().getVersion().toString());
    }
}
1 Injete o objeto Flyway se quiser usá-lo diretamente
No modo de desenvolvimento, o Quarkus reiniciará automaticamente o aplicativo se algum dos scripts de migração existentes for modificado. Se quiser tirar proveito disso ao desenvolver e testar novos scripts de migração, você deverá definir %dev.quarkus.flyway.clean-at-start=true , para que o Flyway realmente execute a migração modificada.

Reparando a tabela de histórico do esquema Flyway

Há diferentes cenários que podem exigir o reparo da tabela de histórico do esquema do Flyway. Um desses cenários é quando uma migração falha em um banco de dados que não oferece suporte a instruções DDL transacionais.

Nessas situações, o Comando de reparo do Flyway é útil. No Quarkus, ele pode ser executado automaticamente antes da migração, definindo quarkus.flyway.repair-at-start=true , ou manualmente, injetando o objeto Flyway e chamando Flyway#repair() .

Datasources Múltiplos

O Flyway pode ser configurado para vários datasources. As propriedades do Flyway são prefixadas exatamente da mesma forma que os datasources nomeados, por exemplo:

quarkus.datasource.db-kind=h2
quarkus.datasource.username=username-default
quarkus.datasource.jdbc.url=jdbc:h2:tcp://localhost/mem:default
quarkus.datasource.jdbc.max-size=13

quarkus.datasource.users.db-kind=h2
quarkus.datasource.users.username=username1
quarkus.datasource.users.jdbc.url=jdbc:h2:tcp://localhost/mem:users
quarkus.datasource.users.jdbc.max-size=11

quarkus.datasource.inventory.db-kind=h2
quarkus.datasource.inventory.username=username2
quarkus.datasource.inventory.jdbc.url=jdbc:h2:tcp://localhost/mem:inventory
quarkus.datasource.inventory.jdbc.max-size=12

# Flyway configuration for the default datasource
quarkus.flyway.schemas=DEFAULT_TEST_SCHEMA
quarkus.flyway.locations=db/default/location1,db/default/location2
quarkus.flyway.migrate-at-start=true

# Flyway configuration for the "users" datasource
quarkus.flyway.users.schemas=USERS_TEST_SCHEMA
quarkus.flyway.users.locations=db/users/location1,db/users/location2
quarkus.flyway.users.migrate-at-start=true

# Flyway configuration for the "inventory" datasource
quarkus.flyway.inventory.schemas=INVENTORY_TEST_SCHEMA
quarkus.flyway.inventory.locations=db/inventory/location1,db/inventory/location2
quarkus.flyway.inventory.migrate-at-start=true

Observe que há um bit extra na chave. A sintaxe é a seguinte: quarkus.flyway.[optional name.][datasource property] .

Sem configuração, o Flyway é configurado para cada _datasource _ usando as configurações padrão.

Customizando o Flyway

Nos casos em que o Flyway precisa ser configurado além das opções de configuração fornecidas pelo Quarkus, a classe io.quarkus.flyway.FlywayConfigurationCustomizer é útil.

Para personalizar o Flyway para o datasource padrão, basta adicionar um bean da seguinte forma:

@Singleton
public static class MyCustomizer implements FlywayConfigurationCustomizer {

    @Override
    public void customize(FluentConfiguration configuration) {
        // do something with configuration
    }
}

Quando são usados datasources _ nomeados, a anotação @FlywayDataSource pode ser usada para especificar o _datasource _ ao qual o customizador se aplica. Por exemplo, se houver vários _datasources, um dos quais se chama users , e a customização do Flyway for necessária apenas para esse _datasource _, então o seguinte código poderá ser usado:

@Singleton
@FlywayDataSource("users")
public static class UsersCustomizer implements FlywayConfigurationCustomizer {

    @Override
    public void customize(FluentConfiguration configuration) {
        // do something with configuration
    }
}

Usando o objeto Flyway

Caso esteja interessado em usar o objeto Flyway diretamente, você pode injetá-lo da seguinte forma:

@ApplicationScoped
public class MigrationService {
    // You can Inject the object if you want to use it manually
    @Inject
    Flyway flyway; (1)

    @Inject
    @FlywayDataSource("inventory") (2)
    Flyway flywayForInventory;

    @Inject
    @Named("flyway_users") (3)
    Flyway flywayForUsers;

    public void checkMigration() {
        // Use the flyway instance manually
        flyway.clean(); (4)
        flyway.migrate();
        // This will print 1.0.0
        System.out.println(flyway.info().current().getVersion().toString());
    }
}
1 Injete o objeto Flyway se quiser usá-lo diretamente
2 Injete o Flyway para datasources nomeados usando o qualificador do Quarkus FlywayDataSource
3 Injete o Flyway para datasources nomeados
4 Use a instância do Flyway diretamente

Flyway e Hibernate ORM

Ao usar o Flyway junto com o Hibernate ORM, você pode usar a Dev UI para gerar o script de criação do esquema inicial.

Você pode encontrar mais informações sobre esse recurso no Guia Hibernate ORM .

Flyway and Reactive datasources

Flyway internally relies on a JDBC datasource, whereas reactive use cases will rely on reactive SQL clients, either directly or through Hibernate Reactive. This is not a problem in Quarkus, because a single configured datasource can be made available both through reactive clients and JDBC.

To use Flyway on a datasource you otherwise access reactively, simply make sure to configure that datasource both as JDBC and reactive. This involves in particular adding dependencies to Quarkus extensions for both the JDBC driver and the reactive client, for instance quarkus-jdbc-postgresql and quarkus-reactive-pg-client.

Flyway no Kubernetes

Às vezes, é útil não executar a inicialização do Flyway em cada inicialização da aplicação. Um exemplo disso é ao implantar

no Kubernetes, onde não faz sentido executar o Flyway em cada réplica. Em vez disso, é desejável executá-lo uma vez e depois iniciar o aplicativo real sem o Flyway. Para dar suporte a esse caso de uso, ao gerar manifestos para o Kubernetes, os manifestos gerados contêm um Job de inicialização do Kubernetes para o Flyway. O Job executa a inicialização e o Pod real será iniciado assim que o Job for concluído com êxito.

Desabilitando

O recurso é habilitado por padrão e pode ser desativado globalmente, usando:

quarkus.kubernetes.init-task-defaults.enabled=false

ou no OpenShift:

quarkus.openshift.init-task-defaults.enabled=false

Usando uma imagem personalizada que controla a espera pelo Job

Para alterar a imagem wait-for que, por padrão, é groundnuty/k8s-wait-for:no-root-v1.7 , você pode usar:

quarkus.kubernetes.init-task-defaults.wait-for-container.image=my/wait-for-image:1.0

ou no OpenShift:

quarkus.openshift.init-task-defaults.wait-for-container.image=my/wait-for-image:1.0

Observação : Neste contexto, globalmente significa for all extensions that support init task externalization .

Conteúdo Relacionado