Skip to content

Latest commit

 

History

History
976 lines (826 loc) · 39.3 KB

LIQUIBASE.adoc

File metadata and controls

976 lines (826 loc) · 39.3 KB

SmallMind Liquibase

The smallmind-liquibase module is a thin Spring integration over Liquibase plus a logging bridge that routes Liquibase’s own log output through the SmallMind Scribe framework.

It is organised as a single Maven artifact (smallmind-liquibase) with one Java package (org.smallmind.liquibase.spring) containing six classes:

  • SpringLiquibase — a Spring InitializingBean that runs a configurable Liquibase command against one or more change logs during application-context refresh.

  • ChangeLog — a plain parameter envelope describing the input (and optional output) location of a single Liquibase change log file.

  • Goal — an enum enumerating the Liquibase commands SpringLiquibase is willing to execute: NONE, PREVIEW, UPDATE, DOCUMENT, GENERATE.

  • Source — an enum selecting whether change log resources are resolved from the filesystem (rooted at user.home) or from the classpath.

  • ScribeLogService — a Liquibase LogService implementation, discovered through java.util.ServiceLoader, that supersedes Liquibase’s built-in JUL service when both are on the classpath.

  • ScribeLiquibaseLogger — a Liquibase Logger that translates java.util.logging.Level to org.smallmind.scribe.pen.Level and delegates to a per-class Scribe logger.

The module is deliberately small. It does not wrap Liquibase’s CLI, does not attempt to expose its full feature surface, and does not replace its schema. It exists to turn Liquibase into a bean you can drop into a Spring context, configure through five properties, and have it perform exactly one of five coarse-grained operations at the moment the context comes up.

Liquibase ships with its own Spring integration (liquibase.integration.spring.SpringLiquibase), and for many applications that is sufficient. smallmind-liquibase exists because a SmallMind application has a particular shape that Liquibase’s default integration does not quite fit:

  1. A single bean must cover more than one command. In a SmallMind service, the same configuration file typically drives development ("generate the schema from what the developer just changed"), QA ("preview the SQL that would be executed"), CI ("produce the documentation"), and production ("apply pending changes"). Liquibase’s built-in integration is wired for update only; switching commands means swapping bean classes. A single SpringLiquibase bean in smallmind-liquibase covers all five operations by flipping the goal property — in practice, via a placeholder like ${liquibase.goal} set differently per environment.

  2. Multiple change logs, one bean. A service that spans several logical schemas (the application’s own tables, plus infrastructure schemas like Spring Batch’s BATCH_* or Quartz’s QRTZ_*) needs Liquibase to execute the same command against each. SpringLiquibase.setChangeLogs accepts an array, processes them in order, and opens a fresh JDBC connection per change log.

  3. Custom data types registered once. Applications that define LiquibaseDataType subclasses (for UUIDs, enumerated strings, domain types, etc.) must register them with DataTypeFactory before any change log is read. SpringLiquibase.setDataTypes performs the unregister/register pair at the start of afterPropertiesSet() so the custom type wins over any built-in of the same name. This works even when the configured goal is NONE — a common pattern for beans that exist only to install data types into a context that will use them later.

  4. Schema round-tripping from a live database. Goal.GENERATE uses Liquibase’s diff/snapshot machinery to reverse-engineer a live database into a change log, keyed per catalog. The default Spring integration has no equivalent. This is how the shipped Batch.changelog.xml and Quartz.changelog.xml files were produced.

  5. Logging that lines up with the rest of the service. SmallMind services use Scribe. Liquibase does not. Without a bridge, Liquibase output either disappears (if JUL is not configured) or arrives on a different channel than the service’s own log. ScribeLogService plus ScribeLiquibaseLogger make Liquibase log through the same appender, at the same level map, as everything else.

  6. Spring-managed transactions for UPDATE. afterPropertiesSet is annotated with SmallMind’s @Transactional so that, when a transactional context is already active at startup, the Liquibase UPDATE participates in it.

  • Wraps the Liquibase command API (CommandScope, UpdateCommandStep, UpdateSqlCommandStep, DbDocCommandStep) in a single Spring bean whose behaviour is chosen by setting one enum property.

  • Registers custom data types with Liquibase’s DataTypeFactory before reading any change log, replacing prior registrations.

  • Resolves change log resources through either a DirectoryResourceAccessor rooted at the user’s home directory or a ClassLoaderResourceAccessor bound to a caller-supplied class loader.

  • Runs one change log at a time inside a Liquibase Scope that carries the configured resource accessor, so relative includes in the change log resolve the same way the top-level file did.

  • Reverse-engineers the live schema into a change log file per catalog when the goal is GENERATE, with the change set author pinned to auto.generated.

  • Installs a logging bridge that routes Liquibase log events to a Scribe logger keyed on the requesting class.

  • It does not expose every Liquibase command. rollback, status, tag, history, clearCheckSums, and the contexts-manipulation subcommands are not wired in. Callers that need them run Liquibase directly.

  • It does not provide a transaction manager, a connection pool, or a data source factory. SpringLiquibase.setDataSource expects an already-built javax.sql.DataSource — the caller decides where it comes from (a JNDI lookup, a DriverManagerDataSource, a pooled data source, etc.).

  • It does not support multi-schema comparisons or cross-database diffs. The GENERATE goal always compares the default schema of the configured database against an empty snapshot, producing a "create from nothing" change log.

  • It does not ship its own change log XSD or any prewritten change sets. Callers supply those; the module only executes them.

  • It does not lock or coordinate between JVMs. Liquibase’s own DATABASECHANGELOGLOCK table provides that guarantee, and smallmind-liquibase relies on it rather than reimplementing it.

