Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix: prevent AddAmountToTransfers migration aborting on legacy transfer data (#2795)

RealDiligent98bf563458d5
diff --git a/db/migrate/20260628171409_add_amount_to_transfers.rb b/db/migrate/20260628171409_add_amount_to_transfers.rb
index e68a3f1c27..3005d59475 100644
--- a/db/migrate/20260628171409_add_amount_to_transfers.rb
+++ b/db/migrate/20260628171409_add_amount_to_transfers.rb
@@ -5,9 +5,14 @@ class AddAmountToTransfers < ActiveRecord::Migration[8.1]
reversible do |dir|
dir.up do
# Backfill principal from outflow entries: amount = outflow_entry.amount - source_fee_amount
+ # Historical rows can violate the modern sign convention (negative
+ # outflow amounts) or carry fees larger than the entry amount, which
+ # would produce a negative principal and trip the check constraint
+ # below — aborting the migration and blocking the whole upgrade.
+ # Normalize with ABS and clamp at zero instead (#2653).
execute <<~SQL
UPDATE transfers
- SET amount = e.amount - COALESCE(transfers.source_fee_amount, 0)
+ SET amount = GREATEST(ABS(e.amount) - COALESCE(transfers.source_fee_amount, 0), 0)
FROM entries e
WHERE e.entryable_id = transfers.outflow_transaction_id
AND e.entryable_type = 'Transaction';