Skip to content

DatabaseError caused by foreign key ON DELETE RESTRICT is not classified as ForeignKeyViolation using Sqlite #4299

@dav-wolff

Description

@dav-wolff

Setup

Versions

  • Rust: rustc 1.81.0 (eeb90cda1 2024-09-04) (rustc 1.83.0-nightly (fb4aebddd 2024-09-30) originally tested )
  • Diesel: diesel v2.2.4
  • Database: 3.46.0 2024-05-23 13:25:27 96c92aba00c8375bc32fafcdf12429c58bd8aabfcadab6683e35bbb9cdebf19e (64-bit)
  • Operating System NixOS 24.11.20241006.c31898a (Vicuna)

Feature Flags

  • diesel: "sqlite", "returning_clauses_for_sqlite_3_35", "r2d2"

Problem Description

Diesel using sqlite doesn't recognize foreign key violations caused by deleting a row that is referenced by a row in a different table which is a foreign key with ON DELETE RESTRICT. It returns a DatabaseErrorKind::Unknown instead of a DatabaseErrorKind::ForeignKeyViolation.

I believe a DatabaseErrorKind::ForeignKeyViolation would be appropriate because the error arises from the foreign key constraint and the error message says "FOREIGN KEY constraint failed".

What are you trying to accomplish?

Check if the error return from diesel::delete(...).execute(...) is caused by a foreign key violation, or some general database error, in order to properly handle the error.

For now I'm thinking of just checking for the error message, but I'm not sure if that is stable or might change at some point.

What is the expected output?

DatabaseError(
    ForeignKeyViolation,
    "FOREIGN KEY constraint failed",
)

What is the actual output?

DatabaseError(
    Unknown,
    "FOREIGN KEY constraint failed",
)

Are you seeing any additional errors?

No

Steps to reproduce

  1. Create a table with a foreign key with ON DELETE RESTRICT
  2. Violate that restriction using diesel::delete.

Reproduction: https://github.com/dav-wolff/diesel-foreign-key-violation

Checklist

  • This issue can be reproduced on Rust's stable channel. (Your issue will be
    closed if this is not the case)
  • This issue can be reproduced without requiring a third party crate

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions