Java.DBMigrationTools.How do you undo a Flyway migration?

Short Answer

Flyway lets you undo a migration using special undo scripts — but only if you’re using Flyway Teams Edition.

In open-source Flyway, undo must be done manually (e.g., with a rollback script or by reverting migrations in Git and resetting the DB).

🔍 Flyway Teams Edition: Undo Scripts

To enable automatic rollbacks, you write U__ undo scripts that correspond to versioned migrations.

🛠️ Example

If you have this migration:

V2__add_users_table.sql

You can write this undo file:

U2__drop_users_table.sql

Content:

DROP TABLE users;

Then you can call:

flyway undo

✅ Flyway looks up the most recently applied versioned migration (V2)
✅ Finds the corresponding U2 script
✅ Executes it and removes V2 from flyway_schema_history

⚠️ Notes on Undo Scripts

  • Undo is not repeatable — it’s only for the latest applied migration
  • Only one version can be undone per command
  • Undo does not apply to repeatable migrations (R__)

🧱 Open Source Workarounds

If you’re using Flyway Community Edition (open-source):

  1. Create a manual rollback script (e.g., rollback.sql)
  2. Run it manually if something goes wrong
  3. Or, if you’re in dev: reset the DB + clean + re-migrate:
flyway clean
flyway migrate

⚠️ flyway clean deletes all schema objects — only use in dev/test environments.

📌 Key Takeaways

✅ In Flyway Teams, use U__ scripts + flyway undo to rollback versioned migrations
❌ In Community Edition, there is no automatic undo — handle rollbacks manually
✅ Best practice: write custom rollback scripts or ensure your migrations are idempotent and safe

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.What is a Flyway baseline?

A Flyway baseline tells Flyway:

“Start tracking from this version — assume all migrations before this are already applied.”

It lets you start using Flyway with an existing database without re-running old scripts.


🔍 Detailed Explanation

Imagine you have a production database with many tables, but you’re just now introducing Flyway.

If you add versioned migration files like:

V1__init_schema.sql
V2__add_users.sql

Flyway will try to apply them from scratch — and crash, because the tables already exist.

Solution: Use a baseline

🛠️ How to Baseline a Database

You run:

flyway baseline

Or in Java:

flyway.baseline();

Or configure it via properties:

flyway.baselineVersion=1
flyway.baselineDescription=Baseline existing schema
flyway.baselineOnMigrate=true

This creates the flyway_schema_history table with a starting version (e.g. 1), without running any scripts.

💡 When to Use a Baseline

ScenarioShould You Baseline?
Existing schema, no Flyway yet✅ Yes
Legacy systems with hundreds of tables✅ Yes
Fresh, empty database❌ No — start with V1

🧾 What Gets Recorded?

In flyway_schema_history:

installed_rankversiondescriptionsuccess
11Baseline existing schema

Now Flyway knows to start from V2 and ignore earlier scripts.


⚠️ Important Notes

  • You can only baseline before any migrations are applied
  • If the history table exists, baseline() will fail unless it was empty
  • Useful with baselineOnMigrate=true for auto-baselining on first migration

📌 Key Takeaways

flyway baseline sets the starting point for tracking in a live schema
✅ Prevents Flyway from reapplying already existing changes
✅ Ideal for introducing Flyway into production projects
✅ Sets up versioning safely without touching existing data

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.Can you use Java code to write Flyway migrations?

Short Answer

Yes, you can write migrations in Java by implementing the JavaMigration interface or extending BaseJavaMigration.
This allows you to write complex, logic-driven database changes in code, including loops, conditional logic, or calling other APIs.

🔍 How to Write a Java-Based Migration

✅ Step 1: Create a class like this:

import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;

public class V3__Add_default_users extends BaseJavaMigration {
    @Override
    public void migrate(Context context) throws Exception {
        try (var statement = context.getConnection().createStatement()) {
            statement.execute("INSERT INTO users (name, email) VALUES ('admin', 'admin@example.com')");
        }
    }
}

✅ Step 2: Place the file in:

src/main/java/db/migration/

📦 By default, Flyway scans this package:

db.migration

🧠 Java Migration Naming Convention

TypeNaming Format
VersionedV3__Add_default_users.java
RepeatableR__Seed_data.java

Same naming rules apply as for SQL files.

✅ When to Use Java Migrations

Use CaseWhy Java Helps
Conditional logicHandle “if exists” / “if not” programmatically
Complex data transformationsJava gives more control than plain SQL
Interacting with external systemsAPI calls, config checks, auditing
Platform-agnostic logicAvoid SQL dialect issues

⚠️ Limitations

  • No support for undo migrations in Java
  • You still need to track the version and description manually in the class name
  • Slightly more setup effort than SQL

📌 Key Takeaways

✅ Flyway supports Java-based migrations for advanced, logic-heavy use cases
✅ Use BaseJavaMigration to create versioned migrations in Java
✅ Name your classes like V2__Description.java and place them under db.migration
✅ Ideal when SQL is not expressive or safe enough for your migration logic

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.What is flyway.migrate() used for?

**flyway.migrate()** is the core method in Flyway used to apply pending migrations to your database.

It scans the migration files, checks which ones haven’t been applied (based on flyway_schema_history), and executes them in order.


🧠 When Would You Use It?

  • In Java code (e.g. Spring, CLI tools, or tests) to trigger migrations programmatically
  • As an alternative to the CLI command:
flyway migrate

🛠️ Example (Java API)

Flyway flyway = Flyway.configure()
    .dataSource("jdbc:postgresql://localhost:5432/mydb", "user", "password")
    .load();

flyway.migrate();

✅ This connects to the database
✅ Looks for migration files in the default location (db/migration)
✅ Applies any unapplied V__ or R__ migration files
✅ Logs them in flyway_schema_history


🔍 What Does It Actually Do?

  1. Scans migration files (in classpath or specified location)
  2. Checks what’s already applied (via flyway_schema_history)
  3. Validates checksums and version order
  4. Executes unapplied versioned and repeatable migrations
  5. Updates the tracking table with new entries

🚫 It Will Not:

  • Re-run already executed versioned migrations
  • Run undo scripts (U__) — those require explicit commands
  • Automatically repair broken checksums — for that, use flyway.repair()

✅ When to Use flyway.migrate() (Instead of CLI)

  • Inside a Spring Boot app’s startup logic
  • In JUnit tests that need fresh schema setup
  • In custom admin tools or bootstrap scripts

📌 Key Takeaways

flyway.migrate() is the Java method to apply migrations programmatically
✅ It works just like the flyway migrate CLI command
✅ Applies pending versioned and repeatable migrations, logs them, and ensures safe, idempotent schema changes

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.What happens if you rename a Flyway migration file?

If you rename a Flyway migration file that was already executed, Flyway will treat it as a new migration and might:

  • ❌ Try to re-run it (if version number changes)
  • ❌ Throw a checksum error (if only filename changes)
  • ✅ Require repair to fix inconsistencies

🔎 What Happens Depends On the Change

1. 🔁 Renaming a Versioned Migration (e.g., V1__init.sql → V1__initial_setup.sql)

  • Same version (V1), new description
  • ❌ Flyway compares checksums → checksum mismatch
  • 🔒 Migration is not re-run, but Flyway throws a validation error

To fix:

flyway repair

This tells Flyway: “Yes, I deliberately changed the file name or contents — trust me.”

2. 🆕 Changing the Version (V1 → V2)

E.g., V1__init.sqlV2__init.sql

  • ✅ Flyway sees this as a new migration
  • ❌ It runs it again, even if the contents are identical to V1
  • ⛔ Can result in duplicate changes, errors, or schema conflicts

3. 🔁 Renaming a Repeatable Migration (R__...)

  • The description part (after R__) is the unique identifier
  • Renaming it → Flyway thinks it’s a new repeatable
  • ✅ Re-runs the new one
  • ✅ Deletes the old one from tracking

📋 Summary Table

ScenarioResultSolution
Rename file (same version, diff description)❌ Checksum mismatchflyway repair
Rename + change version❌ Treated as new migration → re-runAvoid, or manually manage
Rename repeatable migration✅ Re-run with new name, old one removedAcceptable if intentional

✅ Best Practices

  • 🔒 Never rename versioned migration files after they are applied
  • ✅ If you must rename → follow with flyway repair to fix metadata
  • 🔁 Repeatable migrations can be renamed, but do it thoughtfully
  • 🧪 Always test migrations in a staging DB before production

📌 Key Takeaways

