The personal finance app for everyone (by everyone)
Ruby
Index exchange rates by update time for cache keys (#5075)
Yong Cong Sin7f217066b233
diff --git a/db/migrate/20261114233000_add_updated_at_indexes_to_exchange_rates.rb b/db/migrate/20261114233000_add_updated_at_indexes_to_exchange_rates.rbnew file mode 100644index 0000000000..54274f3c77--- /dev/null+++ b/db/migrate/20261114233000_add_updated_at_indexes_to_exchange_rates.rb@@ -0,0 +1,56 @@+class AddUpdatedAtIndexesToExchangeRates < ActiveRecord::Migration[8.1]+ disable_ddl_transaction!++ UPDATED_AT_INDEX = "index_exchange_rates_on_updated_at"+ CURRENCY_UPDATED_AT_INDEX = "index_exchange_rates_on_to_currency_and_updated_at"+ CURRENCY_INDEX = "index_exchange_rates_on_to_currency"++ # Cache keys carry the newest stored exchange rate so a rate that arrives+ # later refreshes the cached totals. ExchangeRate.maximum(:updated_at) runs+ # on every dashboard, report and transactions render (net worth and its+ # breakdown, the income statement, investment totals, transaction search)+ # and, without an index, scans the whole exchange_rates table, which every+ # family shares. These make it, and the budget rollover's per-currency+ # variant, a lookup at the end of an index.+ def up+ add_valid_index UPDATED_AT_INDEX, [ :updated_at ]++ # Replaces the single-column to_currency index: it serves the same+ # to_currency lookups and also ExchangeRate.where(to_currency:).maximum(:updated_at).+ add_valid_index CURRENCY_UPDATED_AT_INDEX, [ :to_currency, :updated_at ]++ # Only drop the old index once its replacement is there and usable, so+ # to_currency lookups never lose their index.+ unless valid_index?(CURRENCY_UPDATED_AT_INDEX)+ raise "#{CURRENCY_UPDATED_AT_INDEX} is missing or invalid; keeping #{CURRENCY_INDEX}"+ end+ remove_index :exchange_rates, name: CURRENCY_INDEX, algorithm: :concurrently, if_exists: true+ end++ def down+ add_valid_index CURRENCY_INDEX, [ :to_currency ]+ remove_index :exchange_rates, name: CURRENCY_UPDATED_AT_INDEX, algorithm: :concurrently, if_exists: true+ remove_index :exchange_rates, name: UPDATED_AT_INDEX, algorithm: :concurrently, if_exists: true+ end++ private+ # CREATE INDEX CONCURRENTLY leaves an INVALID index behind when it's+ # interrupted (a deploy killed mid-build, a timeout). That index still has+ # its name in the catalog, so `if_not_exists` would accept it and the+ # migration would be recorded as done with an index PostgreSQL never uses.+ # Only a valid index counts; an invalid leftover is dropped and rebuilt.+ def add_valid_index(name, columns)+ return if valid_index?(name)++ execute "DROP INDEX CONCURRENTLY IF EXISTS #{quote_table_name(name)}"+ add_index :exchange_rates, columns, name: name, algorithm: :concurrently+ end++ def valid_index?(name)+ select_value(<<~SQL.squish) == true+ SELECT pg_index.indisvalid FROM pg_index+ JOIN pg_class ON pg_class.oid = pg_index.indexrelid+ WHERE pg_class.relname = #{quote(name)}+ SQL+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex b4986ea825..88076b347f 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_11_080000) do+ActiveRecord::Schema[8.1].define(version: 2026_11_14_233000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -843,7 +843,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_11_080000) dot.datetime "updated_at", null: falset.index ["from_currency", "to_currency", "date"], name: "index_exchange_rates_on_base_converted_date_unique", unique: truet.index ["from_currency"], name: "index_exchange_rates_on_from_currency"- t.index ["to_currency"], name: "index_exchange_rates_on_to_currency"+ t.index ["to_currency", "updated_at"], name: "index_exchange_rates_on_to_currency_and_updated_at"+ t.index ["updated_at"], name: "index_exchange_rates_on_updated_at"t.check_constraint "rate > 0::numeric AND rate <> 'NaN'::numeric AND rate::text <> 'Infinity'::text", name: "chk_exchange_rates_rate_positive"enddiff --git a/test/migrations/add_updated_at_indexes_to_exchange_rates_migration_test.rb b/test/migrations/add_updated_at_indexes_to_exchange_rates_migration_test.rbnew file mode 100644index 0000000000..7fb153ac4e--- /dev/null+++ b/test/migrations/add_updated_at_indexes_to_exchange_rates_migration_test.rb@@ -0,0 +1,70 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20261114233000_add_updated_at_indexes_to_exchange_rates")++# CREATE INDEX CONCURRENTLY leaves an INVALID index behind when it's+# interrupted, and the migration (with `disable_ddl_transaction!`) stays+# pending, so the next run has to finish the job. These tests pin that the+# re-run rebuilds such a leftover instead of accepting it by name, and that the+# old to_currency index is only dropped once its replacement is valid.+class AddUpdatedAtIndexesToExchangeRatesMigrationTest < ActiveSupport::TestCase+ # CONCURRENTLY can't run inside the transaction each test is otherwise+ # wrapped in. Every test leaves the schema as the migration's `up` does.+ self.use_transactional_tests = false++ MIGRATION = AddUpdatedAtIndexesToExchangeRates++ teardown do+ run_migration(:up)+ end++ test "re-running over an invalid leftover index rebuilds it before dropping the old one" do+ run_migration(:down)+ assert valid_index?(MIGRATION::CURRENCY_INDEX), "precondition: the old to_currency index is back"++ # The state an interrupted run leaves: the replacement's name is in the+ # catalog, but PostgreSQL marks it invalid and never uses it.+ connection.execute(+ "CREATE INDEX #{MIGRATION::CURRENCY_UPDATED_AT_INDEX} ON exchange_rates (to_currency, updated_at)"+ )+ connection.execute(+ "UPDATE pg_index SET indisvalid = false " \+ "WHERE indexrelid = #{connection.quote(MIGRATION::CURRENCY_UPDATED_AT_INDEX)}::regclass"+ )+ assert_not valid_index?(MIGRATION::CURRENCY_UPDATED_AT_INDEX), "precondition: the leftover is invalid"++ run_migration(:up)++ assert valid_index?(MIGRATION::CURRENCY_UPDATED_AT_INDEX), "the invalid leftover was accepted instead of rebuilt"+ assert valid_index?(MIGRATION::UPDATED_AT_INDEX)+ assert_not index_named?(MIGRATION::CURRENCY_INDEX), "the old to_currency index should be gone"+ end++ test "down restores the to_currency index and removes the new ones" do+ run_migration(:down)++ assert valid_index?(MIGRATION::CURRENCY_INDEX)+ assert_not index_named?(MIGRATION::CURRENCY_UPDATED_AT_INDEX)+ assert_not index_named?(MIGRATION::UPDATED_AT_INDEX)+ end++ private+ def connection = ActiveRecord::Base.connection++ def valid_index?(name)+ connection.select_value(<<~SQL.squish) == true+ SELECT pg_index.indisvalid FROM pg_index+ JOIN pg_class ON pg_class.oid = pg_index.indexrelid+ WHERE pg_class.relname = #{connection.quote(name)}+ SQL+ end++ def index_named?(name)+ connection.select_value("SELECT count(*) FROM pg_class WHERE relname = #{connection.quote(name)}").to_i.positive?+ end++ def run_migration(direction)+ ActiveRecord::Migration.suppress_messages { MIGRATION.new.public_send(direction) }+ end+enddiff --git a/test/models/exchange_rate_test.rb b/test/models/exchange_rate_test.rbindex b41f309897..755580395f 100644--- a/test/models/exchange_rate_test.rb+++ b/test/models/exchange_rate_test.rb@@ -264,4 +264,26 @@ class ExchangeRateTest < ActiveSupport::TestCase)endend++ # Cache keys read the newest stored rate on every dashboard, report and+ # transactions render; that read must not scan the table every family shares.+ test "the newest stored rate is read from an index" do+ assert_index_lookup ExchangeRate.select("MAX(updated_at)"), "index_exchange_rates_on_updated_at"+ end++ test "the newest stored rate into a currency is read from an index" do+ assert_index_lookup ExchangeRate.where(to_currency: "USD").select("MAX(updated_at)"),+ "index_exchange_rates_on_to_currency_and_updated_at"+ end++ private+ # With sequential scans priced out, the planner uses an index whenever one+ # can answer the query; without one it still falls back to a sequential scan.+ def assert_index_lookup(relation, index_name)+ plan = ExchangeRate.transaction do+ ExchangeRate.connection.execute("SET LOCAL enable_seqscan = off")+ ExchangeRate.connection.select_values("EXPLAIN #{relation.to_sql}").join("\n")+ end+ assert_includes plan, index_name, "expected the query to use #{index_name}:\n#{plan}"+ endend