The personal finance app for everyone (by everyone)
Ruby
Make entries.excluded NOT NULL (#5853)
David Gilecf8c1078946
diff --git a/app/models/entry.rb b/app/models/entry.rbindex b6600bb965..5ff244f4cf 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -24,6 +24,9 @@ class Entry < ApplicationRecordmonetize :amount+ # A blank form value casts to nil, which the NOT NULL column refuses.+ normalizes :excluded, with: ->(excluded) { excluded || false }, apply_to_nil: true+belongs_to :accountbelongs_to :transfer, optional: truebelongs_to :import, optional: truediff --git a/app/models/goal.rb b/app/models/goal.rbindex 0f7d1eb7ac..2cf9e2dbe6 100644--- a/app/models/goal.rb+++ b/app/models/goal.rb@@ -388,7 +388,7 @@ class Goal < ApplicationRecorddormant = Entry.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(account_id: account_ids - valued_ids)- .where("entries.excluded IS NOT TRUE")+ .where(entries: { excluded: false }).merge(Transaction.excluding_pending).distinct.pluck(:account_id)diff --git a/app/models/portfolio/flow_classifier.rb b/app/models/portfolio/flow_classifier.rbindex 8a4c399022..01514a61f7 100644--- a/app/models/portfolio/flow_classifier.rb+++ b/app/models/portfolio/flow_classifier.rb@@ -320,15 +320,14 @@ class Portfolio::FlowClassifier# A security moved between accounts has no Transfer row; its other leg is# the opposite-quantity Transfer trade on the same security and date in- # another account. entries.excluded is nullable, and a NULL leg is live- # here as it is to #classify, hence IS NOT TRUE rather than = false.+ # another account.def security_transfer_counterpart_in_scope?(entry, trade)Entry.joins("JOIN trades counterpart_trades ON counterpart_trades.id = entries.entryable_id AND entries.entryable_type = 'Trade'").where(account_id: scope_account_ids).where.not(account_id: entry.account_id).where(date: entry.date)- .where("entries.excluded IS NOT TRUE")+ .where(excluded: false).where(counterpart_trades: { security_id: trade.security_id, qty: -trade.qty, investment_activity_label: TRANSFER_LABEL }).exists?end@@ -371,9 +370,7 @@ class Portfolio::FlowClassifier# jit_above_cost; JIT compilation then took longer than the query.# Grouped and hash-joined, the cost stays proportional to the rows read.#- # entries.excluded is nullable, and a NULL leg is live here as it is to- # #classify, hence IS NOT TRUE rather than = false. uuid has no MIN or- # MAX, so the ids are compared as text.+ # uuid has no MIN or MAX, so the ids are compared as text.def security_transfer_legs_sql<<~SQL.squishSELECT@@ -387,7 +384,7 @@ class Portfolio::FlowClassifierON counterpart_trades.id = counterpart_entries.entryable_idAND counterpart_entries.entryable_type = 'Trade'WHERE counterpart_entries.account_id = ANY(#{scope_ids_sql})- AND counterpart_entries.excluded IS NOT TRUE+ AND counterpart_entries.excluded = falseAND counterpart_trades.investment_activity_label = '#{TRANSFER_LABEL}'GROUP BY counterpart_entries.date, counterpart_trades.security_id, counterpart_trades.qtySQLdiff --git a/app/views/api/v1/transactions/_transaction.json.jbuilder b/app/views/api/v1/transactions/_transaction.json.jbuilderindex 86f071d6eb..56d6d2f8c6 100644--- a/app/views/api/v1/transactions/_transaction.json.jbuilder+++ b/app/views/api/v1/transactions/_transaction.json.jbuilder@@ -55,10 +55,9 @@ json.amount_currency transaction.entry.currency# Excluded entries are left out of budget and report totals, and splitting# marks the parent excluded. A split parent's amount is carried by its-# children, so a client summing a list should skip the parent. entries.excluded-# is nullable, so the predicate keeps the field a boolean. Callers that render-# many rows pass split_parent_ids (the set of entry ids with children) so-# split_parent costs no query per row; a single row falls back to an EXISTS.+# children, so a client summing a list should skip the parent. Callers that+# render many rows pass split_parent_ids (the set of entry ids with children)+# so split_parent costs no query per row; a single row falls back to an EXISTS.json.excluded transaction.entry.excluded?split_parent_ids = local_assigns[:split_parent_ids]json.split_parent split_parent_ids ? split_parent_ids.include?(transaction.entry.id) : transaction.entry.split_parent?diff --git a/db/migrate/20261126100000_backfill_entries_excluded.rb b/db/migrate/20261126100000_backfill_entries_excluded.rbnew file mode 100644index 0000000000..761cd285d5--- /dev/null+++ b/db/migrate/20261126100000_backfill_entries_excluded.rb@@ -0,0 +1,56 @@+# entries.excluded had a default but no NOT NULL, and a blank form value or+# `update!(excluded: "")` stored NULL. Ruby and the serializer read such a row+# as included, while most report, budget and transfer-matching queries filter+# on `excluded = false` and dropped it. The row showed in the transactions list+# and was missing from the totals. NULL becomes false, which is what the UI+# already showed.+#+# Batched outside a transaction so a large table is not locked in one+# statement. Only NULL rows are written, so it can run more than once. Each+# changed row gets a new updated_at, since report caches are keyed on it and+# these rows now count in the totals.+#+# The check is added NOT VALID once the rows are backfilled: new and updated+# rows are checked right away, and a row an old process wrote as NULL in the+# meantime is caught by the second pass. MakeEntriesExcludedNotNull validates+# the check and turns it into the column's NOT NULL.+class BackfillEntriesExcluded < ActiveRecord::Migration[8.1]+ disable_ddl_transaction!++ def up+ backfill+ add_check_constraint :entries, "excluded IS NOT NULL",+ name: "chk_entries_excluded_not_null", validate: false, if_not_exists: true+ backfill+ end++ # The backfilled rows read as false before and are not set back to NULL.+ def down+ remove_check_constraint :entries, name: "chk_entries_excluded_not_null", if_exists: true+ end++ private+ def backfill+ loop do+ updated = exec_update(<<~SQL)+ UPDATE entries+ SET excluded = false, updated_at = CURRENT_TIMESTAMP+ WHERE id IN (SELECT id FROM entries WHERE excluded IS NULL LIMIT #{batch_size})+ AND excluded IS NULL+ SQL+ break if updated.zero? && !null_rows_remain?+ end+ end++ def batch_size+ 10_000+ end++ # Uncached: the updates do not clear the query cache, so a cached answer+ # would keep the loop running.+ def null_rows_remain?+ connection.uncached do+ connection.select_value("SELECT 1 FROM entries WHERE excluded IS NULL LIMIT 1").present?+ end+ end+enddiff --git a/db/migrate/20261126100100_make_entries_excluded_not_null.rb b/db/migrate/20261126100100_make_entries_excluded_not_null.rbnew file mode 100644index 0000000000..37177f3378--- /dev/null+++ b/db/migrate/20261126100100_make_entries_excluded_not_null.rb@@ -0,0 +1,19 @@+# Validates the check BackfillEntriesExcluded added as NOT VALID, in its own+# migration so the full-table scan runs after that lock has been released;+# VALIDATE CONSTRAINT only takes SHARE UPDATE EXCLUSIVE. PostgreSQL then uses+# the validated check to set NOT NULL without scanning the table again, and the+# check is dropped as redundant.+class MakeEntriesExcludedNotNull < ActiveRecord::Migration[8.1]+ def up+ validate_check_constraint :entries, name: "chk_entries_excluded_not_null"+ change_column_null :entries, :excluded, false+ remove_check_constraint :entries, name: "chk_entries_excluded_not_null"+ end++ # Back to the NOT VALID check the previous migration leaves; rolling that one+ # back removes it.+ def down+ change_column_null :entries, :excluded, true+ add_check_constraint :entries, "excluded IS NOT NULL", name: "chk_entries_excluded_not_null", validate: false+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex e1bdd79def..765061dd62 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_11_24_120100) do+ActiveRecord::Schema[8.1].define(version: 2026_11_26_100100) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -702,7 +702,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_24_120100) dot.date "date"t.uuid "entryable_id"t.string "entryable_type"- t.boolean "excluded", default: false+ t.boolean "excluded", default: false, null: falset.string "external_id"t.string "idempotency_key"t.uuid "import_id"diff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rbindex 0c362fa911..90935761ba 100644--- a/test/controllers/api/v1/transactions_controller_test.rb+++ b/test/controllers/api/v1/transactions_controller_test.rb@@ -1787,20 +1787,6 @@ end"split children should not be loaded just to compute split_parent"end- test "excluded is false, not null, when the stored flag is null" do- entry = create_transaction(account: @account, amount: 20, name: "Null exclusion")- entry.update_column(:excluded, nil)-- get api_v1_transaction_url(entry.transaction), headers: api_headers(@api_key)- assert_response :success- assert_equal false, JSON.parse(response.body)["excluded"]-- get api_v1_transactions_url, params: { per_page: 100 }, headers: api_headers(@api_key)- assert_response :success- row = JSON.parse(response.body)["transactions"].find { |t| t["id"] == entry.transaction.id }- assert_equal false, row["excluded"]- end-test "show exposes the activity label and the safe provider fields, not the raw extra" dosecurity = Security.create!(ticker: "WHT#{SecureRandom.hex(2).upcase}", name: "Withholding Security", country_code: "US")entry = create_transaction(diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex 8ae642c846..477460441e 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -652,6 +652,15 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTestassert_enqueued_with(job: SyncJob)end+ test "a blank excluded field includes the transaction again" do+ @entry.update!(excluded: true)++ patch transaction_url(@entry), params: { entry: { excluded: "" } }++ assert_redirected_to account_url(@entry.account)+ assert_equal false, Entry.where(id: @entry.id).pick(:excluded)+ end+test "re-renders show with mark-recurring state when update fails validation" dofamily = families(:empty)sign_in users(:empty)diff --git a/test/migrations/make_entries_excluded_not_null_migration_test.rb b/test/migrations/make_entries_excluded_not_null_migration_test.rbnew file mode 100644index 0000000000..b7d0d1d6bb--- /dev/null+++ b/test/migrations/make_entries_excluded_not_null_migration_test.rb@@ -0,0 +1,101 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20261126100000_backfill_entries_excluded")+require Rails.root.join("db/migrate/20261126100100_make_entries_excluded_not_null")++class MakeEntriesExcludedNotNullMigrationTest < ActiveSupport::TestCase+ include EntriesTestHelper++ # Each test starts from the nullable column an installation has before both+ # migrations. DDL is transactional in Postgres, so the change is rolled back+ # with the rest of the test.+ setup do+ not_null.down+ backfill.down+ @null_entry = create_transaction(account: accounts(:depository), name: "Blank form value")+ @excluded_entry = create_transaction(account: accounts(:depository), name: "Excluded", excluded: true)+ @null_entry.update_columns(updated_at: 1.year.ago)+ connection.execute(Entry.sanitize_sql_array([ "UPDATE entries SET excluded = NULL WHERE id = ?", @null_entry.id ]))+ end++ test "a NULL excluded becomes false and the column refuses NULL" do+ backfill.up+ not_null.up++ assert_equal false, stored_excluded(@null_entry)+ assert_equal true, stored_excluded(@excluded_entry)+ assert_not entries_column.null+ assert_not check_constraint_exists?+ end++ # Report caches are keyed on the newest entries.updated_at, and the totals+ # of a backfilled row change.+ test "the backfill touches only the rows it changes" do+ excluded_updated_at = @excluded_entry.reload.updated_at++ backfill.up++ assert_operator @null_entry.reload.updated_at, :>, 1.minute.ago+ assert_equal excluded_updated_at, @excluded_entry.reload.updated_at+ end++ test "the backfill can run again" do+ backfill.up+ backfill.up+ not_null.up++ assert_equal false, stored_excluded(@null_entry)+ end++ test "the check added not valid already refuses a NULL" do+ backfill.up++ assert check_constraint_exists?+ assert_raises(ActiveRecord::StatementInvalid) { write_null(@excluded_entry) }+ end++ test "rolling back both leaves the column nullable again" do+ backfill.up+ not_null.up+ not_null.down+ backfill.down++ assert entries_column.null+ assert_not check_constraint_exists?+ write_null(@excluded_entry)+ assert_nil stored_excluded(@excluded_entry)+ end++ private+ def backfill+ @backfill ||= BackfillEntriesExcluded.new.tap { |m| m.verbose = false }+ end++ def not_null+ @not_null ||= MakeEntriesExcludedNotNull.new.tap { |m| m.verbose = false }+ end++ def connection+ ActiveRecord::Base.connection+ end++ def stored_excluded(entry)+ connection.select_value(Entry.sanitize_sql_array([ "SELECT excluded FROM entries WHERE id = ?", entry.id ]))+ end++ # A savepoint, so a refused UPDATE leaves the test's transaction usable.+ def write_null(entry)+ Entry.transaction(requires_new: true) do+ connection.execute(Entry.sanitize_sql_array([ "UPDATE entries SET excluded = NULL WHERE id = ?", entry.id ]))+ end+ end++ def entries_column+ connection.columns(:entries).find { |column| column.name == "excluded" }+ end++ def check_constraint_exists?+ connection.check_constraints(:entries).any? { |constraint| constraint.name == "chk_entries_excluded_not_null" }+ end+enddiff --git a/test/models/entry_test.rb b/test/models/entry_test.rbindex 32abc784b5..56d9256148 100644--- a/test/models/entry_test.rb+++ b/test/models/entry_test.rb@@ -657,6 +657,31 @@ class EntryTest < ActiveSupport::TestCaseaccount.entries.excluding_balance_updates.pluck(:id).sortend+ # A blank form value casts to nil. Stored as NULL, the row read as live in+ # Ruby but dropped out of every `excluded = false` query.+ test "a blank or nil excluded is stored as false" do+ entry = create_transaction(account: accounts(:depository))++ [ "", nil ].each do |blank|+ entry.update!(excluded: true)+ entry.update!(excluded: blank)++ assert_equal false, Entry.where(id: entry.id).pick(:excluded), "excluded: #{blank.inspect}"+ end+ end++ test "the database refuses a NULL excluded" do+ entry = create_transaction(account: accounts(:depository))++ # A savepoint, so the refused UPDATE leaves the test's transaction usable.+ assert_raises(ActiveRecord::NotNullViolation) do+ Entry.transaction(requires_new: true) do+ Entry.connection.execute(Entry.sanitize_sql_array([ "UPDATE entries SET excluded = NULL WHERE id = ?", entry.id ]))+ end+ end+ assert_equal false, entry.reload.excluded+ end+privatedef create_pending(account, date:, amount:)create_transaction(diff --git a/test/models/portfolio/flow_classifier_test.rb b/test/models/portfolio/flow_classifier_test.rbindex 6dcc29857d..f8afaf9674 100644--- a/test/models/portfolio/flow_classifier_test.rb+++ b/test/models/portfolio/flow_classifier_test.rb@@ -289,18 +289,11 @@ class Portfolio::FlowClassifierTest < ActiveSupport::TestCaseassert_equal :external_inflow, @family_scope.classify(orphan)end- # entries.excluded is nullable. #classify reads a NULL as live (excluded? is- # false), and so does the SQL CASE (WHEN NULL is not taken), so the opposite- # leg's lookup has to read it the same way; `excluded = false` dropped it and- # turned an in-scope move into an external flow. An excluded leg still does- # not count, which is the other side of the boundary.- test "a security transfer leg with a NULL excluded flag still counts as the opposite leg" do+ # The Ruby and SQL lookups of the opposite leg agree on which legs are live.+ test "an excluded security transfer leg does not count as the opposite leg" dosecurity = create_portfolio_securityout_leg, in_leg = create_security_transfer(security: security, from: @brokerage, to: @ira, qty: 10, price: 50)- in_leg.update_columns(excluded: nil)- assert_nil in_leg.reload.excluded, "precondition: the opposite leg's flag is NULL, not false"-assert_equal :internal, @family_scope.classify(out_leg)assert_equal :internal, @family_scope.classify_ids([ out_leg.id ])[out_leg.id]