Repository navigation
refactor: migration tooling - #3595
Conversation
📝 WalkthroughWalkthroughRefactors migration initialization to an options-backed Changes
Sequence DiagramsequenceDiagram
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)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 usemigrator.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) andtest/app/testenv.go(line 93).
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 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.gotest/app/testenv.goopenmeter/subscription/testutils/db.goapp/common/database.gotools/migrate/migrate.gotools/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
omMigrationsto lowercase improves the API design. The logger being accessible is useful for the newCloseOrLogErrormethod.Also applies to: 74-74
76-96: Solid validation pattern!The
MigrationsConfigstruct with its validation method is clean and thorough. Usingerrors.Jointo collect all validation errors at once provides better developer experience.
98-102: Great default config!Exposing
OMMigrationsConfigas a ready-to-use default configuration makes the API very convenient for standard use cases.
104-126: Excellent dependency injection pattern!The
MigrateOptionsstruct 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
Newfunction 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
WaitForMigrationJoba method onMigrateis 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
MigrateOptionsAPI and ensures cleanup withdefer 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.Newconstructor withMigrateOptions, ensuring the refactored API works as expected.
183-184: Nice use of the config for parameterization!Using
migrate.OMMigrationsConfig.StateTableNameinstead of a hardcoded value makes the test more maintainable and keeps it in sync with the actual configuration.
5d87064 to
4b17f8c
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 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.goapp/common/database.gotools/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
MigrateOptionswiring here—it reads clearly and keeps the test setup transparent.
183-184: Good call using the configured state table name.Passing
OMMigrationsConfig.StateTableNamekeeps 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.Newwith a shared close helper keeps this path tidy, and the switch cleanly separates the job-based flow. Nicely done.
| ver, dirty, err := m.Version() | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if dirty { | ||
| return fmt.Errorf("database is dirty, please run migrations manually") | ||
| } | ||
|
|
There was a problem hiding this comment.
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.
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