activerecord-rescue_from_duplicate 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 00a9576198c85da3503fc44c7420dd287082a3a8219fe716cd88340ab8da432d
4
- data.tar.gz: 196bb9b82c0d333e4fdbaf254992f9e2cf997d62d171420bff1859bdf4d1aca8
3
+ metadata.gz: 3193ffcb42033af327473cb7e381c7608fc722b19337e57692e2fd719db7eebb
4
+ data.tar.gz: 2ac40815c3d7358c8d0ed566257e45d9ae863fd0f7b4646ea49c2e3ebe94a37a
5
5
  SHA512:
6
- metadata.gz: df70343a3219b0c4c2ce0497329d3f59ac3c1e60b6888fabb8b1b5a0562981d1a1b0a27ad1eb0f52e7b190dbfb7584cd6dbbcf72df9f4672b8d4de34f04807cd
7
- data.tar.gz: fb404a3201ab1bc5739a4ac71686d7bb5002ce849e439c87063aa9f530f9390165e9044a549bcc733fcc15d7d004c4dd5b1386b1b8a203be4762c5f94bb03c9d
6
+ metadata.gz: 3531efe5bed868d957a924feee9f83477ee010bda2c5e3e9d937a629e7642e8fe78d0336edd5de59a7c1b9deb34a8439b84670e56c921fed8defc3fc9c22481e
7
+ data.tar.gz: 6601427dea1768ef3005c293853e81055ef031893240dcac1077389765e9dfc97e3cdddd296dd98b3be0108d283183558ed85b4c8f7a65872b8184ef620c366f
@@ -5,7 +5,9 @@ on: [push, pull_request]
5
5
  jobs:
6
6
  build:
7
7
  runs-on: ubuntu-latest
8
- name: Ruby ${{ matrix.ruby }}
8
+ name: Ruby ${{ matrix.ruby }} / Active Record ${{ matrix.activerecord }}
9
+ env:
10
+ BUNDLE_GEMFILE: ${{ github.workspace }}/gemfiles/activerecord_${{ matrix.activerecord }}.gemfile
9
11
  services:
10
12
  postgres:
11
13
  image: postgres
@@ -28,12 +30,17 @@ jobs:
28
30
  strategy:
29
31
  fail-fast: false
30
32
  matrix:
31
- ruby: ["3.0", "3.1", "3.2", "3.3"]
33
+ ruby: ["3.2", "3.3", "3.4", "4.0"]
34
+ activerecord: ["7.1", "7.2", "8.0", "8.1", "edge"]
35
+ exclude:
36
+ # Rails main requires Ruby >= 3.3.5.
37
+ - ruby: "3.2"
38
+ activerecord: "edge"
32
39
  steps:
33
40
  - name: Check out code
34
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
41
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
35
42
  - name: Set up Ruby ${{ matrix.ruby }}
36
- uses: ruby/setup-ruby@e34163cd15f4bb403dcd72d98e295997e6a55798 # v1.238.0
43
+ uses: ruby/setup-ruby@145243922b4465b78e04dd66294782c7de45901f # v1.345.0
37
44
  with:
38
45
  ruby-version: ${{ matrix.ruby }}
39
46
  bundler-cache: true
@@ -19,8 +19,8 @@ jobs:
19
19
  sudo apt-get update
20
20
  sudo apt-get -y install libmemcached-dev libmysqlclient-dev libpq-dev libsasl2-dev
21
21
  - name: Set up Ruby
22
- uses: ruby/setup-ruby@95ef2b042f9d7a56d8268cba8559e2842e2ad01b # v1.321.0
22
+ uses: ruby/setup-ruby@145243922b4465b78e04dd66294782c7de45901f # v1.345.0
23
23
  with:
24
24
  bundler-cache: true
25
25
  ruby-version: 3.3
26
- - uses: rubygems/release-gem@052cc82692552de3ef2b81fd670e41d13cba8092 # v1.4.0
26
+ - uses: rubygems/release-gem@2654a0fe0dc39725c07fe84d7fe863a084f2424e # v1.5.0
data/CHANGELOG.md CHANGED
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.3.0] - 2026-12-01
11
+
12
+ ### Added
13
+
14
+ - An `index_name:` option on `rescue_from_duplicate` and inside `rescue_from_duplicate: { index_name: }` on a
15
+ uniqueness validation, taking one index name or an array of names. The handler that names the violated index is
16
+ used even when the index columns differ from the declaration, and `missing_unique_indexes` accepts a named unique
17
+ index as well as one with matching columns. It also accepts a handler that names the table's primary key
18
+ (`PRIMARY` on MySQL, the constraint name on PostgreSQL).
19
+ - On SQLite, a violation of an expression index is matched by the index name that SQLite reports.
20
+
21
+ ### Fixed
22
+
23
+ - `missing_unique_indexes` no longer raises `NoMethodError` on a table that has an expression unique index
24
+ (`lower(email)`), whose columns Active Record reports as a String.
25
+ - A violation of a MySQL functional index (`(lower(email))`) raised `NoMethodError` while the gem matched columns.
26
+ It now raises `ActiveRecord::RecordNotUnique` unless a handler names the index.
27
+
10
28
  ## [0.2.7] - 2026-08-26
11
29
 
12
30
  ### Fixed
data/Gemfile.lock CHANGED
@@ -1,48 +1,50 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- activerecord-rescue_from_duplicate (0.2.7)
4
+ activerecord-rescue_from_duplicate (0.3.0)
5
5
  activerecord (>= 7)
