Schema migrations and constraints
What you will learn
A schema migration is a controlled change to a database structure. Constraints defend invariants across all writers, while compatibility lets old and new application versions coexist during deployment.
- Use versioned migrations and database constraints.
- Plan expand/backfill/contract deployment safely.
- Distinguish application validation from durable constraint enforcement.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. PostgreSQL and Spring examples require the companion lab or configured infrastructure. Their predicted results are not execution evidence.
Model a required quantity
public class Main { static boolean valid(Integer n){return n!=null&&n>0;} public static void main(String[] args) {for(Integer n:new Integer[]{2,0,null})System.out.println(valid(n)); }}Expected output:
truefalsefalseThis models a positive non-null domain rule, not SQL three-valued logic.
Versioned change
Keep applied migration files immutable; Flyway records versions and checksums. Add a new migration for a correction. Expand with an additive nullable column or separate table, deploy code compatible with both schemas, backfill in bounded batches, verify completeness, then add stricter constraints and remove legacy fields in a later deployment. Consider lock duration, replicas, backups and recovery rehearsals. PostgreSQL can run many DDL statements transactionally but not every operation can be put in a transaction (CREATE INDEX CONCURRENTLY is a common exception). Never assume rollback of code reverses database changes.
Enforce invariants at the database
A primary key identifies a row, UNIQUE prevents duplicate keys (null semantics depend on the database), FOREIGN KEY enforces referenced-row existence, NOT NULL rejects missing values and CHECK enforces a row predicate. A CHECK can accept UNKNOWN, so pair with NOT NULL where absence is invalid. Cross-row invariants may need a different design or concurrency control. Application checks improve error messages but can race; map actual constraint violations carefully rather than exposing raw SQL errors.
Check old and new reader compatibility
public class Main { record Row(String title,String displayTitle) {} static String label(Row r){return r.displayTitle()==null?r.title():r.displayTitle();} public static void main(String[] args) {System.out.println(label(new Row("Java",null))); System.out.println(label(new Row("Java","Java 21"))); }}Expected output:
JavaJava 21Readers tolerate a missing additive field during migration. Writers and backfill need a separate compatibility plan.
Initial inventory migration
Source-reviewed, NOT RUN. File lab-fixtures/database-architecture-v43/V1__inventory.sql; use the companion lab README.
CREATE TABLE inventory ( sku text PRIMARY KEY, stock integer NOT NULL CHECK (stock >= 0), version bigint NOT NULL DEFAULT 0 CHECK (version >= 0));INSERT INTO inventory(sku, stock) VALUES ('B1', 5), ('B2', 8);CREATE TABLE reservation ( request_id text PRIMARY KEY, sku text NOT NULL REFERENCES inventory(sku), quantity integer NOT NULL CHECK (quantity > 0));Predicted behavior: Creates inventory and reservation tables with key, reference and quantity constraints.
PostgreSQL DDL, not executed.
Additive outbox migration
Source-reviewed, NOT RUN. File lab-fixtures/database-architecture-v43/V2__outbox.sql; use the companion lab README.
CREATE TABLE outbox ( event_id text PRIMARY KEY REFERENCES reservation(request_id), sku text NOT NULL REFERENCES inventory(sku), quantity integer NOT NULL CHECK (quantity > 0), published_at timestamptz);CREATE TABLE processed_event (event_id text PRIMARY KEY);CREATE TABLE delivery_summary (sku text PRIMARY KEY, total bigint NOT NULL CHECK (total >= 0));Predicted behavior: Adds durable event and consumer state tables without removing existing columns.
Apply after V1; migration runner execution pending.
Common mistakes
Editing V1 after deployment creates checksum drift. A pre-insert existence check is not a substitute for a UNIQUE constraint. Do not add a required column without validating compatibility and existing rows.
Practice
Implement a compatibility reader for old label "Book" with no new label, and then new label "Book 2". Treat blank new labels as absent. Print both results and the blank fallback.
Expected output:
BookBook 2BookCompare with the manual review criteria.
Official reading: Migration · Constraints. PostgreSQL and Spring execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Schema migrations and constraints — knowledge check
Database transaction and data architecture reasoning.
How should an already applied versioned migration be corrected?
Why combine CHECK(quantity > 0) with NOT NULL?
What prevents two concurrent requests from creating the same request ID?
When remove an old column during expand-contract?
What should be tested before large DDL changes?