8000 fix: reversed migration order by gfyrag · Pull Request #963 · formancehq/ledger · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix: reversed migration order #963

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2025
Merged

fix: reversed migration order #963

merged 1 commit into from
Jun 13, 2025

Conversation

gfyrag
Copy link
Contributor
@gfyrag gfyrag commented Jun 13, 2025

No description provided.

@gfyrag gfyrag requested a review from a team as a code owner June 13, 2025 10:16
Copy link
coderabbitai bot commented Jun 13, 2025

Walkthrough

The order of two database migration steps in the system migrations file has been swapped. The migration that sets the default metadata on ledgers now follows the migration that adds the json_compact SQL function, with their respective SQL commands exchanged accordingly. No other logic or error handling has been altered.

Changes

File(s) Change Summary
internal/storage/system/migrations.go Swapped the order and SQL contents of the migrations for setting default metadata and adding json_compact function. No other changes.

Possibly related PRs

  • formancehq/ledger#926: Adds a migration for the json_compact function and updates memento format, both involving the json_compact function but affecting different migrations and tables.
  • formancehq/ledger#927: Introduced the original migration for the json_compact function, which is directly modified by this PR.

Suggested reviewers

  • paul-nicolas

Poem

In the warren where migrations hop,
Two steps swapped places—flip and flop!
Metadata and functions, now in line,
The ledgers and JSON will work just fine.
With every hop and every swap,
This bunny keeps the schema top! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch fix/reverse-migration-order
  • Post Copyable Unit Tests in Comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
internal/storage/system/migrations.go (1)

240-247: Minor hardening: make the “set default” statement idempotent

ALTER TABLE … ALTER COLUMN … SET DEFAULT will error if a different default is already present (unlikely, but possible in forks or manual hot-fixes).
You could guard the operation with a dynamic check:

-					_, err := tx.ExecContext(ctx, `
-						alter table _system.ledgers
-						alter column metadata set default '{}'::jsonb;
-					`)
+					_, err := tx.ExecContext(ctx, `
+						DO $$
+						BEGIN
+						  IF (
+						    SELECT pg_get_expr(adbin, adrelid)
+						    FROM pg_attrdef
+						    WHERE adrelid = '_system.ledgers'::regclass
+						      AND adnum = (
+						        SELECT attnum
+						        FROM pg_attribute
+						        WHERE attrelid = '_system.ledgers'::regclass
+						          AND attname = 'metadata'
+						      )
+						  ) IS DISTINCT FROM '''{}''::jsonb' THEN
+						    ALTER TABLE _system.ledgers
+						    ALTER COLUMN metadata SET DEFAULT '{}'::jsonb;
+						  END IF;
+						END$$;
+					`)

Not strictly required but ensures full idempotency if someone tweaks the default out-of-band.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bee3bc9 and 1bf4f21.

📒 Files selected for processing (1)
  • internal/storage/system/migrations.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Tests
  • GitHub Check: Dirty
🔇 Additional comments (1)
internal/storage/system/migrations.go (1)

231-238:

❓ Verification inconclusive

Re-ordering is fine, but double-check migration history across environments

Because Bun keys migrations by name and stores every applied name in _migrations, the swap will not re-execute anything that has already run.
However, if you have any database that:

  1. Ran only one of the two migrations (e.g. CI snapshot or a blue/green rollout paused between the two), and
  2. Has that migration recorded after the other in the _migrations table,

then the new order could trigger an “unexpected migration” error.

Run the quick check below against an existing staging/prod database before shipping to be sure both names are present and in any order:

If both rows exist, you are safe; if only one row exists you may need a manual insert/delete.
No code change required, just operational awareness.


🏁 Script executed:

#!/bin/bash
# List the two migrations and their applied order
psql "$DATABASE_URL" -c \
  "SELECT name, run_at FROM _migrations WHERE name IN
  ('Add json_compact function', 'set default metadata on ledgers')
  ORDER BY run_at;"

Length of output: 258


Verify migration order in all environments

Reordering these two migrations is safe in code—Bun keys by migration name and won’t re-execute already applied names—but you must confirm your staging/prod databases haven’t applied only one of them in the “wrong” order, which would trigger an unexpected-migration error.

Please run this against each target database before deploying:

psql "$DATABASE_URL" -c \
"SELECT na
8000
me, run_at
 FROM _migrations
 WHERE name IN (
   'Add json_compact function',
   'set default metadata on ledgers'
 )
 ORDER BY run_at;"
  • If you see both rows, in any order, you’re all set.
  • If only one row appears, you’ll need to manually insert or remove the missing entry to realign the history.

No code changes are required—just operational awareness.

Copy link
codecov bot commented Jun 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 82.72%. Comparing base (739e4b4) to head (1bf4f21).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #963      +/-   ##
==========================================
- Coverage   82.79%   82.72%   -0.08%     
==========================================
  Files         142      142              
  Lines        8028     8028              
==========================================
- Hits         6647     6641       -6     
- Misses       1056     1060       +4     
- Partials      325      327       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@gfyrag gfyrag added this pull request to the merge queue Jun 13, 2025
Merged via the queue into main with commit 23b6baf Jun 13, 2025
9 of 10 checks passed
@gfyrag gfyrag deleted the fix/reverse-migration-order branch June 13, 2025 10:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0