6
6
 
7
7
  GEM
8
8
  remote: https://rubygems.org/
9
9
  specs:
10
- activemodel (7.1.5.2)
11
- activesupport (= 7.1.5.2)
12
- activerecord (7.1.5.2)
13
- activemodel (= 7.1.5.2)
14
- activesupport (= 7.1.5.2)
10
+ activemodel (8.0.5.2)
11
+ activesupport (= 8.0.5.2)
12
+ activerecord (8.0.5.2)
13
+ activemodel (= 8.0.5.2)
14
+ activesupport (= 8.0.5.2)
15
15
  timeout (>= 0.4.0)
16
- activesupport (7.1.5.2)
16
+ activesupport (8.0.5.2)
17
17
  base64
18
18
  benchmark (>= 0.3)
19
19
  bigdecimal
20
- concurrent-ruby (~> 1.0, >= 1.0.2)
20
+ concurrent-ruby (~> 1.0, >= 1.3.1)
21
21
  connection_pool (>= 2.2.5)
22
22
  drb
23
23
  i18n (>= 1.6, < 2)
24
24
  logger (>= 1.4.2)
25
25
  minitest (>= 5.1)
26
- mutex_m
27
26
  securerandom (>= 0.3)
28
- tzinfo (~> 2.0)
27
+ tzinfo (~> 2.0, >= 2.0.5)
28
+ uri (>= 0.13.1)
29
29
  base64 (0.3.0)
30
- benchmark (0.4.1)
31
- bigdecimal (3.2.2)
30
+ benchmark (0.5.0)
31
+ bigdecimal (4.1.3)
32
32
  coderay (1.1.3)
33
- concurrent-ruby (1.3.5)
34
- connection_pool (2.5.3)
33
+ concurrent-ruby (1.3.8)
34
+ connection_pool (3.0.3)
35
35
  diff-lcs (1.5.1)
36
36
  docile (1.4.0)
37
37
  drb (2.2.3)
38
- i18n (1.14.7)
38
+ i18n (1.15.2)
39
39
  concurrent-ruby (~> 1.0)
40
40
  logger (1.7.0)
41
41
  method_source (1.0.0)
42
- minitest (5.25.5)
43
- mutex_m (0.3.0)
42
+ minitest (6.1.0)
43
+ drb (~> 2.0)
44
+ prism (>= 1.5, < 3)
44
45
  mysql2 (0.5.6)
45
46
  pg (1.5.6)
47
+ prism (2.1.0)
46
48
  pry (0.14.2)
47
49
  coderay (~> 1.1)
48
50
  method_source (~> 1.0)
@@ -60,22 +62,23 @@ GEM
60
62
  diff-lcs (>= 1.2.0, < 2.0)
61
63
  rspec-support (~> 3.13.0)
62
64
  rspec-support (3.13.1)
63
- securerandom (0.3.2)
65
+ securerandom (0.4.1)
64
66
  simplecov (0.22.0)
65
67
  docile (~> 1.1)
66
68
  simplecov-html (~> 0.11)
67
69
  simplecov_json_formatter (~> 0.1)
68
70
  simplecov-html (0.12.3)
69
71
  simplecov_json_formatter (0.1.4)
70
- sqlite3 (1.7.3-aarch64-linux)
71
- sqlite3 (1.7.3-arm-linux)
72
- sqlite3 (1.7.3-arm64-darwin)
73
- sqlite3 (1.7.3-x86-linux)
74
- sqlite3 (1.7.3-x86_64-darwin)
75
- sqlite3 (1.7.3-x86_64-linux)
72
+ sqlite3 (2.10.2-aarch64-linux-gnu)
73
+ sqlite3 (2.10.2-arm-linux-gnu)
74
+ sqlite3 (2.10.2-arm64-darwin)
75
+ sqlite3 (2.10.2-x86-linux-gnu)
76
+ sqlite3 (2.10.2-x86_64-darwin)
77
+ sqlite3 (2.10.2-x86_64-linux-gnu)
76
78
  timeout (0.4.3)
77
79
  tzinfo (2.0.6)
78
80
  concurrent-ruby (~> 1.0)
81
+ uri (1.1.2)
79
82
 
80
83
  PLATFORMS
81
84
  aarch64-linux
data/README.md CHANGED
@@ -54,6 +54,23 @@ class ModelWithUniqueToken < ActiveRecord::Base
54
54
  end
