Skip to content

ActiveRecord::StatementInvalid raised in case of duplicate key #939

Closed
@gucki

Description

@gucki

Issue

Creating two entries with the same id (primary key) of the same model fails with an ActiveRecord::StatementInvalid exception rather than ActiveRecord::RecordNotUnique. This is different to how other db adapters, ex postgresql work.

Expected behavior

ActiveRecord::RecordNotUnique is raised

Actual behavior

ActiveRecord::StatementInvalid is raised

/usr/local/bundle/gems/activerecord-sqlserver-adapter-6.1.1.0/lib/active_record/connection_adapters/sqlserver/database_statements.rb:447:in each': TinyTds::Error: Violation of PRIMARY KEY constraint 'PK__entities__3213E83F5236FD09'. Cannot insert duplicate key in object 'dbo.entities'. The duplicate key value is (aa). (ActiveRecord::StatementInvalid) /usr/local/bundle/gems/activerecord-sqlserver-adapter-6.1.1.0/lib/active_record/connection_adapters/sqlserver/database_statements.rb:447:in each': Violation of PRIMARY KEY constraint 'PK__entities__3213E83F5236FD09'. Cannot insert duplicate key in object 'dbo.entities'. The duplicate key value is (aa). (TinyTds::Error)

How to reproduce

Create a simple model:

create_table "entities", id: :string, force: :cascade do |t|
t.datetime "created_at", precision: 7, null: false
t.datetime "updated_at", precision: 7, null: false
end

Try to insert two records with the same id:
Entity.create!(id: "aa")
Entity.create!(id: "aa")

Details

rails (6.1.4.1)
activerecord-sqlserver-adapter (6.1.1.0)
tiny_tds (2.1.5)

Compile-time settings (established with the "configure" script)
Version: freetds v1.2.18
freetds.conf directory: /etc
MS db-lib source compatibility: yes
Sybase binary compatibility: no
Thread safety: yes
iconv library: yes
TDS version: auto
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: no
OpenSSL: yes
GnuTLS: no
MARS: yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions