Skip to content

refactor: migration tooling - #3595

Merged
turip merged 3 commits into
mainfrom
refactor/migration-tooling
Nov 12, 2025
Merged

turip merged 3 commits into
mainfrom
refactor/migration-tooling

Conversation

@turip

@turip turip commented Nov 10, 2025 •

Copy link
Copy Markdown
Member

Overview

Fixes comments from this PR: #3594

We are also shifting into a direction where the migrator becomes a fully fledged struct, so that we have better transparency on the config.

Notes for reviewer

Summary by CodeRabbit

  • Refactor
    • Migration setup moved to an options-based configuration and a unified migrator workflow for clearer initialization, stronger error handling, and guaranteed resource cleanup.
  • New Features
    • Added explicit wait and close controls for migrations and validation of migration configuration.
  • Style
    • Added an informational "database initialized" log for improved visibility.

@coderabbitai

coderabbitai Bot commented Nov 10, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Refactors migration initialization to an options-backed Migrate API. Adds MigrationsConfig and MigrateOptions, replaces direct/free migrate calls with migrate.New(MigrateOptions) returning *Migrate, adds WaitForMigrationJob and CloseOrLogError methods, and keeps Ent auto-migrate as an early-return path.

Changes

Cohort / File(s) Summary
Core migration refactor
tools/migrate/migrate.go
Adds MigrationsConfig and MigrateOptions with validation, introduces Migrate type and New(MigrateOptions) constructor, adds WaitForMigrationJob and CloseOrLogError methods, and internalizes setMigrationTableName.
Migration tests & helpers
tools/migrate/migrate_test.go
Tests updated to use migrate.New(migrate.MigrateOptions{...}), reference OMMigrationsConfig/StateTableName, and provide a logger via testutils.NewLogger(t).
App DB init
app/common/database.go
Replaces direct migrate usage with migrate.New(...), defers migrator.CloseOrLogError(), uses migrator.Up() / migrator.WaitForMigrationJob(), and preserves Ent auto-migrate as an early-return.
Test setup & utilities
openmeter/subscription/testutils/db.go, test/app/testenv.go, test/billing/suite.go
Switches from positional NewMigrate(...) to migrate.New(migrate.MigrateOptions{...}), passes logger from testutils.NewLogger(t), defers CloseOrLogError(), and calls migrator.Up().

Sequence Diagram

sequenceDiagram
    autonumber
    participant Init as Initializer
    participant API as migrate.New(options)
    participant Migr as *Migrate
    participant DB as Database

    Init->>API: Build MigrateOptions{ConnectionString, Migrations, Logger}
    Init->>API: New(options)
    API->>API: Validate options, create source/driver
    API-->>Migr: return *Migrate (with logger)
    Init->>Init: defer Migr.CloseOrLogError()
    Init->>Migr: Up()
    Migr->>DB: apply migrations
    alt job-based migration
        Init->>Migr: WaitForMigrationJob(opts)
        loop poll
            Migr->>DB: check migration job status
        end
    end
    Init->>Migr: CloseOrLogError() (deferred)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Pay extra attention to:
    • Validation logic in tools/migrate/migrate.go (MigrationsConfig.Validate, MigrateOptions.Validate) and error paths.
    • Proper resource cleanup: CloseOrLogError() usage and Ent early-return in app/common/database.go.
    • Tests and any SQL that references the migration state table name (OMMigrationsConfig.StateTableName).

Possibly related PRs

Suggested reviewers

  • tothandras
  • chrisgacsal
  • GAlexIHU

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: migration tooling' accurately describes the main change—a refactoring of the migration system to use a structured options-based approach instead of direct function calls.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/migration-tooling

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@turip turip added the release-note/ignore Ignore this change when generating release notes label Nov 10, 2025
@turip
turip marked this pull request as ready for review November 10, 2025 16:16
@turip
turip requested a review from a team as a code owner November 10, 2025 16:16
@turip
turip requested a review from GAlexIHU November 10, 2025 16:17

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
openmeter/subscription/testutils/db.go (1)

53-64: Consider using the new cleanup method for consistency.

This code correctly creates the migrator with the new API, but the deferred cleanup still uses the old migrator.Close() pattern. Other files in this PR use migrator.CloseOrLogError() which provides better error logging.

For consistency with other test files, consider updating to:

-	defer func() {
-		if migrator != nil {
-			if err1, err2 := migrator.Close(); err1 != nil || err2 != nil {
-				t.Fatalf("failed to close migrator: %v", errors.Join(err1, err2))
-			}
-		}
-	}()
+	defer func() {
+		if migrator != nil {
+			migrator.CloseOrLogError()
+		}
+	}()

This simplifies the code and aligns with the pattern used in test/billing/suite.go (line 116) and test/app/testenv.go (line 93).

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 76c032a and e528f75.

📒 Files selected for processing (6)
  • app/common/database.go (1 hunks)
  • openmeter/subscription/testutils/db.go (1 hunks)
  • test/app/testenv.go (1 hunks)
  • test/billing/suite.go (1 hunks)
  • tools/migrate/migrate.go (4 hunks)
  • tools/migrate/migrate_test.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

⚙️ CodeRabbit configuration file

**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

Files:

  • test/billing/suite.go
  • test/app/testenv.go
  • openmeter/subscription/testutils/db.go
  • app/common/database.go
  • tools/migrate/migrate.go
  • tools/migrate/migrate_test.go
**/*_test.go

⚙️ CodeRabbit configuration file

**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.
When appropriate, recommend e2e tests for critical changes.

Files:

  • tools/migrate/migrate_test.go
🧬 Code graph analysis (6)
test/billing/suite.go (1)
tools/migrate/migrate.go (4)
  • New (129-155)
  • MigrateOptions (104-108)
  • OMMigrationsConfig (98-102)
  • NewLogger (69-71)
test/app/testenv.go (1)
tools/migrate/migrate.go (4)
  • New (129-155)
  • MigrateOptions (104-108)
  • OMMigrationsConfig (98-102)
  • NewLogger (69-71)
openmeter/subscription/testutils/db.go (1)
tools/migrate/migrate.go (4)
  • New (129-155)
  • MigrateOptions (104-108)
  • OMMigrationsConfig (98-102)
  • NewLogger (69-71)
app/common/database.go (2)
app/config/postgres.go (4)
  • AutoMigrate (66-66)
  • AutoMigrateEnt (69-69)
  • AutoMigrateMigration (70-70)
  • AutoMigrateMigrationJob (71-71)
tools/migrate/migrate.go (3)
  • New (129-155)
  • MigrateOptions (104-108)
  • OMMigrationsConfig (98-102)
tools/migrate/migrate.go (1)
tools/migrate/fs.go (2)
  • FS (11-14)
  • NewSourceWrapper (24-26)
tools/migrate/migrate_test.go (1)
tools/migrate/migrate.go (4)
  • New (129-155)
  • MigrateOptions (104-108)
  • OMMigrationsConfig (98-102)
  • NewLogger (69-71)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Code Generators
  • GitHub Check: Analyze (go)
🔇 Additional comments (13)
tools/migrate/migrate.go (6)

33-33: Nice refactor!

Making the logger public and renaming omMigrations to lowercase improves the API design. The logger being accessible is useful for the new CloseOrLogError method.

Also applies to: 74-74


76-96: Solid validation pattern!

The MigrationsConfig struct with its validation method is clean and thorough. Using errors.Join to collect all validation errors at once provides better developer experience.


98-102: Great default config!

Exposing OMMigrationsConfig as a ready-to-use default configuration makes the API very convenient for standard use cases.


104-126: Excellent dependency injection pattern!

The MigrateOptions struct makes all dependencies explicit and the validation ensures nothing is missing. The nested validation with error wrapping is particularly nice.


128-155: Clean constructor implementation!

The New function follows best practices: validate early, fail fast, and provide clear error messages. The step-by-step setup is easy to follow.


176-213: Nice method conversion!

Making WaitForMigrationJob a method on Migrate is a good design choice. The integrated logging and clear timeout messages improve observability.

test/billing/suite.go (1)

109-118: Perfect migration setup!

The test properly uses the new MigrateOptions API and ensures cleanup with defer migrator.CloseOrLogError(). This is exactly the pattern we want to see.

test/app/testenv.go (1)

81-93: Clean migration initialization!

The test environment setup correctly uses the new API with proper error handling and cleanup. The error wrapping provides good context.

openmeter/subscription/testutils/db.go (1)

66-72: Migration execution looks good!

The error handling and migration flow is clean and straightforward.

app/common/database.go (2)

46-52: Good separation of migration strategies!

The early return for the Ent migration path keeps the code clean and separates the two different approaches nicely.


54-73: Solid migrator setup and execution!

The migrator initialization uses the new API correctly, and the deferred CloseOrLogError() ensures proper cleanup. The switch statement clearly handles the different migration strategies.

tools/migrate/migrate_test.go (2)

93-97: Great test coverage of the new API!

The test properly exercises the new migrate.New constructor with MigrateOptions, ensuring the refactored API works as expected.


183-184: Nice use of the config for parameterization!

Using migrate.OMMigrationsConfig.StateTableName instead of a hardcoded value makes the test more maintainable and keeps it in sync with the actual configuration.

Comment thread tools/migrate/migrate.go Resolved
@turip
turip force-pushed the refactor/migration-tooling branch from 5d87064 to 4b17f8c Compare November 11, 2025 08:48

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d87064 and 4b17f8c.

📒 Files selected for processing (6)
  • app/common/database.go (1 hunks)
  • openmeter/subscription/testutils/db.go (1 hunks)
  • test/app/testenv.go (1 hunks)
  • test/billing/suite.go (1 hunks)
  • tools/migrate/migrate.go (4 hunks)
  • tools/migrate/migrate_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/billing/suite.go
  • openmeter/subscription/testutils/db.go
  • test/app/testenv.go
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

⚙️ CodeRabbit configuration file

**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

Files:

  • tools/migrate/migrate_test.go
  • app/common/database.go
  • tools/migrate/migrate.go
**/*_test.go

⚙️ CodeRabbit configuration file

**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.
When appropriate, recommend e2e tests for critical changes.

Files:

  • tools/migrate/migrate_test.go
🧬 Code graph analysis (3)
tools/migrate/migrate_test.go (1)
tools/migrate/migrate.go (4)
  • New (129-155)
  • MigrateOptions (104-108)
  • OMMigrationsConfig (98-102)
  • NewLogger (69-71)
app/common/database.go (2)
app/config/postgres.go (4)
  • AutoMigrate (66-66)
  • AutoMigrateEnt (69-69)
  • AutoMigrateMigration (70-70)
  • AutoMigrateMigrationJob (71-71)
tools/migrate/migrate.go (3)
  • New (129-155)
  • MigrateOptions (104-108)
  • OMMigrationsConfig (98-102)
tools/migrate/migrate.go (1)
tools/migrate/fs.go (2)
  • FS (11-14)
  • NewSourceWrapper (24-26)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Lint
  • GitHub Check: Migration Checks
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Code Generators
  • GitHub Check: Repository Scan
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
tools/migrate/migrate_test.go (2)

93-97: Nice move to the options-based constructor.

Appreciate the explicit MigrateOptions wiring here—it reads clearly and keeps the test setup transparent.


183-184: Good call using the configured state table name.

Passing OMMigrationsConfig.StateTableName keeps the purge logic aligned with whatever table the migrator is actually using.

app/common/database.go (1)

54-73: Appreciate the unified migrator flow.

The shift to migrate.New with a shared close helper keeps this path tidy, and the switch cleanly separates the job-based flow. Nicely done.

Comment thread tools/migrate/migrate.go
Comment on lines +192 to 199
ver, dirty, err := m.Version()
if err != nil {
return err
}
if dirty {
return fmt.Errorf("database is dirty, please run migrations manually")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Handle ErrNilVersion while polling.

Right now WaitForMigrationJob bails out as soon as the database hasn’t run any migrations yet, because Version() returns migrate.ErrNilVersion. That’s exactly the state we’re supposed to wait through, so callers hit an immediate failure on brand-new environments. Let’s treat that error as “version 0” and keep polling instead of returning early.

-		ver, dirty, err := m.Version()
-		if err != nil {
-			return err
-		}
+		ver, dirty, err := m.Version()
+		if errors.Is(err, migrate.ErrNilVersion) {
+			ver = 0
+			err = nil
+		}
+		if err != nil {
+			return err
+		}
🤖 Prompt for AI Agents
In tools/migrate/migrate.go around lines 192 to 199, handle
migrate.ErrNilVersion returned by m.Version() as a non-fatal condition: if err
is migrate.ErrNilVersion treat it like version 0 (and not dirty) and continue
polling instead of returning; only return for other errors. Update the logic to
check errors.Is(err, migrate.ErrNilVersion) and set ver = 0 (and dirty = false)
in that branch, and ensure the "errors" package is imported if not already.

@turip
turip merged commit cd21d44 into main Nov 12, 2025
@turip
turip deleted the refactor/migration-tooling branch November 12, 2025 16:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants