Uso de Liquibase MongoDB
Liquibase es una herramienta de código abierto para la gestión de cambios en los esquemas de las bases de datos, permite gestionar las bases de datos MongoDB a través de su extensión MongoDB.
Quarkus proporciona un soporte de primera clase para el uso de Liquibase MongoDB Extension como se explicará en esta guía.
Solución
Le recomendamos que siga las instrucciones de las siguientes secciones y cree la aplicación paso a paso. Sin embargo, puede ir directamente al ejemplo completado.
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 -
active la opción
migrate-at-start
para migrar el esquema automáticamente o inyecte el objetoLiquibase
y ejecute su migración como lo hace normalmente.
En su pom.xml
, añada las siguientes dependencias:
-
la extensión Liquibase MongoDB
-
la extensión del cliente de MongoDB
<!-- Liquibase MongoDB -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-liquibase-mongodb</artifactId>
</dependency>
<!-- MongoDB client dependency -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-mongodb-client</artifactId>
</dependency>
// Liquibase MongoDB
implementation("io.quarkus:quarkus-liquibase-mongodb")
// MongoDB client dependency
implementation("io.quarkus:quarkus-mongodb-client")
El soporte de la extensión de Liquibase MongoDB depende de la configuración del cliente Quarkus MongoDB. Por el momento, no soporta múltiples clientes. En primer lugar, es necesario añadir la configuración de MongoDB al archivo application.properties
para permitir que Liquibase gestione el esquema.
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
Añade un archivo changeLog a la carpeta por defecto siguiendo las convenciones de nomenclatura de Liquibase: src/main/resources/db/changeLog.xml
Los formatos YAML, JSON y XML son compatibles con el 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:
Si habilitó la propiedad quarkus.liquibase.migrate-at-start , cuando utilice la instancia de Liquibase, Quarkus ya habrá ejecutado la operación de migración.
|
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.
The feature is enabled by default and can be globally disabled, using:
quarkus.kubernetes.externalize-init=false
or on OpenShift:
quarkus.openshift.externalize-init=false
Note: In this context globally means for all extensions that support init task externalization
.
Referencia de configuración
Configuration property fixed at build time - All other configuration properties are overridable at runtime
Type |
Default |
|
---|---|---|
The change log file Environment variable: Show more |
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 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 |
|
The parameters to be passed to the changelog. Defined as key value pairs. Environment variable: Show more |
|