Class Role

SpringLiquibase

The only bean a typical caller declares. Implements InitializingBean so that the configured goal runs during context refresh, once all properties have been injected. Holds a DataSource, a ResourceAccessor, the chosen Goal, an array of ChangeLog`s, optional custom `LiquibaseDataType[], an optional comma-delimited contexts string, an optional outputDir, and an optional previewStream.

ChangeLog

Plain JavaBean with two string properties, input and output. input is required whenever the goal is not NONE and is interpreted according to the active Source. output is retained for callers that want to pair an input with a named output file, but the current SpringLiquibase implementation writes GENERATE output under ${outputDir}/${catalog}.changelog rather than consuming ChangeLog.getOutput() — the property is part of the configuration shape, not the execution path.

Goal

Five-valued enum that selects which Liquibase command afterPropertiesSet() runs per change log. See Goals in detail below for the semantics of each constant.

Source

Two-valued enum (FILE, CLASSPATH) that selects the Liquibase ResourceAccessor used to resolve change log paths. FILE builds a DirectoryResourceAccessor rooted at System.getProperty("user.home"); CLASSPATH builds a ClassLoaderResourceAccessor bound to the class loader supplied at SpringLiquibase construction time.

ScribeLogService

Liquibase LogService SPI implementation. Its priority is PRIORITY_DEFAULT + 1, which is enough to beat Liquibase’s built-in JUL service when both are on the classpath. getLog(Class) returns a fresh ScribeLiquibaseLogger on every call.

ScribeLiquibaseLogger

Liquibase Logger implementation built on AbstractLogger. Holds a Logger obtained from LoggerManager.getLogger(clazz) and translates java.util.logging.Level to org.smallmind.scribe.pen.Level on each emit. Unknown non-null levels default to INFO so nothing is silently dropped.

Goal is the single most important configuration knob on SpringLiquibase. Each constant maps to a different Liquibase command, with different inputs and different side effects.

NONE

Register custom data types, then return. No database connection is opened, no change log is read. Use this when a bean’s only purpose is to install LiquibaseDataType instances — typically in a context where another bean will perform the actual migration later, or in a read-only process that must understand the schema’s custom types without altering anything.

PREVIEW

Invoke UpdateSqlCommandStep against an offline database URL of the form offline:${displayName}. Liquibase resolves the database dialect from the display name, generates the SQL for every pending change set filtered by the configured contexts, and writes the result to the supplied previewStream (falling back to System.out when none is set). No DDL or DML is applied — the live connection is used only to determine which dialect to generate. Useful for change-control review boards that want to see the exact SQL before a deployment.

UPDATE

Invoke UpdateCommandStep against the live database. Liquibase consults its DATABASECHANGELOG table to determine which change sets have already been applied, filters the remainder by the configured contexts, and executes them. The run happens inside the transaction established by SmallMind’s @Transactional annotation on afterPropertiesSet, so a caller that wraps context startup in a transaction gets all-or-nothing semantics. This is the canonical production goal.

DOCUMENT

Invoke DbDocCommandStep. Liquibase reads the change log plus the current schema and produces an HTML documentation tree under outputDir (or the system temp directory when outputDir is blank). Useful in CI pipelines that publish a browseable schema reference alongside the application artifact.

GENERATE

Bypass the change log entirely and reverse-engineer the current schema. For each distinct catalog encountered while iterating the configured change logs, SpringLiquibase:

  1. Builds a SnapshotControl from the resolved Database.

  2. Builds a CompareControl that compares the default catalog/schema against itself.

  3. Captures a live snapshot through SnapshotGeneratorFactory.

  4. Diffs it against an empty snapshot (producing a "create everything" result).

  5. Writes the change log to ${outputDir}/${catalog}.changelog, falling back to the system temp directory when outputDir is blank.

    The changeSetAuthor is hard-coded to auto.generated and the changeSetContext is set to the configured contexts string. A change log generated this way round-trips cleanly: running UPDATE against an empty database reproduces the snapshot.

Source controls how strings passed to ChangeLog.setInput are resolved. The two constants map to two different Liquibase ResourceAccessor implementations:

FILE

DirectoryResourceAccessor rooted at System.getProperty("user.home"). A change log input of schemas/main/schema.xml resolves to $HOME/schemas/main/schema.xml (or the Windows equivalent). Use this when change logs are deployed alongside the application as external configuration — a pattern common for hand-edited schemas that must be modified without rebuilding the artifact.

CLASSPATH

ClassLoaderResourceAccessor bound to the class loader supplied to SpringLiquibase’s constructor (or the context class loader when the no-arg constructor is used). A change log input of `org/smallmind/batch/spring/Batch.changelog.xml resolves through ClassLoader.getResource(…​). Use this when change logs are packaged inside the application JAR/WAR — the normal case for the BATCH_* and QRTZ_* tables shipped by sibling SmallMind modules.

Note
Source is not a per-change-log setting. One SpringLiquibase bean uses one ResourceAccessor for every change log it processes. Callers that mix filesystem-based and classpath-based change logs should declare two beans.

The module is published as a single artifact:

<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>smallmind-liquibase</artifactId>
  <version>${project.version}</version>
</dependency>

Module name (for requires): org.smallmind.liquibase

It transitively pulls in liquibase-core, smallmind-nutsnbolts, and smallmind-persistence. spring-beans is declared as an optional dependency, which means a project consuming smallmind-liquibase also has to declare its own Spring dependencies — the module does not pin a Spring version for you. spring-orm and smallmind-quorum are optional too; only the shipped schema-hibernate.xml uses them.

  • A working javax.sql.DataSource addressable as a Spring bean. The module does not build one for you; the shipped example Spring XML files use org.smallmind.persistence.sql.DriverManagerDataSource, but any DataSource works.

  • A Liquibase change log reachable from the configured Source. Supported formats are whatever liquibase-core understands at runtime (XML, YAML, JSON, SQL).

  • For the Scribe logging bridge, a classpath entry META-INF/services/liquibase.logging.LogService containing the single line org.smallmind.liquibase.spring.ScribeLogService. Liquibase discovers log services via java.util.ServiceLoader, so without this file it will fall back to its built-in JUL service.

The jar ships an explicit module descriptor for org.smallmind.liquibase that exports org.smallmind.liquibase.spring and opens it unconditionally, so classpath:org/smallmind/liquibase/spring/schema-hibernate.xml stays loadable from other modules and Spring can reach SpringLiquibase. It re-exports (requires transitive) org.smallmind.persistence, java.sql, and java.logging, and requires org.smallmind.nutsnbolts, org.smallmind.scribe.pen, and the automatic module liquibase.core; spring.beans is requires static. On the classpath the descriptor is ignored. See Module Path And Classpath for the repository-wide rules.

  • liquibase.core is automatic and never re-exported. ScribeLogService and ScribeLiquibaseLogger expose Liquibase types, so a module that uses them requires liquibase.core itself.

  • The Scribe bridge is registered differently on a module path; see How Liquibase discovers the bridge.

  • liquibase.core is automatic, so it cannot bring its own dependencies into the module graph. The application resolves them with --add-modules org.apache.commons.lang3,org.yaml.snakeyaml,org.apache.commons.io. Without them creating a SpringLiquibase bean fails with NoClassDefFoundError: org/apache/commons/lang3/ObjectUtils.

  • A changelog stored in a package-like directory of a named module (for example database/schema/schema.xml) is encapsulated, so the module opens that package unconditionally (opens database.schema;). Without it the run fails with ChangeLogParseException: The file database/schema/schema.xml was not found in the configured search path.

The typical wiring puts SpringLiquibase in a Spring XML file alongside the DataSource that feeds it. The shipped smallmind-batch and smallmind-schedule-quartz modules both use the same pattern — reproduced below as a template.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="applicationLiquibase"                                     (1)
        class="org.smallmind.liquibase.spring.SpringLiquibase">
    <property name="dataSource" ref="applicationDataSource"/>         (2)
    <property name="source" value="CLASSPATH"/>                       (3)
    <property name="goal" value="UPDATE"/>                            (4)
    <property name="changeLogs">                                      (5)
      <list>
        <bean class="org.smallmind.liquibase.spring.ChangeLog">
          <property name="input"
                    value="com/example/db/schema.changelog.xml"/>
        </bean>
      </list>
    </property>
  </bean>

  <bean id="applicationDataSource"                                    (2)
        class="org.smallmind.persistence.sql.DriverManagerDataSource">
    <constructor-arg index="0" value="${jdbc.driver.classname}"/>
    <constructor-arg index="1" value="${jdbc.url}"/>
    <constructor-arg index="2" value="${jdbc.username}"/>
    <constructor-arg index="3" value="${jdbc.password}"/>
  </bean>
</beans>
  1. The bean id can be anything — nothing in the module depends on it. Multiple SpringLiquibase beans are allowed in one context; each runs independently during refresh.

  2. Any DataSource bean will do. SpringLiquibase calls dataSource.getConnection() once per change log and closes the connection through try-with-resources before moving to the next.

  3. CLASSPATH selects a ClassLoaderResourceAccessor. The input path below is resolved via ClassLoader.getResource.

  4. UPDATE is the production goal. Replace with ${liquibase.goal} and set a different value per environment to drive the other four behaviours from the same bean definition.

  5. changeLogs is a Spring list of ChangeLog beans. A single bean instance processes every entry in order, opening a fresh JDBC connection per entry.

The Liquibase run happens during the afterPropertiesSet callback, which Spring invokes after all property setters have returned. Beans that depend on the schema (ORM session factories, DAO beans, etc.) should be wired to depend on applicationLiquibase so that Spring orders their initialisation after the migration has completed — either by listing the Liquibase bean as a constructor-arg, by declaring depends-on="applicationLiquibase", or by importing the XML file that defines the bean before any dependent beans.

The goal is an enum-valued property, which Spring populates via PropertyEditorSupport from a string placeholder. A single XML file can cover every environment:

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="${liquibase.goal}"/>
  <property name="outputDir" value="${liquibase.output.dir}"/>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="database/schema/schema.xml"/>
      </bean>
    </list>
  </property>
</bean>

Combine with per-environment property files:

# production.properties
liquibase.goal=UPDATE

# ci.properties
liquibase.goal=DOCUMENT
liquibase.output.dir=/var/build/schema-docs

# preview.properties
liquibase.goal=PREVIEW

# developer-regenerating-from-db.properties
liquibase.goal=GENERATE
liquibase.output.dir=/home/dev/regen

This is the pattern used by schema-hibernate.xml.

The minimal configuration — the classpath-resident change log runs during context refresh, pending change sets are applied, the context comes up with the schema in the intended state.

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="UPDATE"/>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/schema.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

A single SpringLiquibase processes every change log in array order with the same goal. A service that owns application tables plus auxiliary infrastructure tables might wire it like this:

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="UPDATE"/>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/application.changelog.xml"/>
      </bean>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/audit.changelog.xml"/>
      </bean>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/reporting.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

Each change log gets a fresh connection. Liquibase’s own DATABASECHANGELOG table tracks applied change sets per change log — or per logical file, depending on how change sets are keyed — so cross-log include references remain safe.

Goal.PREVIEW writes the SQL to whatever stream the caller supplies. A common pattern is to route it to a file so a DBA can review it before a production push.

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="PREVIEW"/>
  <property name="previewStream">
    <bean class="java.io.FileOutputStream">
      <constructor-arg value="/var/build/pending-changes.sql"/>
    </bean>
  </property>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/schema.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

The live database is contacted only to determine the dialect; no DDL or DML is issued.

Goal.DOCUMENT produces a browseable HTML tree. Pointing outputDir at a build-artifact directory publishes the result alongside the rest of the build output:

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="DOCUMENT"/>
  <property name="outputDir" value="${project.build.directory}/dbdoc"/>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/schema.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

Goal.GENERATE ignores the change log’s contents and snapshots the live database instead, writing one change log file per distinct catalog. The input is still required (the module iterates the change logs to pick up their catalogs), but its body is not parsed.

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="legacyDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="GENERATE"/>
  <property name="outputDir" value="/home/dev/generated"/>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="placeholder.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

After context refresh, /home/dev/generated/${catalog}.changelog contains a complete Liquibase change log whose change set author is auto.generated. This is exactly how Batch.changelog.xml and Quartz.changelog.xml were produced — run GENERATE against an empty database that has had the tool’s native DDL applied, then commit the resulting file as the canonical change log.

setDataTypes takes an array of LiquibaseDataType instances. Each is unregistered from DataTypeFactory by name and then re-registered, so the caller’s implementation wins over any built-in or prior registration for the same name.

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="UPDATE"/>
  <property name="dataTypes">
    <list>
      <bean class="com.example.db.types.UuidDataType"/>
      <bean class="com.example.db.types.JsonbDataType"/>
    </list>
  </property>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/schema.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

A bean wired purely to install data types uses goal=NONE:

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="goal" value="NONE"/>
  <property name="dataTypes">
    <list>
      <bean class="com.example.db.types.UuidDataType"/>
    </list>
  </property>
</bean>

No data source, no change logs, no resource accessor are required — the bean runs the data-type registration block and returns.

The contexts property is passed through to the underlying Liquibase command. A comma-delimited list restricts the change sets processed (or generated SQL) to those matching at least one of the supplied context names, plus any change sets declared without a context.

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="UPDATE"/>
  <property name="contexts" value="production,us-east"/>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/schema.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

When Source.FILE is chosen, the input path is resolved relative to the user’s home directory. This is the right choice for change logs that ship outside the application artifact — for instance, a schema maintained by operations and deployed to a fixed location on the host:

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="FILE"/>
  <property name="goal" value="UPDATE"/>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="schemas/main/schema.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

This resolves to $HOME/schemas/main/schema.changelog.xml. The resource accessor is shared across every change log in the bean, so every input in the list is resolved the same way.

The no-arg SpringLiquibase() constructor captures the current thread’s context class loader. In an application server where the context class loader is the web module loader, that is usually the right thing. In embedded or test scenarios where the intended loader is different, use the one-arg constructor:

<bean class="org.smallmind.liquibase.spring.SpringLiquibase">
  <constructor-arg>
    <bean class="org.springframework.util.ClassUtils"
          factory-method="getDefaultClassLoader"/>
  </constructor-arg>
  <property name="dataSource" ref="applicationDataSource"/>
  <property name="source" value="CLASSPATH"/>
  <property name="goal" value="UPDATE"/>
  <property name="changeLogs">
    <list>
      <bean class="org.smallmind.liquibase.spring.ChangeLog">
        <property name="input" value="com/example/db/schema.changelog.xml"/>
      </bean>
    </list>
  </property>
</bean>

The class loader supplied here is the one ClassLoaderResourceAccessor will consult when Source.CLASSPATH is active; it has no effect when Source.FILE is used.

A complete stack under the session source key schema: a connection pool, Liquibase migration, a JPA EntityManagerFactory on Hibernate, and a JPAProxySession. Import it and supply the properties below:

<import resource="classpath:org/smallmind/liquibase/spring/schema-hibernate.xml"/>

What it defines:

  • schemaPooledDataSource — a PooledDataSource over a ComponentPool of DriverManagerComponentInstanceFactory connections. Hibernate uses it.

  • schemaLiquibase — a SpringLiquibase that applies database/schema/schema.xml from the classpath. It runs on its own unpooled DriverManagerDataSource (schemaLiquibaseDataSource) against the same database, and finishes before the entity manager factory starts.

  • schemaEntityManagerFactory — an EntitySeekingEntityManagerFactoryBean with session source key schema and the Hibernate persistence provider.

  • schemaProxySession — a JPAProxySession for schema, registered with SessionManager at startup.

Entities join the persistence unit through their DAOs: declare each DAO as a bean and annotate its class with @SessionSource("schema"):

@SessionSource("schema")
public class WidgetDao extends JPADao<Long, Widget> {

  public WidgetDao (JPAProxySession proxySession) {

    super(proxySession);
  }
}
<bean id="widgetDao" class="com.example.WidgetDao">
  <constructor-arg index="0" ref="schemaProxySession"/>
</bean>

Properties the file reads:

Property Used for

jdbc.driver.class_name.pool, jdbc.url.pool, jdbc.user.pool, jdbc.password.pool

The database, for both the pool and Liquibase

jdbc.validation_query.pool

Connection validation query

jdbc.max_statements.pool

Prepared statements cached per connection (0 disables the cache)

jdbc.validity_timeout_seconds.pool

Seconds a connection may take to answer Connection.isValid after an error before the pool discards it

jdbc.pool.test_on_acquire.pool, jdbc.pool.initial_size.pool, jdbc.pool.min_size.pool, jdbc.pool.max_size.pool

Pool sizing and testing

liquibase.goal

UPDATE, PREVIEW, GENERATE, DOCUMENT, or NONE

hibernate.dialect, hibernate.hbm2ddl.auto, hibernate.connection.isolation, hibernate.connection.autocommit, hibernate.jdbc.batch_size, hibernate.show_sql, hibernate.format_sql, hibernate.cache.use_second_level_cache

Hibernate settings

The file wires classes from smallmind-persistence’s optional stack, so the application declares those dependencies itself: `smallmind-quorum, spring-orm, spring-context, hibernate-core, and jakarta.persistence-api. It also starts the Spring context on a thread with a per-application context (the pool registers there); without one, startup fails with MissingPerApplicationContextException.

Liquibase writes a lot of output during a run, especially the first time a schema is applied. By default that output goes through Liquibase’s built-in JUL LogService. A SmallMind application that uses Scribe for everything else has two options: configure JUL to forward to Scribe, or install ScribeLogService as Liquibase’s log service. The second is simpler and requires no runtime configuration.

Liquibase discovers LogService implementations through java.util.ServiceLoader. For ScribeLogService to be picked up, the classpath must contain a file named META-INF/services/liquibase.logging.LogService whose contents are the fully-qualified class name of the service:

org.smallmind.liquibase.spring.ScribeLogService

The module does not ship this file itself — the consumer must place it in src/main/resources/META-INF/services/liquibase.logging.LogService in their own artifact. This is intentional: shipping the file in the module would force the bridge on every consumer of smallmind-liquibase, including ones that are not using Scribe.

On a module path the services file is not consulted, and provides must name a class in the declaring module. A modular application therefore declares a subclass of its own and provides that:

public class AppLogService extends ScribeLogService {
}
module com.example.app {
  requires liquibase.core;
  requires org.smallmind.liquibase;

  provides liquibase.logging.LogService with com.example.app.AppLogService;
}

Without the provides clause Liquibase falls back to its own JavaLogger. A Scribe backend (for example scribe-ink-indigenous) must also be on the module path, or the first log call fails with StaticInitializationError: No provider found for LoggingBlueprint.

