Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Enforce one tagging per tag and object with a unique index (#5293)

jaysbeekay46360cedb789
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index e03c0c4efe..61d49a1e10 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -1053,7 +1053,7 @@ class Family::DataImporter
def mapped_tag_ids(old_tag_ids, record_type:)
Array(old_tag_ids).map do |old_tag_id|
mapped_id(:tags, old_tag_id, record_type: record_type)
- end.compact
+ end.compact.uniq
end
def importable_split_rows(data)
diff --git a/app/models/qif_import.rb b/app/models/qif_import.rb
index efbf47f739..02375f08bc 100644
--- a/app/models/qif_import.rb
+++ b/app/models/qif_import.rb
@@ -364,7 +364,7 @@ class QifImport < Import
children = entry.split!(split_rows)
children.zip(split_rows).each do |child, row|
child.update!(notes: row[:notes]) if row[:notes].present?
- row[:tags].each { |tag| child.entryable.taggings.create!(tag: tag) }
+ row[:tags].uniq.each { |tag| child.entryable.taggings.create!(tag: tag) }
end
end
diff --git a/app/models/tag.rb b/app/models/tag.rb
index 2c792bdfcb..f86ec4bd85 100644
--- a/app/models/tag.rb
+++ b/app/models/tag.rb
@@ -60,7 +60,21 @@ class Tag < ApplicationRecord
raise ActiveRecord::RecordInvalid, "Replacement tag cannot be the same as the tag being destroyed" if replacement == self
if replacement
- taggings.update_all tag_id: replacement.id
+ # Skip objects that already carry the replacement: moving their row
+ # would tag them twice. Their old row goes with destroy! below. The
+ # type is compared the way index_taggings_unique keys it, with a
+ # missing type folded to '', so the two always agree.
+ taggings.where(<<~SQL, replacement.id).update_all(tag_id: replacement.id)
+ NOT EXISTS (
+ SELECT 1 FROM taggings carried
+ WHERE carried.tag_id = ?
+ AND COALESCE(carried.taggable_type, '') = COALESCE(taggings.taggable_type, '')
+ AND carried.taggable_id = taggings.taggable_id
+ )
+ SQL
+ # A loaded taggings association still lists the moved rows, and
+ # destroy! would delete them by id.
+ taggings.reset
end
destroy!
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index c67aecf692..3a5bb78fa6 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -27,6 +27,20 @@ class Transaction < ApplicationRecord
accepts_nested_attributes_for :taggings, allow_destroy: true
+ # A tag can be applied to a transaction only once, but assigning the same
+ # tag twice would insert two taggings. Collapse repeats first, comparing
+ # ids as the database does. The original values go on to `super`: Rails
+ # drops blanks before it casts, so passing a malformed id cast to nil would
+ # discard it silently instead of raising RecordNotFound.
+ def tag_ids=(ids)
+ id_type = Tag.type_for_attribute(:id)
+ super(Array(ids).uniq { |id| id_type.cast(id) || id })
+ end
+
+ def tags=(tags)
+ super(Array(tags).uniq)
+ end
+
after_save :clear_merchant_unlinked_association, if: :merchant_id_previously_changed?
after_save :supersede_automatic_category_claims, if: :saved_change_to_category_id?
diff --git a/db/migrate/20261007120000_add_unique_index_to_taggings.rb b/db/migrate/20261007120000_add_unique_index_to_taggings.rb
new file mode 100644
index 0000000000..37c4bece90
--- /dev/null
+++ b/db/migrate/20261007120000_add_unique_index_to_taggings.rb
@@ -0,0 +1,51 @@
+# Nothing stopped a tag being applied twice to the same object, and some
+# installations already hold such duplicates. Remove them, keeping the
+# oldest row of each, then add a unique index so they cannot come back.
+#
+# The index is partial because both taggable columns are nullable: a row
+# with no taggable is not a tagging of anything, so it is left alone.
+# taggable_type is indexed as COALESCE(taggable_type, ''): Postgres treats two
+# NULLs as different keys, so a plain column index would let a duplicate with
+# no type through. The expression works on every supported Postgres version,
+# where NULLS NOT DISTINCT would need 15 or later. The dedupe partitions on
+# the same expression, so the rows it keeps are exactly the ones the index
+# will accept.
+#
+# Writers are locked out from before the DELETE until the index exists. The
+# DELETE alone takes only ROW EXCLUSIVE, which lets other inserts through, so
+# a duplicate written between it and CREATE INDEX would fail the index build.
+# SHARE ROW EXCLUSIVE blocks concurrent writes and is held to the end of the
+# migration's transaction; a transaction never conflicts with its own locks,
+# so the DELETE still runs.
+class AddUniqueIndexToTaggings < ActiveRecord::Migration[8.1]
+ def up
+ execute "LOCK TABLE taggings IN SHARE ROW EXCLUSIVE MODE"
+
+ execute <<~SQL
+ DELETE FROM taggings
+ WHERE id IN (
+ SELECT id FROM (
+ SELECT id, ROW_NUMBER() OVER (
+ PARTITION BY tag_id, COALESCE(taggable_type, ''), taggable_id
+ ORDER BY created_at, id
+ ) AS position
+ FROM taggings
+ WHERE taggable_id IS NOT NULL
+ ) ranked
+ WHERE position > 1
+ )
+ SQL
+
+ add_index :taggings, "tag_id, COALESCE(taggable_type, ''), taggable_id",
+ name: "index_taggings_unique",
+ unique: true,
+ where: "taggable_id IS NOT NULL",
+ if_not_exists: true
+ end
+
+ # The deleted duplicates are not kept anywhere, so rolling back only
+ # drops the index.
+ def down
+ remove_index :taggings, name: "index_taggings_unique", if_exists: true
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index e0e64f9a74..81dd13addb 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2789,6 +2789,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) do
t.uuid "taggable_id"
t.string "taggable_type"
t.datetime "updated_at", null: false
+ t.index "tag_id, COALESCE(taggable_type, ''::character varying), taggable_id", name: "index_taggings_unique", unique: true, where: "(taggable_id IS NOT NULL)"
t.index ["tag_id"], name: "index_taggings_on_tag_id"
t.index ["taggable_type", "taggable_id"], name: "index_taggings_on_taggable"
end
diff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rb
index 142a5f461f..34071f18c7 100644
--- a/test/controllers/api/v1/transactions_controller_test.rb
+++ b/test/controllers/api/v1/transactions_controller_test.rb
@@ -1251,6 +1251,29 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTest
assert_response :unprocessable_entity
end
+ test "should store a repeated tag id once in update" do
+ tag = @family.tags.first
+
+ put api_v1_transaction_url(@transaction),
+ params: { transaction: { tag_ids: [ tag.id, tag.id ] } },
+ headers: api_headers(@api_key)
+ assert_response :success
+
+ assert_equal [ tag.id ], @transaction.reload.taggings.pluck(:tag_id)
+ end
+
+ test "update with a malformed tag id leaves the tags unchanged" do
+ @transaction.update!(tag_ids: [ @family.tags.first.id ])
+ before_ids = @transaction.reload.tag_ids.sort
+
+ put api_v1_transaction_url(@transaction),
+ params: { transaction: { tag_ids: [ "not-a-uuid" ] } },
+ headers: api_headers(@api_key)
+
+ assert_not_equal 200, response.status
+ assert_equal before_ids, @transaction.reload.tag_ids.sort
+ end
+
test "should clear tags when empty tag_ids explicitly provided in update" do
# Set up transaction with existing tags
@transaction.tags = [ Tag.first, Tag.second ]
diff --git a/test/controllers/tag/deletions_controller_test.rb b/test/controllers/tag/deletions_controller_test.rb
index 2cf3da3072..df5d514feb 100644
--- a/test/controllers/tag/deletions_controller_test.rb
+++ b/test/controllers/tag/deletions_controller_test.rb
@@ -14,13 +14,18 @@ class Tag::DeletionsControllerTest < ActionDispatch::IntegrationTest
test "create with replacement" do
replacement_tag = tags(:two)
- affected_transaction_count = @tag.transactions.count
+ # The fixture transaction already carries both tags, so it must end up
+ # with the replacement once; this one only carries the deleted tag.
+ already_tagged = transactions(:one)
+ moved = transactions(:transfer_out)
+ moved.taggings.create!(tag: @tag)
- assert affected_transaction_count > 0
-
- assert_difference -> { Tag.count } => -1, -> { replacement_tag.transactions.count } => affected_transaction_count do
+ assert_difference -> { Tag.count } => -1, -> { Tagging.count } => -1 do
post tag_deletions_url(@tag), params: { replacement_tag_id: replacement_tag.id }
end
+
+ assert_equal [ replacement_tag ], already_tagged.reload.tags.to_a
+ assert_equal [ replacement_tag ], moved.reload.tags.to_a
end
test "create without replacement" do
diff --git a/test/migrations/add_unique_index_to_taggings_migration_test.rb b/test/migrations/add_unique_index_to_taggings_migration_test.rb
new file mode 100644
index 0000000000..295dde5421
--- /dev/null
+++ b/test/migrations/add_unique_index_to_taggings_migration_test.rb
@@ -0,0 +1,158 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require Rails.root.join("db/migrate/20261007120000_add_unique_index_to_taggings")
+
+class AddUniqueIndexToTaggingsMigrationTest < ActiveSupport::TestCase
+ INDEX = "index_taggings_unique"
+
+ # The test schema already carries the index, so each test starts from the
+ # state an installation is in before the migration runs: no index, and
+ # duplicates the database was free to accept. DDL is transactional in
+ # Postgres, so the removal is rolled back with the rest of the test.
+ setup do
+ @schema_definition = index_definition
+ connection.remove_index :taggings, name: INDEX, if_exists: true
+ @tag = tags(:one)
+ @transaction = transactions(:one)
+ @kept = taggings(:one)
+ end
+
+ test "removes duplicate taggings and keeps the oldest" do
+ @kept.update_columns(created_at: 2.days.ago)
+ # The duplicate's id sorts below the original's, so a dedupe that kept
+ # the lowest id instead of the oldest row would keep the wrong one.
+ insert_tagging(id: "00000000-0000-4000-8000-000000000000", created_at: 1.day.ago)
+ insert_tagging(created_at: Time.current)
+ assert_equal 3, Tagging.where(tag: @tag, taggable: @transaction).count
+
+ run_migration
+
+ assert_equal [ @kept.id ], Tagging.where(tag: @tag, taggable: @transaction).pluck(:id)
+ end
+
+ test "leaves distinct taggings alone" do
+ other = transactions(:transfer_out)
+ Tagging.create!(tag: @tag, taggable: other)
+
+ assert_no_difference -> { Tagging.count } do
+ run_migration
+ end
+
+ assert_equal [ tags(:one), tags(:two) ].sort_by(&:id), @transaction.tags.sort_by(&:id)
+ assert_equal [ @tag ], other.tags.to_a
+ end
+
+ # The index treats a missing taggable_type as a value like any other, so
+ # duplicates without one must be cleaned too or creating it fails.
+ test "removes duplicates whose taggable_type is missing" do
+ 2.times { insert_tagging(taggable_type: nil) }
+
+ run_migration
+
+ assert_equal 1, Tagging.where(tag: @tag, taggable_type: nil, taggable_id: @transaction.id).count
+ assert_raises(ActiveRecord::RecordNotUnique) { insert_tagging(taggable_type: nil) }
+ end
+
+ # Rows with no taggable are outside the index, so the migration has no
+ # reason to touch them.
+ test "leaves rows without a taggable alone" do
+ 2.times { insert_tagging(taggable_type: nil, taggable_id: nil) }
+
+ run_migration
+
+ assert_equal 2, Tagging.where(tag: @tag, taggable_id: nil).count
+ end
+
+ test "the index refuses a duplicate afterwards" do
+ run_migration
+
+ assert_raises ActiveRecord::RecordNotUnique do
+ Tagging.create!(tag: @tag, taggable: @transaction)
+ end
+ end
+
+ # A duplicate inserted after the dedupe but before the index exists would
+ # fail the index build, and DELETE's own lock lets inserts through. So the
+ # table is locked against writers before the dedupe, and held.
+ test "locks out writers from before the dedupe until the index exists" do
+ statements = []
+ subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") { |*, payload| statements << payload[:sql] }
+ begin
+ run_migration
+ ensure
+ ActiveSupport::Notifications.unsubscribe(subscriber)
+ end
+
+ lock_at = statements.index { |sql| sql.match?(/\ALOCK TABLE taggings IN SHARE ROW EXCLUSIVE MODE\z/) }
+ delete_at = statements.index { |sql| sql.include?("DELETE FROM taggings") }
+ assert lock_at, "no lock was taken on taggings"
+ assert_operator lock_at, :<, delete_at, "the lock was taken after the dedupe"
+
+ held = connection.select_values(<<~SQL)
+ SELECT mode FROM pg_locks
+ WHERE locktype = 'relation' AND relation = 'taggings'::regclass AND pid = pg_backend_pid()
+ SQL
+ assert_includes held, "ShareRowExclusiveLock", "the lock was not held to the end of the transaction"
+ end
+
+ # The LOCK TABLE above only works inside a transaction. This test runs the
+ # migration inside the fixture transaction, so it would pass even if the
+ # migration opted out of the one Rails wraps it in on deploy.
+ test "runs inside the transaction Rails wraps a migration in" do
+ assert_not AddUniqueIndexToTaggings.disable_ddl_transaction
+ end
+
+ # Looking up an index that isn't there must not abort the test's
+ # transaction, or every later statement in the test fails.
+ test "reads a missing index without aborting the transaction" do
+ assert_nil index_definition
+ assert_equal 1, connection.select_value("SELECT 1")
+ end
+
+ # db/schema.rb carries the index by hand, as an expression, so check it is
+ # the index the migration builds rather than trusting the dump format.
+ test "builds the same index the schema declares" do
+ run_migration
+
+ assert_not_nil @schema_definition
+ assert_equal @schema_definition, index_definition
+ end
+
+ # No NULLS NOT DISTINCT (PostgreSQL 15+): a missing taggable_type is folded
+ # to '' by the index expression, so the index holds on any supported version.
+ test "treats a missing taggable_type and an empty one as the same key" do
+ run_migration
+ assert_not_includes index_definition, "NULLS NOT DISTINCT"
+
+ Tagging.where(id: @kept.id).delete_all
+ insert_tagging(taggable_type: nil)
+ assert_raises(ActiveRecord::RecordNotUnique) { insert_tagging(taggable_type: "") }
+ end
+
+ test "can be run again" do
+ 2.times { run_migration }
+
+ assert connection.index_name_exists?(:taggings, INDEX)
+ end
+
+ private
+ def connection = ActiveRecord::Base.connection
+
+ def insert_tagging(id: SecureRandom.uuid, created_at: Time.current, taggable_type: "Transaction", taggable_id: @transaction.id)
+ Tagging.insert_all!([ {
+ id: id, tag_id: @tag.id, taggable_type: taggable_type, taggable_id: taggable_id,
+ created_at: created_at, updated_at: created_at
+ } ])
+ end
+
+ def index_definition
+ connection.select_value("SELECT pg_get_indexdef(to_regclass('#{INDEX}'))")
+ end
+
+ def run_migration
+ ActiveRecord::Migration.suppress_messages do
+ AddUniqueIndexToTaggings.new.up
+ end
+ end
+end
diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rb
index 9cd1baefed..619cdf6fc9 100644
--- a/test/models/family/data_importer_test.rb
+++ b/test/models/family/data_importer_test.rb
@@ -1283,6 +1283,41 @@ class Family::DataImporterTest < ActiveSupport::TestCase
assert_empty explicit_empty_child.transaction.tags
end
+ # An export taken while a transaction carried a tag twice lists the tag id
+ # twice, and the import must not fail on the unique index because of it.
+ test "imports a repeated tag id once" do
+ ndjson = build_ndjson([
+ { type: "Account", data: { id: "checking", name: "Checking", balance: "1000", currency: "USD", accountable_type: "Depository" } },
+ { type: "Tag", data: { id: "tag-1", name: "Repeated" } },
+ {
+ type: "Transaction",
+ data: {
+ id: "plain", account_id: "checking", date: "2024-01-15", amount: "10.00",
+ name: "Plain", currency: "USD", tag_ids: [ "tag-1", "tag-1" ]
+ }
+ },
+ {
+ type: "Transaction",
+ data: {
+ id: "split-parent", account_id: "checking", date: "2024-01-15", amount: "30.00",
+ name: "Split parent", currency: "USD", tag_ids: [ "tag-1", "tag-1" ],
+ split_lines: [
+ { id: "inherits", amount: "10.00", name: "Inherits" },
+ { id: "explicit", amount: "20.00", name: "Explicit", tag_ids: [ "tag-1", "tag-1" ] }
+ ]
+ }
+ }
+ ])
+
+ Family::DataImporter.new(@family, ndjson).import!
+
+ tag = @family.tags.find_by!(name: "Repeated")
+ [ "Plain", "Inherits", "Explicit" ].each do |name|
+ transaction = @family.entries.find_by!(name: name).transaction
+ assert_equal [ tag.id ], transaction.taggings.pluck(:tag_id), "#{name} should carry the tag once"
+ end
+ end
+
test "session transaction reimport only replaces current family taggings" do
session = @family.import_sessions.create!(expected_chunks: 1)
account = @family.accounts.create!(
diff --git a/test/models/qif_import_test.rb b/test/models/qif_import_test.rb
index b6d2f829dc..f21d0f7811 100644
--- a/test/models/qif_import_test.rb
+++ b/test/models/qif_import_test.rb
@@ -722,6 +722,34 @@ class QifImportTest < ActiveSupport::TestCase
assert_equal [ "KEEP" ], train.entryable.tags.map(&:name)
end
+ test "import! applies a tag repeated on a split line once" do
+ qif = <<~QIF
+ !Type:Bank
+ D1/ 1'24
+ U-100.00
+ T-100.00
+ PRepeated Tag Store
+ L--Split--
+ SFood/KEEP:KEEP
+ $-60.00
+ EGroceries
+ STravel
+ $-40.00
+ ETrain
+ ^
+ QIF
+
+ @import.update!(raw_file_str: qif)
+ @import.generate_rows_from_csv
+ @import.sync_mappings
+
+ @import.import!
+
+ parent = @account.entries.find_by!(name: "Repeated Tag Store")
+ groceries = parent.child_entries.find_by!(name: "Groceries")
+ assert_equal [ "KEEP" ], groceries.entryable.taggings.map { |tagging| tagging.tag.name }
+ end
+
test "import! skips split creation when split line totals do not match parent" do
@import.update!(raw_file_str: QIF_WITH_ROUNDING_SPLIT_MISMATCH)
@import.generate_rows_from_csv
diff --git a/test/models/tag_test.rb b/test/models/tag_test.rb
index 428647c272..805cf65fa9 100644
--- a/test/models/tag_test.rb
+++ b/test/models/tag_test.rb
@@ -1,19 +1,54 @@
require "test_helper"
class TagTest < ActiveSupport::TestCase
- test "replace and destroy" do
+ test "replace and destroy moves the tag and tags nothing twice" do
old_tag = tags(:one)
new_tag = tags(:two)
- assert_difference "Tag.count", -1 do
+ # The fixture transaction already carries both tags; this one carries
+ # only the tag being replaced.
+ already_tagged = transactions(:one)
+ moved = transactions(:transfer_out)
+ moved.taggings.create!(tag: old_tag)
+
+ assert_difference [ "Tag.count", "Tagging.count" ], -1 do
old_tag.replace_and_destroy!(new_tag)
end
- old_tag.transactions.each do |txn|
- txn.reload
- assert_includes txn.tags, new_tag
- assert_not_includes txn.tags, old_tag
+ assert_equal [ new_tag ], already_tagged.reload.tags.to_a
+ assert_equal [ new_tag ], moved.reload.tags.to_a
+ end
+
+ # destroy! removes the taggings association it holds. If a caller loaded it
+ # before the merge, that list still names the rows the merge just moved.
+ test "replace and destroy keeps the moved rows when the source taggings were loaded first" do
+ old_tag = tags(:one)
+ new_tag = tags(:two)
+ moved = transactions(:transfer_out)
+ moved_tagging = moved.taggings.create!(tag: old_tag)
+ old_tag.taggings.load
+
+ assert_difference "Tagging.count", -1 do
+ old_tag.replace_and_destroy!(new_tag)
end
+
+ assert Tagging.exists?(moved_tagging.id)
+ assert_equal [ new_tag ], moved.reload.tags.to_a
+ end
+
+ # The unique index treats a missing taggable_type as a value, so the merge
+ # has to as well, or it moves the row into a duplicate and fails.
+ test "replace and destroy skips a row with no taggable type that the replacement already has" do
+ old_tag = tags(:one)
+ new_tag = tags(:two)
+ taggable_id = transactions(:transfer_out).id
+ Tagging.insert_all!([ old_tag, new_tag ].map do |tag|
+ { tag_id: tag.id, taggable_id: taggable_id, taggable_type: nil, created_at: Time.current, updated_at: Time.current }
+ end)
+
+ old_tag.replace_and_destroy!(new_tag)
+
+ assert_equal [ new_tag.id ], Tagging.where(taggable_id: taggable_id).pluck(:tag_id)
end
test "ids_with_transactions lists only the given tags that are on a transaction" do
@@ -25,6 +60,23 @@ class TagTest < ActiveSupport::TestCase
assert_equal({}, Tag.ids_with_transactions(family: family, tag_ids: []))
end
+ # The unique index folds a missing taggable_type to '', so the merge must
+ # treat a NULL type and an empty one as the same object too, or moving the
+ # row would hit the index.
+ test "replace and destroy treats a missing and an empty taggable type as the same object" do
+ old_tag = tags(:one)
+ new_tag = tags(:two)
+ taggable_id = transactions(:transfer_out).id
+ Tagging.insert_all!([
+ { tag_id: old_tag.id, taggable_id: taggable_id, taggable_type: nil, created_at: Time.current, updated_at: Time.current },
+ { tag_id: new_tag.id, taggable_id: taggable_id, taggable_type: "", created_at: Time.current, updated_at: Time.current }
+ ])
+
+ old_tag.replace_and_destroy!(new_tag)
+
+ assert_equal [ new_tag.id ], Tagging.where(taggable_id: taggable_id).pluck(:tag_id)
+ end
+
test "rejects the reserved Untagged filter sentinel as a name" do
tag = families(:dylan_family).tags.new(name: Tag::UNTAGGED_FILTER_VALUE, color: "#e99537")
diff --git a/test/models/tagging_test.rb b/test/models/tagging_test.rb
new file mode 100644
index 0000000000..8741278bee
--- /dev/null
+++ b/test/models/tagging_test.rb
@@ -0,0 +1,29 @@
+require "test_helper"
+
+class TaggingTest < ActiveSupport::TestCase
+ test "a tag cannot be applied twice to the same transaction" do
+ assert_raises ActiveRecord::RecordNotUnique do
+ Tagging.create!(tag: tags(:one), taggable: transactions(:one))
+ end
+ end
+
+ # Postgres treats NULLs as distinct in a unique index by default, which
+ # would let this duplicate through.
+ test "a tag cannot be applied twice to a taggable with no type" do
+ row = {
+ tag_id: tags(:one).id, taggable_id: transactions(:transfer_out).id,
+ taggable_type: nil, created_at: Time.current, updated_at: Time.current
+ }
+ Tagging.insert_all!([ row ])
+
+ assert_raises ActiveRecord::RecordNotUnique do
+ Tagging.insert_all!([ row ])
+ end
+ end
+
+ test "the same tag can still be applied to different transactions" do
+ assert_difference -> { Tagging.count }, 1 do
+ Tagging.create!(tag: tags(:one), taggable: transactions(:transfer_out))
+ end
+ end
+end
diff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rb
index 9072ae330b..4f12c6454c 100644
--- a/test/models/transaction_test.rb
+++ b/test/models/transaction_test.rb
@@ -722,6 +722,91 @@ class TransactionTest < ActiveSupport::TestCase
assert transaction.reload.locked?(:category_id)
end
+ # A tag can only be applied once to a transaction, so a writer handed the
+ # same tag twice must store it once rather than fail on the unique index.
+ test "assigning a repeated tag id stores it once" do
+ transaction = transactions(:transfer_out)
+ tag = tags(:one)
+
+ transaction.update!(tag_ids: [ tag.id, tag.id, tag.id.upcase ])
+
+ assert_equal [ tag.id ], transaction.taggings.pluck(:tag_id)
+ end
+
+ # The dedupe above relies on the uuid cast downcasing a non-canonical id
+ # (ActiveRecord's PostgreSQL OID::Uuid#format_uuid), so pin that, and an
+ # assignment made only of case variants of one id.
+ test "an id differing only in case is the same tag" do
+ transaction = transactions(:transfer_out)
+ tag = tags(:one)
+
+ assert_equal tag.id, Tag.type_for_attribute(:id).cast(tag.id.upcase)
+
+ transaction.update!(tag_ids: [ tag.id.upcase, tag.id.downcase ])
+
+ assert_equal [ tag.id ], transaction.taggings.pluck(:tag_id)
+ end
+
+ # Rails' ids writer drops blanks before it casts, so the dedupe must not cast a
+ # malformed id to a blank: the writer would then discard it and clear the tags
+ # instead of refusing the unknown id.
+ test "a malformed tag id still raises and leaves the tags in place" do
+ transaction = transactions(:transfer_out)
+ transaction.update!(tag_ids: [ tags(:one).id ])
+ before_ids = transaction.reload.tag_ids.sort
+
+ assert_raises(ActiveRecord::RecordNotFound) { transaction.tag_ids = [ "not-a-uuid" ] }
+
+ assert_equal before_ids, transaction.reload.tag_ids.sort
+ end
+
+ test "a malformed tag id beside a valid one still raises" do
+ transaction = transactions(:transfer_out)
+ transaction.update!(tag_ids: [ tags(:two).id ])
+
+ assert_raises(ActiveRecord::RecordNotFound) { transaction.tag_ids = [ tags(:one).id, "not-a-uuid" ] }
+
+ assert_equal [ tags(:two).id ], transaction.reload.tag_ids
+ end
+
+ # A blank and a malformed id both cast to nil, so deduping on the cast alone
+ # would keep the blank, drop the malformed id, and clear the tags.
+ test "a malformed tag id after a blank one still raises" do
+ transaction = transactions(:transfer_out)
+ transaction.update!(tag_ids: [ tags(:one).id ])
+
+ assert_raises(ActiveRecord::RecordNotFound) { transaction.tag_ids = [ "", "not-a-uuid" ] }
+
+ assert_equal [ tags(:one).id ], transaction.reload.tag_ids
+ end
+
+ test "a blank tag id is still ignored" do
+ transaction = transactions(:transfer_out)
+
+ transaction.update!(tag_ids: [ "", tags(:one).id, "" ])
+
+ assert_equal [ tags(:one).id ], transaction.reload.tag_ids
+ end
+
+ test "assigning a repeated tag stores it once" do
+ transaction = transactions(:transfer_out)
+ tag = tags(:one)
+
+ transaction.tags = [ tag, tag ]
+
+ assert_equal [ tag.id ], transaction.taggings.pluck(:tag_id)
+ end
+
+ test "a new transaction built with a repeated tag saves it once" do
+ tag = tags(:one)
+ entry = accounts(:depository).entries.create!(
+ name: "Repeated tag", amount: 10, currency: "USD", date: Date.current,
+ entryable: Transaction.new(tags: [ tag, tag ])
+ )
+
+ assert_equal [ tag.id ], entry.transaction.taggings.pluck(:tag_id)
+ end
+
private
# Whether each SQL form of "is this transaction pending?" says it is.
def sql_pending_answers(transaction)