✅ Renaming a Flyway migration can break integrity checks or cause re-execution
✅ Versioned migrations are sensitive to filenames and checksums
✅ Use flyway repair when you intentionally rename or edit an applied migration
❌ Avoid renaming files casually in production environments

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.What’s the difference between versioned and repeatable migrations?

  • Versioned migrations run once, in a strict order, and never again.
  • Repeatable migrations can run multiple times — they’re re-applied whenever the file changes.

They serve different purposes in managing your database schema.


🔍 Detailed Comparison

FeatureVersioned MigrationsRepeatable Migrations
File NamingV1__create_users.sqlR__refresh_views.sql
Execution CountOnceRe-applied when content changes
Use CaseSchema evolutionViews, stored procedures, seed data
Tracked ByVersion number (V1, V2, etc.)Description (e.g., R__refresh_data)
Checksum SensitivityErrors if checksum changes (unless repaired)Triggers re-execution if checksum changes
Execution OrderStrict version order (1 → 2 → 3…)After all versioned migrations
Can be undone?✅ (with U__undo.sql)❌ (not supported by default)

🧪 Example — Versioned Migration

V1__create_users_table.sql
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100)
);

✅ Runs once, logged in flyway_schema_history, never runs again unless manually repaired or rolled back.

🧪 Example — Repeatable Migration

R__create_views.sql
CREATE OR REPLACE VIEW active_users AS
SELECT * FROM users WHERE active = true;

✅ Will re-run any time this file changes (checksum is re-calculated on each migrate)

🔄 When Do Repeatable Migrations Run?

  1. After all versioned migrations
  2. If:
    • The file content changed (checksum mismatch)
    • It has never run before

📌 Key Takeaways

✅ Use versioned migrations for all structural schema changes (tables, columns, constraints)
✅ Use repeatable migrations for redefinable objects (views, stored procedures, triggers, seed data)
✅ Repeatables help you keep non-critical DDL up-to-date across environments

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.What is the flyway_schema_history table?

The flyway_schema_history table is a metadata table automatically created by Flyway in your database.
It records which migrations have been applied, in what order, by whom, and when — ensuring each migration is executed exactly once.


🔎 Detailed Explanation

When you run flyway migrate, Flyway:

  1. Checks if flyway_schema_history exists — if not, it creates it
  2. Scans your migration files (e.g., V1__init.sql, V2__add_table.sql)
  3. Compares them against what’s already been recorded
  4. Applies only the new (unapplied) migrations
  5. Logs each successfully applied migration as a new row

📋 Key Columns in flyway_schema_history

Column NameDescription
installed_rankOrder of execution (starts at 1)
versionVersion number (e.g., 1, 2.1, 3.0)
descriptionHuman-friendly name (from filename, like create_users_table)
typeType of migration (SQL, JDBC, UNDO, REPEATABLE)
scriptExact filename applied (V2__add_email_column.sql)
checksumHash of the file contents for integrity verification
installed_byDatabase user who executed the migration
installed_onTimestamp when migration was applied
successWhether the migration succeeded (1 for success, 0 for failure)

🧠 Why It Matters

  • ✅ Prevents Flyway from re-applying the same migrations
  • ✅ Detects checksum mismatches if a migration file is modified
  • ✅ Ensures your environments stay in sync
  • ✅ Enables repeatable migrations and undo tracking

🔄 Example Entry

installed_rankversiondescriptionscriptsuccess
11init_schemaV1__init_schema.sql1
22add_users_tableV2__add_users_table.sql1
33add_index_on_emailV3__add_index_on_email.sql1

📌 Key Takeaways

flyway_schema_history is Flyway’s way of tracking migration progress
✅ Ensures that every migration is applied exactly once and in order
✅ Enables rollback, validation, and schema safety across environments

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.What naming convention does Flyway use for migration files?

Flyway uses a structured naming convention for migration files:

V<Version>__<Description>.sql

✅ The V stands for versioned migration
✅ A double underscore __ separates the version from the description
✅ The description is free-form (no spaces) and helps identify the purpose
✅ The file must end in .sql (or .java for Java-based migrations)

🔎 Detailed Breakdown

🔸 Example:

V1__create_users_table.sql
V2__add_email_column.sql
V3__create_orders_table.sql

V1, V2, V3 → version numbers (can be integers or dotted like 1.1, 2.5.3)

__ (double underscore) → required separator

create_users_table → optional human-readable description (use snake_case)

🧪 Special File Types

TypeNaming FormatPurpose
VersionedV1__init.sqlRun in order, exactly once
UndoU1__undo_init.sql(optional) Used to undo versioned migration V1
RepeatableR__refresh_materialized_view.sqlRe-run when file checksum changes

⚠️ Important Notes

  • Versions must increase monotonically (V1, V2, V3, …)
  • Descriptions must not contain spaces
  • Flyway sorts migrations based on version number
  • You cannot have two migrations with the same version

✅ File System Example

/resources/db/migration/
├── V1__init_schema.sql
├── V2__add_users_table.sql
├── V3__add_roles_table.sql
├── R__refresh_views.sql

📌 Key Takeaways

✅ The standard Flyway naming pattern is V<version>__<description>.sql
✅ Use U<version>__... for undo and R__... for repeatable migrations
✅ Naming is how Flyway orders, tracks, and applies migrations safely

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.What is Flyway?

Flyway is a lightweight, Java-based database migration tool that helps you version, manage, and automate schema changes using plain SQL or Java migration scripts.

It’s simple, fast, and widely used in microservices, CI/CD pipelines, and Spring Boot projects.


🔎 Detailed Explanation

Flyway works by:

  1. Keeping a migration history table (flyway_schema_history) in your database
  2. Applying migration files in order, based on version numbers in filenames (e.g. V1__init.sql)
  3. Ensuring each migration is only applied once per environment
  4. Supporting both forward migrations and undo scripts

🛠️ Typical Workflow

  1. You create a migration file:
V1__create_users_table.sql

Flyway runs it and logs it in flyway_schema_history

You create the next version:

V2__add_email_to_users.sql

Flyway detects the new file and applies it

💡 File Naming Convention

File NameMeaning
V1__init.sqlVersion 1 – initial setup
V2__add_column.sqlVersion 2 – add a column
U2__undo_add_column.sqlUndo script for version 2 (optional)
R__seed_data.sqlRepeatable migration (re-runs on change)

✅ Features

  • Supports SQL-based and Java-based migrations
  • Works with almost any RDBMS (PostgreSQL, MySQL, Oracle, etc.)
  • Easy to plug into Spring Boot
  • Supports baseline, repair, clean, and undo
  • Integrates well with CI/CD tools like Jenkins, GitLab, etc.

📌 Key Takeaways

✅ Flyway is a simple, reliable tool for versioning your database schema
✅ Uses a filename-based versioning system and a tracking table
✅ Works well with SQL or Java, and is especially popular in Spring Boot ecosystems
✅ Keeps your environments in sync and repeatable

Posted in Без рубрики | Leave a comment

Java.DBMigrationTools.What is a logicalFilePath?

Short Answer

The logicalFilePath is an identifier for a changelog file that Liquibase uses internally to track changesets — instead of the physical file path.

It helps ensure consistent tracking of changesets even if the file is moved, renamed, or used in a different environment or CI/CD path.

🔎 Detailed Explanation

By default, Liquibase identifies a changeset using:

ID + AUTHOR + FILENAME
  • ID — unique within the file
  • AUTHOR — who created it
  • FILENAME — path to the changelog file (e.g., src/main/resources/db/changelog.xml)

If the file is renamed or moved, that FILENAME changes — and Liquibase thinks it’s a different changeset, which can cause duplicate execution or checksum errors ❌.

🎯 Enter logicalFilePath

You can override the filename tracking with a stable, logical path:

<databaseChangeLog logicalFilePath="changelog/main.xml"
                   xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   ...>

Even if the physical file moves to a different folder, the logicalFilePath stays the same, so Liquibase knows it’s the same changeset.

🧠 Use Cases

Use CaseBenefit of logicalFilePath
CI/CD pipelines with different folder layoutsPrevents duplicate changeset execution
Renaming/moving changelog filesMaintains consistency and checksum integrity
Working across multiple branches or reposKeeps changeset identity stable

✅ With logicalFilePath, changesets are tracked like this:

ID + AUTHOR + LOGICAL_FILE_PATH

Instead of:

ID + AUTHOR + PHYSICAL_FILE_PATH

📌 Key Takeaways

logicalFilePath gives a stable identity to changelogs across environments
✅ Prevents duplicate execution or checksum errors if a file is renamed or moved
✅ Essential for collaborative projects, CI/CD, or multi-repo setups

Posted in Без рубрики | Leave a comment