Exposed icon indicating copy to clipboard operation
Exposed copied to clipboard

generateMigrations overwrites its own files: tables sharing a dependency get one name, and only the last survives

Open youndie opened this issue 3 months ago • 6 comments

generateMigrations writes one file per table, and derives each file's name from the first statement in it. A file for a table with a foreign key begins by creating the parent, so every child of one parent produces a file with the same generated description. With the default second-resolution version format, version and description are then both identical, the files overwrite each other, and only the last one survives.

Exposed and the plugin at 1.4.0, Postgres 18 through testContainersImageName, Gradle 9.7.1, JVM 25.

Minimal reproduction

// build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.10"
    id("org.jetbrains.exposed.plugin") version "1.4.0"
}
exposed {
    migrations {
        tablesPackage.set("probe")
        testContainersImageName.set("postgres:18-alpine")
        fileDirectory.set(layout.buildDirectory.dir("gen"))
        filePrefix.set("V"); fileSeparator.set("__"); fileExtension.set(".sql")
    }
}
package probe

object ParentTable : Table("p_parent") {
    val id = varchar("id", 16)
    override val primaryKey = PrimaryKey(id)
}
object ChildOneTable : Table("p_child_one") {
    val id = varchar("id", 16)
    val parentId = varchar("parent_id", 16).references(ParentTable.id)
    override val primaryKey = PrimaryKey(id)
}
object ChildTwoTable : Table("p_child_two") {
    val id = varchar("id", 16)
    val parentId = varchar("parent_id", 16).references(ParentTable.id)
    override val primaryKey = PrimaryKey(id)
}

./gradlew generateMigrations against an empty database produces one file:

V20260825110903__CREATE_TABLE_P_PARENT.sql

containing p_parent and p_child_two. p_child_one is nowhere. Exit code 0, and the log reports # Exposed Migrations Generated 1 migrations.

The mechanism, shown by changing only the version format

fileVersionFormat.set(VersionFormat.MAJOR_MINOR) on the same three tables, nothing else changed:

V1_0__CREATE_TABLE_P_PARENT.sql   ->  p_parent
V2_1__CREATE_TABLE_P_PARENT.sql   ->  p_parent, p_child_one
V3_2__CREATE_TABLE_P_PARENT.sql   ->  p_parent, p_child_two

Three facts fall out of this:

  1. One file per table, each carrying that table's whole dependency closure. Every child's file re-creates the parent.
  2. The description comes from the first statement, which for a child is the parent — hence all three files are CREATE_TABLE_P_PARENT.
  3. With TIMESTAMP_ONLY the version is identical too, so all three resolve to one filename and overwrite each other. What survives is the last, which is why the output above holds p_parent and p_child_two.

So the missing table is not dropped anywhere in the diffing. MigrationUtils.statementsRequiredForDatabaseMigration(ParentTable, ChildOneTable, ChildTwoTable) against the same empty database returns all three CREATE TABLE statements in dependency order, in any argument order. The loss is entirely in how files are named and written.

The second-resolution version is a defect on its own

Three tables with no foreign keys between them:

V20260825110934__CREATE_TABLE_P_ALPHA.sql
V20260825110934__CREATE_TABLE_P_BETA.sql
V20260825110934__CREATE_TABLE_P_GAMMA.sql

Nothing is lost here — the descriptions differ, so the names do. But all three carry the same version, and Flyway rejects that set outright:

FlywayException: Found more than one migration with version 20260825110934

(verified against Flyway 13.3.0). So even the non-lossy output cannot be applied without renaming it by hand.

What would close it

Either half alone fixes the data loss:

  • a version component that distinguishes files produced in one run — a counter, or sub-second precision. This also makes the output applicable, which the current format is not;
  • a description derived from the table the file is for rather than from its first statement.

Both are worth having. The first is what makes the generated set usable by Flyway at all; the second is what makes a file name mean something when you read the directory later.

Why it is worth more than the sum of the two

The failure is silent and the output is plausible. A generated migration missing a table applies cleanly, and the schema it produces is wrong in a way that surfaces much later, in whichever code first touches the absent table. There is no error, no warning, and the count in the log (Generated 1 migrations) is consistent with what was written rather than with what was asked for.

We only noticed because an independent check runs after Flyway in our test suite — MigrationUtils.statementsRequiredForDatabaseMigration(*tables), failing if anything other than DROP INDEX comes back. That is what named the missing table. Reading the generated file would not have: it looks complete.

Smaller, in passing

fileExtension is concatenated without a separator, so fileExtension.set("sql") yields V2026..._CREATE_TABLE_P_PARENTsql. ".sql" is evidently what is wanted; the property name suggests otherwise, and the result is a file Flyway silently ignores.

youndie avatar Aug 25 '26 10:08 youndie

I’d like to work on this. I’m planning to add regression tests for both filename collisions with dependent tables and duplicate migration versions, then update the naming/version generation to guarantee uniqueness within a single generation run. Would this direction be acceptable?

cfcromn avatar Aug 25 '26 14:08 cfcromn

Yes — and the version half alone is sufficient. I re-checked that end to end rather than by reading filenames: with MAJOR_MINOR on the three tables from the report, Flyway 13.3.0 applies all three generated files against Postgres 18 and p_parent, p_child_one and p_child_two all land. So uniqueness within a run closes the data loss on its own, and the description defect becomes a readability problem you can judge separately rather than part of the fix.

One thing worth knowing before you write the tests, because it is not in the report above: an assertion over filenames will not catch the loss. Add a fourth, independent table beside the same parent-and-two-children shape:

object AlphaTable    : Table("q_alpha")     { /* no foreign keys */ }
object ParentTable   : Table("q_parent")    { }
object ChildOneTable : Table("q_child_one") { /* references q_parent */ }
object ChildTwoTable : Table("q_child_two") { /* references q_parent */ }