ScribeLogService.getPriority() returns PRIORITY_DEFAULT + 1. Liquibase resolves priority ties by preferring the service it sees last, but a priority above default guarantees the Scribe bridge wins even when Liquibase’s own service is also registered. Custom services that want to override ScribeLogService can return a higher priority still.

ScribeLiquibaseLogger maps java.util.logging.Level to org.smallmind.scribe.pen.Level as follows:

JUL level Scribe level

ALL, FINEST, FINER

TRACE

FINE

DEBUG

CONFIG, INFO

INFO

WARNING

WARN

SEVERE

ERROR

OFF

OFF

Any other non-null level

INFO (fail-safe default)

null

null (suppressed)

The fail-safe INFO default means a future Liquibase release that adds a new JUL level never silently loses its output; it only loses its exact severity.

ScribeLogService.getLog(Class) returns a fresh ScribeLiquibaseLogger on every call, but the underlying Scribe Logger is obtained through LoggerManager.getLogger(clazz), which is itself cached per class. Liquibase sees a new Logger wrapper, Scribe sees the shared per-class target. Callers configure Scribe appenders on Liquibase package names (liquibase, liquibase.command, liquibase.database, etc.) exactly as they would for their own code.

afterPropertiesSet carries a SmallMind @Transactional annotation (from org.smallmind.persistence.orm.aop.Transactional). The annotation is honoured when a JPAProxySession or equivalent transactional context is in scope; when no such context is active, the annotation is a no-op.

