Skip to content

Commit 58bd872

Browse files
aidanharanAidan Haran
authored and
Lavika
committed
Primary key violation should result in RecordNotUnique error (rails-sqlserver#940)
* Primary key violation should result in ActiveRecord::RecordNotUnique error * Updated changelog Co-authored-by: Aidan Haran <aharan@fusioneer.com>
1 parent 2fa2bb4 commit 58bd872

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

CHANGELOG.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,17 @@
1+
#### Unreleased
2+
3+
#### Fixed
4+
5+
- [#940](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/pull/940) Primary key violation should result in RecordNotUnique error
6+
7+
#### Changed
8+
9+
- ...
10+
11+
#### Added
12+
13+
- ...
14+
115
## v6.1.1.0
216

317
[Full changelog](https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/compare/v6.1.0.0...v6.1.1.0)

lib/active_record/connection_adapters/sqlserver_adapter.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ def translate_exception(e, message:, sql:, binds:)
469469
case message
470470
when /(SQL Server client is not connected)|(failed to execute statement)/i
471471
ConnectionNotEstablished.new(message)
472-
when /(cannot insert duplicate key .* with unique index) | (violation of unique key constraint)/i
472+
when /(cannot insert duplicate key .* with unique index) | (violation of (unique|primary) key constraint)/i
473473
RecordNotUnique.new(message, sql: sql, binds: binds)
474474
when /(conflicted with the foreign key constraint) | (The DELETE statement conflicted with the REFERENCE constraint)/i
475475
InvalidForeignKey.new(message, sql: sql, binds: binds)

test/cases/adapter_test_sqlserver.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,14 @@ class AdapterTestSQLServer < ActiveRecord::TestCase
120120
"expected database #{db_config.database} to exist"
121121
end
122122

123+
it "test primary key violation" do
124+
Post.create!(id: 0, title: 'Setup', body: 'Create post with primary key of zero')
125+
126+
assert_raise ActiveRecord::RecordNotUnique do
127+
Post.create!(id: 0, title: 'Test', body: 'Try to create another post with primary key of zero')
128+
end
129+
end
130+
123131
describe "with different language" do
124132
before do
125133
@default_language = connection.user_options_language

0 commit comments

Comments
 (0)