Uso de Liquibase MongoDB
Liquibase is an open source tool for database schema change management, it allows managing MongoDB databases via it’s MongoDB Extension.
Quarkus proporciona un soporte de primera clase para el uso de Liquibase MongoDB Extension como se explicará en esta guía.
Solución
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
Clone el repositorio Git: git clone https://github.com/quarkusio/quarkus-quickstarts.git
o descargue un archivo.
The solution is located in the liquibase-mongodb-quickstart
directory.
Configuración del soporte para Liquibase
Para empezar a utilizar la extensión Liquibase MongoDB con su proyecto, sólo tiene que:
-
añada su changeLog al archivo
src/main/resources/db/changeLog.xml
como suele hacer con Liquibase -
activate the
migrate-at-start
option to migrate the schema automatically or inject theLiquibase
object and run your migration as you normally do.
You can add the liquibase-mongodb
extension
to your project by running the following command in your project base directory:
quarkus extension add liquibase-mongodb
./mvnw quarkus:add-extension -Dextensions='liquibase-mongodb'
./gradlew addExtension --extensions='liquibase-mongodb'
Esto añadirá lo siguiente a su archivo de construcción:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-liquibase-mongodb</artifactId>
</dependency>
implementation("io.quarkus:quarkus-liquibase-mongodb")
The Liquibase MongoDB extension support relies on the Quarkus MongoDB client config.
For the time being, it does not support multiple clients.
You need to add the MongoDB config to the application.properties
file
in order to allow Liquibase to manage the schema.
El siguiente es un ejemplo para el archivo application.properties
:
# configure MongoDB
quarkus.mongodb.connection-string = mongodb://localhost:27017
# Liquibase MongoDB minimal config properties
quarkus.liquibase-mongodb.migrate-at-start=true
# Liquibase MongoDB optional config properties
# quarkus.liquibase-mongodb.change-log=db/changeLog.xml
# quarkus.liquibase-mongodb.validate-on-migrate=true
# quarkus.liquibase-mongodb.clean-at-start=false
# quarkus.liquibase-mongodb.contexts=Context1,Context2
# quarkus.liquibase-mongodb.labels=Label1,Label2
# quarkus.liquibase-mongodb.default-catalog-name=DefaultCatalog
# quarkus.liquibase-mongodb.default-schema-name=DefaultSchema
Liquibase MongoDB is configured using a connection string, we do our best to craft a connection string that matches the MongoDB client configuration but if some configuration properties are not working you may consider adding them directly into the quarkus.mongodb.connection-string config property.
|
Add a changeLog file to the default folder following the Liquibase naming conventions: src/main/resources/db/changeLog.xml
YAML, JSON and XML formats are supported for the changeLog.
<?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"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<changeSet id="1" author="loic">
<ext:createCollection collectionName="Fruit"/>
<ext:createIndex collectionName="Fruit">
<ext:keys>{color: 1}</ext:keys>
<ext:options>{name: "colorIdx"}</ext:options>
</ext:createIndex>
<ext:insertOne collectionName="Fruit">
<ext:document>{"name":"orange", "color": "orange"}</ext:document>
</ext:insertOne>
</changeSet>
</databaseChangeLog>
Ahora puedes iniciar tu aplicación y Quarkus ejecutará el método de actualización de Liquibase según tu configuración.
Uso del objeto Liquibase
En caso de que esté interesado en utilizar el objeto Liquibase
directamente, puede inyectarlo de la siguiente manera:
If you enabled the quarkus.liquibase.migrate-at-start property, by the time you use the Liquibase instance,
Quarkus will already have run the migrate operation.
|
import io.quarkus.liquibase.LiquibaseFactory;
@ApplicationScoped
public class MigrationService {
// You can Inject the object if you want to use it manually
@Inject
LiquibaseMongodbFactory liquibaseMongodbFactory; (1)
public void checkMigration() {
// Use the liquibase instance manually
try (Liquibase liquibase = liquibaseFactory.createLiquibase()) {
liquibase.dropAll(); (2)
liquibase.validate();
liquibase.update(liquibaseFactory.createContexts(), liquibaseFactory.createLabels());
// Get the list of liquibase change set statuses
List<ChangeSetStatus> status = liquibase.getChangeSetStatuses(liquibaseFactory.createContexts(), liquibaseFactory.createLabels()); (3)
}
}
}
1 | Inyectar el objeto LiquibaseFactory |
2 | Utilizar directamente la instancia de Liquibase |
3 | Lista de los ChangeSets de liquibase aplicados o no aplicados |
Liquibase Mongodb on Kubernetes
Sometimes, it’s helpful not to execute Liquibase initialization on each application startup. One such example is when deploying
on Kubernetes, where it doesn’t make sense to execute Liquibase on every single replica. Instead it’s desirable to execute it
once and then start the actual application without Liquibase. To support this use case, when generating manifests for Kubernetes
the generated manifests contain a Kubernetes initialization Job
for Liquibase.
The Job
performs initialization and the actual Pod
, will starts once the Job
is successfully completed.
Disabling
The feature is enabled by default and can be globally disabled, using:
quarkus.kubernetes.init-task-defaults.enabled=false
or on OpenShift:
quarkus.openshift.init-task-defaults.enabled=false
Using a custom image that controls waiting for the Job
To change the wait-for
image which by default is groundnuty/k8s-wait-for:no-root-v1.7
you can use:
quarkus.kubernetes.init-task-defaults.wait-for-container.image=my/wait-for-image:1.0
or on OpenShift:
quarkus.openshift.init-task-defaults.wait-for-container.image=my/wait-for-image:1.0
Note: In this context globally means for all extensions that support init task externalization
.
Referencia de configuración
Propiedad de configuración fijada en tiempo de compilación - Todas las demás propiedades de configuración son anulables en tiempo de ejecución
Configuration property |
Tipo |
Por defecto |
---|---|---|
The change log file Environment variable: Show more |
string |
|
The search path for DirectoryResourceAccessor Environment variable: Show more |
list of string |
|
Flag to enable / disable Liquibase. Environment variable: Show more |
boolean |
|
The migrate at start flag Environment variable: Show more |
boolean |
|
The validate on update flag Environment variable: Show more |
boolean |
|
The clean at start flag Environment variable: Show more |
boolean |
|
The parameters to be passed to the changelog. Defined as key value pairs. Environment variable: Show more |
Map<String,String> |
|
The list of contexts Environment variable: Show more |
list of string |
|
The list of labels Environment variable: Show more |
list of string |
|
The default catalog name Environment variable: Show more |
string |
|
The default schema name Environment variable: Show more |
string |
|
The liquibase tables catalog name Environment variable: Show more |
string |
|
The liquibase tables schema name Environment variable: Show more |
string |
|
The liquibase tables tablespace name Environment variable: Show more |
string |