Four tables in, two files out, three tables' DDL:

V20260825150701__CREATE_TABLE_Q_ALPHA.sql    ->  q_alpha
V20260825150701__CREATE_TABLE_Q_PARENT.sql   ->  q_parent, q_child_two

q_child_one is gone, and the file count agrees with neither the input (4) nor what survived (3). "No two filenames collide" is no better as an assertion — it becomes true the moment versions are unique, and says nothing about content, since the collision is the mechanism rather than the symptom.

What does hold, under any naming scheme, is the union across every generated file: N tables in, N CREATE TABLE statements out. That is the property the current output violates.

That four-table shape may also be the better regression fixture, because it trips both defects at once: the two files above collide by description and carry the same version, so it fails the Flyway check as well. Each case in the report trips only one of the two.

Happy to run a candidate through the reproduction once you have one — it is set up here and takes a few seconds per variant.

youndie avatar Aug 25 '26 15:08 youndie

Thanks for the additional details! I’ve implemented the fix and opened a PR.

I also updated the regression test to cover the four-table case you suggested (Alpha + Parent + two children), and it verifies that all expected table DDL is preserved across the generated migration files.

The fix keeps the first timestamp-based version unchanged and appends an index to subsequent migrations generated in the same run.

PR:

If you have a chance, I’d appreciate it if you could run it against your Flyway/Postgres reproduction as well.

cfcromn avatar Aug 25 '26 15:08 cfcromn

Ran it through the reproduction. It holds on every shape from the report, and the output applies.

Built the branch to mavenLocal as 1.4.0-pr2898, with the Exposed libraries left at the released 1.4.0, and pointed the probe at it. Flyway 13.3.0, Postgres 18, a fresh container per run with the schema dropped in between.

tables in before after Flyway
parent + two children 1 file, p_child_one lost 3 files, all three tables applied 3, all three in the database
independent + parent + two children 2 files, q_child_one lost 4 files, all four tables applied 4, all four in the database
three unrelated 3 files, one shared version 3 files, three versions applied 3

The four-table shape is the one that used to trip both defects at once, and it comes out complete. Thank you for taking this on so quickly.

One configuration where it does not hold yet. fileSeparator defaults to __ and is settable; with a single underscore the index is not distinguishable from the separator:

V20260825170625_CREATE_TABLE_P_PARENT.sql
V20260825170625_1_CREATE_TABLE_P_PARENT.sql
V20260825170625_2_CREATE_TABLE_P_PARENT.sql

Flyway 13.3.0, configured with that same separator, reads the version up to the first one and answers:

FlywayException: Found more than one migration with version 20260825170625
Offenders:
-> V20260825170625_1_CREATE_TABLE_P_PARENT.sql
-> V20260825170625_2_CREATE_TABLE_P_PARENT.sql

A loud failure rather than lost DDL, and it needs a non-default setting — a much smaller thing than the bug itself. Reporting it because it is the same error arriving through a different door, and because the probe was already set up to see it.

youndie avatar Aug 25 '26 17:08 youndie

Thanks for catching the custom separator case.

I’ve updated the fix so subsequent timestamp-based migration versions now use dotted numeric segments (.1, .2, …) instead of _1, 2. This avoids conflicting with fileSeparator = "".

I also added regression coverage for both TIMESTAMP_ONLY and TIMESTAMP_WITHOUT_SECONDS with a single-underscore separator, and the existing four-table data-loss regression still passes.

The PR branch has been updated with the change. If you have a chance, I’d appreciate it if you could run the updated version through your Flyway/Postgres reproduction once more.

cfcromn avatar Aug 25 '26 23:08 cfcromn

Ran the updated branch. The separator case is closed, and nothing else moved.

Built fix/2897-migration-file-collision at 64a9286 into mavenLocal as 1.4.0-pr2898-v2 — a version of its own rather than over 1.4.0, so the probe cannot resolve the earlier build by accident. Exposed libraries left at the released 1.4.0. Flyway 13.3.0, Postgres 18, schema dropped between runs, and Flyway configured with the same fileSeparator the files were written with.

shape separator version format files Flyway tables in the database
parent + two children __ TIMESTAMP_ONLY 3 applied 3 p_parent, p_child_one, p_child_two
independent + parent + two children __ TIMESTAMP_ONLY 4 applied 4 q_alpha, q_parent, q_child_one, q_child_two
three unrelated __ TIMESTAMP_ONLY 3 applied 3 f_alpha, f_beta, f_gamma
parent + two children _ TIMESTAMP_ONLY 3 applied 3 p_parent, p_child_one, p_child_two
parent + two children _ TIMESTAMP_WITHOUT_SECONDS 3 applied 3 p_parent, p_child_one, p_child_two

The last two are the ones that failed before. With the dotted segment Flyway reads three distinct versions where it used to read one:

V20260826062237_CREATE_TABLE_P_PARENT.sql      -> 20260826062237
V20260826062237.1_CREATE_TABLE_P_PARENT.sql    -> 20260826062237.1
V20260826062237.2_CREATE_TABLE_P_PARENT.sql    -> 20260826062237.2

Checked against a case that is known to fail, so that "it passes" means something. The previous build is still in mavenLocal; pointing the probe back at it reproduces the old output and the old error, and only then does the new one pass:

1.4.0-pr2898     V20260826062457_1_...  ->  FlywayException: Found more than one migration with
                                            version 20260826062457
1.4.0-pr2898-v2  V20260826062457.1_...  ->  applied 3

Thank you — both rounds turned around quickly.

youndie avatar Aug 26 '26 06:08 youndie