55
55
  ```
56
56
 
57
+ ### Naming the index
58
+
59
+ By default the gem picks the handler whose attribute and scope columns equal the columns of the violated index. When the index has other columns than the declaration (an extra partitioning column, a partial index, an expression), name the index with `index_name:` and the gem matches the violated index by name first. `index_name:` takes one name or an array of names, for a rule that more than one index enforces (on different databases, or during a migration):
60
+
61
+ ```ruby
62
+ class ModelWithNamedIndex < ActiveRecord::Base
63
+ validates :code, uniqueness: { scope: :shop_id, rescue_from_duplicate: { index_name: "index_models_on_shop_id_and_code_and_region" } }
64
+ rescue_from_duplicate :token, scope: :shop_id, index_name: ["index_models_unique_token", "index_models_on_shop_id_and_token"]
65
+ end
66
+ ```
67
+
68
+ On a partitioned PostgreSQL table, the error names the index of the partition that holds the row, not the index of the parent table. List the partition index names too.
69
+
70
+ If no handler names the violated index, the gem falls back to matching columns. SQLite names the index only when an expression index is violated. For a column index it reports only the columns, so there only column matching applies.
71
+
72
+ `RescueFromDuplicate.missing_unique_indexes` treats a handler that names indexes as covered when a unique index or the primary key has one of those names, or when a unique index has its columns. An expression index can only be matched by name.
73
+
57
74
  ## Installation
58
75
 
59
76
  Add this line to your application's Gemfile:
@@ -13,7 +13,7 @@ Gem::Specification.new do |spec|
13
13
  spec.homepage = "https://github.com/Shopify/activerecord-rescue_from_duplicate"
14
14
  spec.license = "MIT"
15
15
 
16
- spec.required_ruby_version = ">= 3.0"
16
+ spec.required_ruby_version = ">= 3.2"
17
17
 
18
18
  spec.files = `git ls-files`.split($/)
19
19
  spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
@@ -0,0 +1,5 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec path: ".."
4
+
5
+ gem "activerecord", "~> 7.1.0"
@@ -0,0 +1,5 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec path: ".."
4
+
5
+ gem "activerecord", "~> 7.2.0"
@@ -0,0 +1,5 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec path: ".."
4
+
5
+ gem "activerecord", "~> 8.0.0"
@@ -0,0 +1,5 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec path: ".."
4
+
5
+ gem "activerecord", "~> 8.1.0"
@@ -0,0 +1,5 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec path: ".."
4
+
5
+ gem "activerecord", github: "rails/rails", branch: "main"
@@ -3,6 +3,7 @@ require 'active_support/core_ext/class'
3
3
  module RescueFromDuplicate::ActiveRecord
4
4
  module Extension
5
5
  DUPLICATE_KEY_REGEX = /for key ['"](?<key>[^'"]+)['"]/
6
+ SQLITE_INDEX_REGEX = /UNIQUE constraint failed: index '(?<index>[^']+)'/
6
7
 
7
8
  extend ActiveSupport::Concern
8
9
 
@@ -38,7 +39,7 @@ module RescueFromDuplicate::ActiveRecord
38
39
  return false unless handler
39
40
 
40
41
  attribute = handler.attributes.first
41
- options = handler.options.except(:case_sensitive, :scope).merge(value: self.send(:read_attribute_for_validation, attribute))
42
+ options = handler.options.except(:case_sensitive, :scope, :index_name).merge(value: self.send(:read_attribute_for_validation, attribute))
42
43
 
43
44
  self.errors.add(attribute, :taken, **options)
44
45
  true
@@ -48,6 +49,22 @@ module RescueFromDuplicate::ActiveRecord
48
49
  handlers = self.class._rescue_from_duplicate_handlers
49
50
  return if handlers.empty?
50
51
 
52
+ handler_for_index_name(handlers, exception) || handler_for_columns(handlers, exception)
53
+ end
54
+
55
+ def handler_for_index_name(handlers, exception)
56
+ named_handlers = handlers.reject { |handler| handler.index_names.empty? }
57
+ return if named_handlers.empty?
58
+
59
+ index_name = exception_index_name(exception)
60
+ return unless index_name
61
+
62
+ named_handlers.detect do |handler|
63
+ handler.rescue? && handler.index_names.include?(index_name)
64
+ end
65
+ end
66
+
67
+ def handler_for_columns(handlers, exception)
51
68
  columns = exception_columns(exception)
52
69
  return unless columns
53
70
  columns = columns.sort
@@ -67,11 +84,38 @@ module RescueFromDuplicate::ActiveRecord
67
84
  end
68
85
  end
69
86
 
87
+ def exception_index_name(exception)
88
+ if exception.message =~ /SQLite3::ConstraintException/
89
+ exception.message[SQLITE_INDEX_REGEX, :index]
90
+ elsif exception.message =~ /PG::UniqueViolation/
91
+ postgresql_exception_index_name(exception)
92
+ else
93
+ other_exception_index_name(exception)
94
+ end
95
+ end
96
+
97
+ def postgresql_exception_index_name(exception)
98
+ result = exception.cause.result if exception.cause.respond_to?(:result)
99
+ index_name = result.error_field(PG::Constants::PG_DIAG_CONSTRAINT_NAME) if result && defined?(PG::Constants::PG_DIAG_CONSTRAINT_NAME)
100
+ index_name || exception.message[/unique constraint "([^"]+)"/, 1]
101
+ end
102
+
103
+ def other_exception_index_name(exception)
104
+ key = exception.message[DUPLICATE_KEY_REGEX, :key]
105
+ return unless key
106
+
107
+ # Mysql > 8.0 prefixes indexes with the table name.
108
+ key.delete_prefix("#{self.class.table_name}.")
109
+ end
110
+
70
111
  def postgresql_exception_columns(exception)
71
112
  extract_columns(exception.message[/Key \((.*?)\)=\(.*?\) already exists./, 1])
72
113
  end
73
114
 
74
115
  def sqlite3_exception_columns(exception)
116
+ # An expression index is reported by name (`index 'name'`), with no columns.
117
+ return if exception.message.match?(SQLITE_INDEX_REGEX)
118
+
75
119
  extract_columns(exception.message[/columns? (.*) (?:is|are) not unique/, 1]) ||
76
120
  extract_columns(exception.message[/UNIQUE constraint failed: ([^:]*)\:?/, 1])
77
121
  end
@@ -82,15 +126,13 @@ module RescueFromDuplicate::ActiveRecord
82
126
  end
83
127
 
84
128
  def other_exception_columns(exception)
85
- key = exception.message[DUPLICATE_KEY_REGEX, :key]
86
- return [] unless key
87
-
88
- # Mysql > 8.0 prefixes indexes with the table name.
89
- index_name = key.delete_prefix("#{self.class.table_name}.")
129
+ index_name = other_exception_index_name(exception)
130
+ return [] unless index_name
90
131
 
91
132
  indexes = self.class.connection.schema_cache.indexes(self.class.table_name)
92
133
  index = indexes.find { |i| i.name == index_name }
93
- index ? index.columns : []
134
+ # An expression index (`(lower(email))`) has a String for its columns and can only match by name.
135
+ index && index.columns.is_a?(Array) ? index.columns : []
94
136
  end
95
137
  end
96
138
  end
@@ -1,5 +1,5 @@
1
1
  module Activerecord
2
2
  module RescueFromDuplicate
3
- VERSION = '0.2.7'
3
+ VERSION = '0.3.0'
4
4
  end
5
5
  end
@@ -18,13 +18,47 @@ module RescueFromDuplicate
18
18
  next unless klass.connection.table_exists?(klass.table_name)
19
19
  unique_indexes = klass.connection.schema_cache.indexes(klass.table_name).select(&:unique)
20
20
 
21
- unless unique_indexes.any? { |index| index.columns.map(&:to_s).sort == handler.columns }
21
+ unless unique_index_for?(unique_indexes, handler) || primary_key_for?(klass, handler)
22
22
  missing_unique_indexes << MissingUniqueIndex.new(klass, handler.attributes, handler.columns)
23
23
  end
24
24
  end
25
25
  end
26
26
  missing_unique_indexes
27
27
  end
28
+
29
+ def self.unique_index_for?(unique_indexes, handler)
30
+ unique_indexes.any? do |index|
31
+ next true if handler.index_names.include?(index.name)
32
+
33
+ # An expression index (`lower(email)`) has a String for its columns and can only match by name.
34
+ index.columns.is_a?(Array) && index.columns.map(&:to_s).sort == handler.columns
35
+ end
36
+ end
37
+ private_class_method :unique_index_for?
38
+
39
+ # Active Record leaves the primary key out of `indexes`, so a handler that names it is checked here.
40
+ def self.primary_key_for?(klass, handler)
41
+ return false if handler.index_names.empty?
42
+
43
+ name = primary_key_name(klass.connection, klass.table_name)
44
+ !name.nil? && handler.index_names.include?(name)
45
+ end
46
+ private_class_method :primary_key_for?
47
+
48
+ def self.primary_key_name(connection, table_name)
49
+ return if Array(connection.schema_cache.primary_keys(table_name)).empty?
50
+
51
+ case connection.adapter_name
52
+ when /mysql|trilogy/i
53
+ "PRIMARY"
54
+ when /postg/i
55
+ connection.select_value(<<~SQL)
56
+ SELECT conname FROM pg_constraint
57
+ WHERE contype = 'p' AND conrelid = #{connection.quote(connection.quote_table_name(table_name))}::regclass
58
+ SQL
59
+ end
60
+ end
61
+ private_class_method :primary_key_name
28
62
  end
29
63
 
30
64
  require 'rescue_from_duplicate/active_record/extension'
@@ -11,5 +11,9 @@ module RescueFromDuplicate
11
11
  def rescue?
12
12
  true
13
13
  end
14
+
15
+ def index_names
16
+ Array(options[:index_name]).map(&:to_s)
17
+ end
14
18
  end
15
19
  end
@@ -12,6 +12,13 @@ module RescueFromDuplicate
12
12
  @validator.options
13
13
  end
14
14
 
15
+ def index_names
16
+ rescue_options = options[:rescue_from_duplicate]
17
+ return [] unless rescue_options.is_a?(Hash)
18
+
19
+ Array(rescue_options[:index_name]).map(&:to_s)
20
+ end
21
+
15
22
  def attributes
16
23
  @validator.attributes
17
24
  end
@@ -13,8 +13,14 @@ module RescueFromDuplicate
13
13
  )
14
14
  end
15
15
 
16
+ let(:expression_index) do
17
+ ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(
18
+ "order_transactions", "index_order_transactions_on_lower_email", true, "(lower(`email`))"
19
+ )
20
+ end
21
+
16
22
  let(:model) do
17
- indexes = [prefix_index, unique_index]
23
+ indexes = [prefix_index, unique_index, expression_index]
18
24
  connection = double(schema_cache: double(indexes: indexes))
19
25
  Class.new do
20
26
  include RescueFromDuplicate::ActiveRecord::Extension
@@ -49,6 +55,18 @@ module RescueFromDuplicate
49
55
  end
50
56
  end
51
57
 
58
+ context "when the key is an expression index" do
59
+ let(:exception) do
60
+ ::ActiveRecord::RecordNotUnique.new(
61
+ "Duplicate entry 'abc' for key 'order_transactions.index_order_transactions_on_lower_email'"
62
+ )
63
+ end
64
+
65
+ it "returns no columns" do
66
+ expect(columns).to eq []
67
+ end
68
+ end
69
+
52
70
  context "when the message carries no key name" do
53
71
  let(:exception) { ::ActiveRecord::RecordNotUnique.new("some unrelated error") }
54
72
 
@@ -67,3 +67,104 @@ describe RescueFromDuplicate::ActiveRecord do
67
67
  it_behaves_like 'database error rescuing'
68
68
  end
69
69
  end
70
+
71
+ describe "RescueFromDuplicate::ActiveRecord matching by index name" do
72
+ let(:named_rescuer) do
73
+ RescueFromDuplicate::Rescuer.new(:name, scope: :shop_id, index_name: "index_rescuable_unique_name", message: "named")
74
+ end
75
+ let(:column_rescuer) do
76
+ RescueFromDuplicate::Rescuer.new(:name, scope: [:shop_id, :type], message: "columns")
77
+ end
78
+
79
+ subject { Rescuable.new }
80
+
81
+ before do
82
+ connection = double(schema_cache: double(indexes: [Rescuable.index]))
83
+ allow(Rescuable).to(receive(:connection).and_return(connection))
84
+ allow(Rescuable).to(receive(:validators).and_return([]))
85
+ allow(Rescuable).to(receive(:_rescue_from_duplicates).and_return([column_rescuer, named_rescuer]))
86
+ allow(Base).to(receive(:exception).and_return(::ActiveRecord::RecordNotUnique.new(message)))
87
+ end
88
+
89
+ context "when a MySQL 8 error names the declared index, whose columns differ from the handler's" do
90
+ let(:message) { "Duplicate entry '1-toto-0' for key 'rescuable.index_rescuable_unique_name'" }
91
+
92
+ it "uses the handler that names the index" do
93
+ subject.create_or_update
94
+ expect(subject.errors[:name]).to eq ["named"]
95
+ end
96
+ end
97
+
98
+ context "when a MySQL 5.7 error names the declared index" do
99
+ let(:message) { "Duplicate entry '1-toto-0' for key 'index_rescuable_unique_name'" }
100
+
101
+ it "uses the handler that names the index" do
102
+ subject.create_or_update
103
+ expect(subject.errors[:name]).to eq ["named"]
104
+ end
105
+ end
106
+
107
+ context "when a PostgreSQL error names the declared index, whose columns differ from the handler's" do
108
+ let(:message) { "PG::UniqueViolation: ERROR: duplicate key value violates unique constraint \"index_rescuable_unique_name\"\nDETAIL: Key (shop_id, name, region)=(1, toto, 0) already exists." }
109
+
110
+ it "uses the handler that names the index" do
111
+ subject.create_or_update
112
+ expect(subject.errors[:name]).to eq ["named"]
113
+ end
114
+ end
115
+
116
+ context "when a PostgreSQL-compatible error names the declared index without a DETAIL line" do
117
+ let(:message) { "PG::UniqueViolation: ERROR: duplicate key value violates unique constraint \"index_rescuable_unique_name\"" }
118
+
119
+ it "uses the handler that names the index" do
120
+ subject.create_or_update
121
+ expect(subject.errors[:name]).to eq ["named"]
122
+ end
123
+ end
124
+
125
+ context "when a SQLite error names the declared index" do
126
+ let(:message) { "SQLite3::ConstraintException: UNIQUE constraint failed: index 'index_rescuable_unique_name'" }
127
+
128
+ it "uses the handler that names the index" do
129
+ subject.create_or_update
130
+ expect(subject.errors[:name]).to eq ["named"]
131
+ end
132
+ end
133
+
134
+ context "when a SQLite error names an index that no handler names" do
135
+ let(:message) { "SQLite3::ConstraintException: UNIQUE constraint failed: index 'index_rescuable_other'" }
136
+
137
+ it "raises" do
138
+ expect { subject.create_or_update }.to raise_error(ActiveRecord::RecordNotUnique)
139
+ end
140
+ end
141
+
142
+ context "when the error names one of several indexes the handler names" do
143
+ let(:named_rescuer) do
144
+ RescueFromDuplicate::Rescuer.new(:name, scope: :shop_id, index_name: ["index_rescuable_other", "index_rescuable_unique_name"], message: "named")
145
+ end
146
+ let(:message) { "Duplicate entry '1-toto-0' for key 'rescuable.index_rescuable_unique_name'" }
147
+
148
+ it "uses the handler that names the index" do
149
+ subject.create_or_update
150
+ expect(subject.errors[:name]).to eq ["named"]
151
+ end
152
+ end
153
+
154
+ context "when the error names another index" do
155
+ let(:message) { "PG::UniqueViolation: ERROR: duplicate key value violates unique constraint \"index_rescuable_on_shop_id_and_type_and_name\"\nDETAIL: Key (shop_id, type, name)=(1, Rescuable, toto) already exists." }
156
+
157
+ it "falls back to matching the index columns" do
158
+ subject.create_or_update
159
+ expect(subject.errors[:name]).to eq ["columns"]
160
+ end
161
+ end
162
+
163
+ context "when the error names another index and no handler matches its columns" do
164
+ let(:message) { "PG::UniqueViolation: ERROR: duplicate key value violates unique constraint \"index_rescuable_other\"\nDETAIL: Key (shop_id, name, region)=(1, toto, 0) already exists." }
165
+
166
+ it "raises" do
167
+ expect { subject.create_or_update }.to raise_error(ActiveRecord::RecordNotUnique)
168
+ end
169
+ end
170
+ end
data/spec/rescuer_spec.rb CHANGED
@@ -14,6 +14,20 @@ describe RescueFromDuplicate::Rescuer do
14
14
  it "returns the options" do
15
15
  expect(subject.options).to eq scope: [:type, :shop_id], message: "Derp!"
16
16
  end
17
+
18
+ it "has no index names by default" do
19
+ expect(subject.index_names).to eq []
20
+ end
21
+
22
+ it "returns the index name from the index_name option" do
23
+ rescuer = RescueFromDuplicate::Rescuer.new(:name, scope: :shop_id, index_name: :index_rescuable_on_shop_id_and_name)
24
+ expect(rescuer.index_names).to eq ["index_rescuable_on_shop_id_and_name"]
25
+ end
26
+
27
+ it "returns every index name from an array index_name option" do
28
+ rescuer = RescueFromDuplicate::Rescuer.new(:name, scope: :shop_id, index_name: ["index_rescuable_on_shop_id_and_name", "rescuable_pkey"])
29
+ expect(rescuer.index_names).to eq ["index_rescuable_on_shop_id_and_name", "rescuable_pkey"]
30
+ end
17
31
  end
18
32
 
19
33
  shared_examples 'a model with rescued unique error without validator' do
@@ -42,3 +56,53 @@ end
42
56
  describe PostgresqlModel do
43
57
  it_behaves_like 'a model with rescued unique error without validator'
44
58
  end
59
+
60
+ shared_examples 'a model with a rescuer naming its index' do
61
+ before { described_class.create!(relation_id: 1, code: 'toto', region: 1) }
62
+
63
+ it 'adds an error on the model when the named index is violated' do
64
+ model = described_class.create(relation_id: 1, code: 'toto', region: 1)
65
+ expect(model.errors[:code]).to eq(["code must be unique for this relation"])
66
+ end
67
+
68
+ it 'does not put the index_name option in the error details' do
69
+ model = described_class.create(relation_id: 1, code: 'toto', region: 1)
70
+ expect(model.errors.details[:code].first).not_to have_key(:index_name)
71
+ end
72
+ end
73
+
74
+ describe MysqlModel do
75
+ it_behaves_like 'a model with a rescuer naming its index'
76
+ end
77
+
78
+ describe PostgresqlModel do
79
+ it_behaves_like 'a model with a rescuer naming its index'
80
+ end
81
+
82
+ describe PostgresqlModel do
83
+ it 'adds an error on the model when a named expression index is violated' do
84
+ PostgresqlModel.create!(email: 'Toto@example.com')
85
+ model = PostgresqlModel.create(email: 'toto@example.com')
86
+ expect(model.errors[:email]).to eq(["email is already taken"])
87
+ end
88
+ end
89
+
90
+ describe Sqlite3Model do
91
+ it 'raises when the index columns do not match, because SQLite reports only the columns of a column index' do
92
+ Sqlite3Model.create!(relation_id: 1, code: 'toto', region: 1)
93
+ expect { Sqlite3Model.create(relation_id: 1, code: 'toto', region: 1) }.to raise_error(ActiveRecord::RecordNotUnique)
94
+ end
95
+
96
+ it 'adds an error on the model when a named expression index is violated' do
97
+ Sqlite3Model.create!(email: 'Toto@example.com')
98
+ model = Sqlite3Model.create(email: 'toto@example.com')
99
+ expect(model.errors[:email]).to eq(["email is already taken"])
100
+ end
101
+ end
102
+
103
+ describe MysqlModel do
104
+ it 'raises ActiveRecord::RecordNotUnique when an expression index that no handler names is violated' do
105
+ MysqlModel.create!(email: 'Toto@example.com')
106
+ expect { MysqlModel.create(email: 'toto@example.com') }.to raise_error(ActiveRecord::RecordNotUnique)
107
+ end
108
+ end
data/spec/spec_helper.rb CHANGED
@@ -56,14 +56,16 @@ module RescueFromDuplicate
56
56
  @uniqueness_validator ||= ::ActiveRecord::Validations::UniquenessValidator.new(
57
57
  attributes: [:name],
58
58
  case_sensitive: true, scope: [:type, :shop_id],
59
- rescue_from_duplicate: true
59
+ rescue_from_duplicate: true,
60
+ class: self
60
61
  ).tap { |o| o.setup(self) if o.respond_to?(:setup) }
61
62
  end
62
63
 
63
64
  def self.uniqueness_validator_without_rescue
64
65
  @uniqueness_validator_without_rescue ||= ::ActiveRecord::Validations::UniquenessValidator.new(
65
66
  attributes: [:name],
66
- case_sensitive: true, scope: [:shop_id, :type]
67
+ case_sensitive: true, scope: [:shop_id, :type],
68
+ class: self
67
69
  ).tap { |o| o.setup(self) if o.respond_to?(:setup) }
68
70
  end
69
71
 
@@ -34,22 +34,32 @@ class CreateAllTables < ActiveRecord::Migration[5.2]
34
34
 
35
35
  t.string :name
36
36
  t.integer :size
37
+
38
+ t.string :code
39
+ t.integer :region
40
+ t.string :email
41
+ t.string :serial
37
42
  end
38
43
 
39
44
  add_index name, [:relation_id, :handle], unique: true
40
45
  add_index name, :name, unique: true
41
46
  add_index name, :size, unique: true
47
+ add_index name, [:relation_id, :code, :region], unique: true, name: "index_#{name}_unique_code"
48
+ add_index name, [:relation_id, :serial, :region], unique: true, name: "index_#{name}_unique_serial"
42
49
  end
43
50
 
44
51
  def self.up
45
52
  ActiveRecord::Base.establish_connection(CONNECTIONS.fetch(:test_mysql))
46
53
  recreate_table(:mysql_models)
54
+ execute "CREATE UNIQUE INDEX index_mysql_models_on_lower_email ON mysql_models ((lower(email)))"
47
55
 
48
56
  ActiveRecord::Base.establish_connection(CONNECTIONS.fetch(:test_postgresql))
49
57
  recreate_table(:postgresql_models)
58
+ add_index :postgresql_models, "lower(email)", unique: true, name: "index_postgresql_models_on_lower_email"
50
59
 
51
60
  ActiveRecord::Base.establish_connection(CONNECTIONS.fetch(:test_sqlite3))
52
61
  recreate_table(:sqlite3_models)
62
+ add_index :sqlite3_models, "lower(email)", unique: true, name: "index_sqlite3_models_on_lower_email"
53
63
  end
54
64
  end
55
65
 
@@ -60,9 +70,11 @@ CreateAllTables.up
60
70
  module TestModel
61
71
  def self.included(base)
62
72
  base.rescue_from_duplicate(:handle, scope: :relation_id, message: "handle must be unique for this relation")
73
+ base.rescue_from_duplicate(:code, scope: :relation_id, index_name: "index_#{base.table_name}_unique_code", message: "code must be unique for this relation")
63
74
 
64
75
  base.validates(:name, uniqueness: { rescue_from_duplicate: true, case_sensitive: true }, allow_nil: true)
65
76
  base.validates(:size, uniqueness: { rescue_from_duplicate: true }, allow_nil: true)
77
+ base.validates(:serial, uniqueness: { scope: :relation_id, rescue_from_duplicate: { index_name: "index_#{base.table_name}_unique_serial" } }, allow_nil: true)
66
78
  end
67
79
  end
68
80
 
@@ -75,12 +87,16 @@ end
75
87
  class PostgresqlModel < ActiveRecord::Base
76
88
  include TestModel
77
89
 
90
+ rescue_from_duplicate :email, index_name: ["index_postgresql_models_email_legacy", "index_postgresql_models_on_lower_email"], message: "email is already taken"
91
+
78
92
  establish_connection(CONNECTIONS.fetch(:test_postgresql))
79
93
  end
80
94
 
81
95
  class Sqlite3Model < ActiveRecord::Base
82
96
  include TestModel
83
97
 
98
+ rescue_from_duplicate :email, index_name: "index_sqlite3_models_on_lower_email", message: "email is already taken"
99
+
84
100
  establish_connection(CONNECTIONS.fetch(:test_sqlite3))
85
101
  end
86
102
 
@@ -25,6 +25,34 @@ describe RescueFromDuplicate::UniquenessRescuer do
25
25
  end
26
26
  end
27
27
 
28
+ context "validator with rescue naming indexes" do
29
+ let(:validator) do
30
+ ::ActiveRecord::Validations::UniquenessValidator.new(
31
+ attributes: [:name],
32
+ scope: [:shop_id],
33
+ rescue_from_duplicate: { index_name: ["index_rescuable_on_shop_id_and_name", "rescuable_pkey"] },
34
+ class: Rescuable,
35
+ ).tap { |o| o.setup(Rescuable) if o.respond_to?(:setup) }
36
+ end
37
+ subject { RescueFromDuplicate::UniquenessRescuer.new(validator) }
38
+
39
+ it "rescues" do
40
+ expect(subject.rescue?).to be_truthy
41
+ end
42
+
43
+ it "returns the index names" do
44
+ expect(subject.index_names).to eq ["index_rescuable_on_shop_id_and_name", "rescuable_pkey"]
45
+ end
46
+ end
47
+
48
+ context "validator with rescue: true" do
49
+ subject { RescueFromDuplicate::UniquenessRescuer.new(Rescuable.uniqueness_validator) }
50
+
51
+ it "has no index names" do
52
+ expect(subject.index_names).to eq []
53
+ end
54
+ end
55
+
28
56
  context "validator without rescue" do
29
57
  subject { RescueFromDuplicate::UniquenessRescuer.new(Rescuable.uniqueness_validator_without_rescue) }
30
58
  it "doesn't rescues" do
@@ -46,6 +46,40 @@ shared_examples 'a model with rescued uniqueness validator' do
46
46
  end
47
47
  end
48
48
 
49
+ shared_examples 'a model with a uniqueness validation naming its index' do
50
+ before do
51
+ allow_any_instance_of(ActiveRecord::Validations::UniquenessValidator).to(receive(:validate_each)).and_return(nil)
52
+ described_class.create!(relation_id: 1, serial: 'toto', region: 1)
53
+ end
54
+
55
+ it 'adds a taken error when the named index, whose columns differ from the validation, is violated' do
56
+ model = described_class.create(relation_id: 1, serial: 'toto', region: 1)
57
+ expect(model).not_to be_persisted
58
+ expect(model.errors[:serial]).to eq ["has already been taken"]
59
+ expect(model.errors.details[:serial].first[:error]).to eq :taken
60
+ end
61
+ end
62
+
63
+ shared_examples 'missing primary key finding' do |primary_key_name|
64
+ it 'accepts a handler that names the primary key' do
65
+ allow(described_class).to(receive(:_rescue_from_duplicate_handlers).and_return([
66
+ RescueFromDuplicate::Rescuer.new(:id, index_name: ["index_that_does_not_exist", primary_key_name]),
67
+ ]))
68
+
69
+ missing_unique_indexes = RescueFromDuplicate.missing_unique_indexes.select { |mi| mi.model == described_class }
70
+ expect(missing_unique_indexes).to be_empty
71
+ end
72
+
73
+ it 'reports a handler on the primary key column that names another index' do
74
+ allow(described_class).to(receive(:_rescue_from_duplicate_handlers).and_return([
75
+ RescueFromDuplicate::Rescuer.new(:id, index_name: "index_that_does_not_exist"),
76
+ ]))
77
+
78
+ missing_unique_indexes = RescueFromDuplicate.missing_unique_indexes.select { |mi| mi.model == described_class }
79
+ expect(missing_unique_indexes.map(&:columns)).to eq [["id"]]
80
+ end
81
+ end
82
+
49
83
  shared_examples 'missing index finding' do
50
84
  describe do
51
85
  context 'all indexes are satisfied' do
@@ -61,12 +95,40 @@ shared_examples 'missing index finding' do
61
95
  ::ActiveRecord::Validations::UniquenessValidator.new(
62
96
  attributes: [:name],
63
97
  case_sensitive: true, scope: [:titi, :toto],
98
+ class: described_class,
64
99
  )
65
100
  ),
66
101
  RescueFromDuplicate::Rescuer.new(:name, scope: [:hello])
67
102
  ]))
68
103
  }
69
104
 
105
+ it 'reports a handler whose named index does not exist' do
106
+ allow(described_class).to(receive(:_rescue_from_duplicate_handlers).and_return([
107
+ RescueFromDuplicate::Rescuer.new(:code, scope: :relation_id, index_name: "index_that_does_not_exist"),
108
+ ]))
109
+
110
+ missing_unique_indexes = RescueFromDuplicate.missing_unique_indexes.select { |mi| mi.model == described_class }
111
+ expect(missing_unique_indexes.map(&:columns)).to eq [["code", "relation_id"]]
112
+ end
113
+
114
+ it 'accepts a handler when one of its named indexes is a unique index' do
115
+ allow(described_class).to(receive(:_rescue_from_duplicate_handlers).and_return([
116
+ RescueFromDuplicate::Rescuer.new(:code, scope: :relation_id, index_name: ["index_that_does_not_exist", "index_#{described_class.table_name}_unique_code"]),
117
+ ]))
118
+
119
+ missing_unique_indexes = RescueFromDuplicate.missing_unique_indexes.select { |mi| mi.model == described_class }
120
+ expect(missing_unique_indexes).to be_empty
121
+ end
122
+
123
+ it 'accepts a handler whose named index does not exist when a unique index has its columns' do
124
+ allow(described_class).to(receive(:_rescue_from_duplicate_handlers).and_return([
125
+ RescueFromDuplicate::Rescuer.new(:handle, scope: :relation_id, index_name: "index_that_does_not_exist"),
126
+ ]))
127
+
128
+ missing_unique_indexes = RescueFromDuplicate.missing_unique_indexes.select { |mi| mi.model == described_class }
129
+ expect(missing_unique_indexes).to be_empty
130
+ end
131
+
70
132
  it 'returns the missing indexes' do
71
133
  missing_unique_indexes = RescueFromDuplicate.missing_unique_indexes.select { |mi| mi.model == described_class }
72
134
  expect(missing_unique_indexes).not_to be_empty
@@ -91,10 +153,14 @@ end
91
153
 
92
154
  describe MysqlModel do
93
155
  it_behaves_like 'a model with rescued uniqueness validator'
156
+ it_behaves_like 'a model with a uniqueness validation naming its index'
94
157
  it_behaves_like 'missing index finding'
158
+ it_behaves_like 'missing primary key finding', "PRIMARY"
95
159
  end
96
160
 
97
161
  describe PostgresqlModel do
98
162
  it_behaves_like 'a model with rescued uniqueness validator'
163
+ it_behaves_like 'a model with a uniqueness validation naming its index'
99
164
  it_behaves_like 'missing index finding'
165
+ it_behaves_like 'missing primary key finding', "postgresql_models_pkey"
100
166
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: activerecord-rescue_from_duplicate
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.7
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Guillaume Malette
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-08-26 00:00:00.000000000 Z
11
+ date: 2026-12-01 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activerecord
@@ -158,6 +158,11 @@ files:
158
158
  - Rakefile
159
159
  - activerecord-rescue_from_duplicate.gemspec
160
160
  - docker-compose.yml
161
+ - gemfiles/activerecord_7.1.gemfile
162
+ - gemfiles/activerecord_7.2.gemfile
163
+ - gemfiles/activerecord_8.0.gemfile
164
+ - gemfiles/activerecord_8.1.gemfile
165
+ - gemfiles/activerecord_edge.gemfile
161
166
  - lib/activerecord-rescue_from_duplicate.rb
162
167
  - lib/rescue_from_duplicate/active_record.rb
163
168
  - lib/rescue_from_duplicate/active_record/extension.rb
@@ -186,7 +191,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
186
191
  requirements:
187
192
  - - ">="
188
193
  - !ruby/object:Gem::Version
189
- version: '3.0'
194
+ version: '3.2'
190
195
  required_rubygems_version: !ruby/object:Gem::Requirement
191
196
  requirements:
192
197
  - - ">="