Skip to content

Commit b7e52f7

Browse files
aidanharanAidan Haran
andauthored
Primary key violation should result in RecordNotUnique error (#940)
* Primary key violation should result in ActiveRecord::RecordNotUnique error * Updated changelog Co-authored-by: Aidan Haran <[email protected]>
1 parent 4af32b0 commit b7e52f7

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
@@ -444,7 +444,7 @@ def translate_exception(e, message:, sql:, binds:)
444444
case message
445445
when /(SQL Server client is not connected)|(failed to execute statement)/i
446446
ConnectionNotEstablished.new(message)
447-
when /(cannot insert duplicate key .* with unique index) | (violation of unique key constraint)/i
447+
when /(cannot insert duplicate key .* with unique index) | (violation of (unique|primary) key constraint)/i
448448
RecordNotUnique.new(message, sql: sql, binds: binds)
449449
when /(conflicted with the foreign key constraint) | (The DELETE statement conflicted with the REFERENCE constraint)/i
450450
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)