The practical implication is that Goal.UPDATE runs inside whatever transaction the caller has already opened. In SmallMind services that do schema migrations under Hibernate, wiring the SpringLiquibase bean inside the persistence composition root ensures the migration either commits entirely or rolls back along with the rest of the startup sequence. Applications that do not use SmallMind’s transaction AOP see ordinary, per-statement JDBC behaviour — which is what Liquibase expects by default anyway.

Per-change-log isolation is absolute: each change log is processed inside its own try-with-resources block that closes the JDBC connection before the next change log opens one. A failure in change log N does not leave connection N+1’s transaction dangling.

  • FindException: Module java.activation not found, required by java.xml.bind at startup on a module path. liquibase-core depends on the old javax.xml.bind:jaxb-api, whose module requires java.activation. Nothing in a normal module graph resolves it; it is resolved when the launch uses --add-modules ALL-MODULE-PATH. Name the modules you need instead, or add javax.activation:javax.activation-api to the module path.

  • FileNotFoundException from setSource(Source.FILE). Thrown when DirectoryResourceAccessor cannot use System.getProperty("user.home") as a root — usually because the property is unset in the JVM. Either set -Duser.home=…​ or switch to Source.CLASSPATH.

  • UnknownSwitchCaseException from setSource or afterPropertiesSet. Thrown when the caller has constructed a Source or Goal value that the switch statement does not handle. Because both are enums declared in this module, this indicates a programming error — a caller passing null, or a new enum constant added without extending the switch.

  • Any SQLException thrown while acquiring a connection. Propagated up as a wrapped Exception from afterPropertiesSet; the Spring container will fail context refresh.

  • liquibase.exception.CommandExecutionException from an inner CommandScope.execute(). Propagated identically. A failing change set typically surfaces here — the error message identifies the change set id and the offending SQL.

  • IOException while writing PREVIEW, DOCUMENT, or GENERATE output. Propagated; the caller’s container decides the policy.

In every case, SpringLiquibase does not attempt to recover. The expectation is that a failed migration should fail the context, because continuing past one is almost always worse than aborting.

  • smallmind-batch — batch-liquibase.xml defines a SpringLiquibase bean that runs Batch.changelog.xml against a dedicated batchDataSource. The change log itself was generated by running Goal.GENERATE against a database that had Spring Batch’s native DDL applied.

  • smallmind-schedule-quartz — quartz-liquibase.xml does the same thing for Quartz’s QRTZ_* tables.

  • smallmind-persistence — this module’s schema-hibernate.xml runs a SpringLiquibase ahead of a smallmind-persistence JPA stack, with its goal driven by a placeholder so the same file runs UPDATE, PREVIEW, DOCUMENT, or GENERATE depending on the environment.

  • smallmind-scribe-pen — the logging target for ScribeLiquibaseLogger. Any Scribe appender configuration that applies to the liquibase.* package hierarchy applies to Liquibase’s output.

Each of these consumers demonstrates the same pattern: declare one SpringLiquibase per logical schema, feed it a DataSource aimed at that schema, point it at a classpath change log, and let context refresh do the migration.