Skip to content

[Postgres] add constraint() to the DatabaseError trait, which covers most uses of downcasting #821

@abonander

Description

@abonander

In my experience, far and away the primary reason to use DatabaseError::downcast_ref() is to check the constraint name. It would be nice not to have to downcast, though:

https://github.com/launchbadge/sqlx/blob/master/sqlx-core/src/error.rs#L146

 pub trait DatabaseError: ... {
    // existing methods omitted

    /// Returns the name of the constraint that triggered the error, if applicable. 
    /// If the error was caused by a conflict of a unique index, this will be the index name.
    /// 
    /// ### Note
    /// Currently only populated by the Postgres driver.
    fn constraint(&self) -> Option<&str> { None }
}

This only needs to be overridden by PgDatabaseError as unfortunately none of the other databases have this context in their errors.

https://github.com/launchbadge/sqlx/blob/master/sqlx-core/src/postgres/error.rs#L164

impl DatabaseError for PgDatabaseError {
    // existing methods omitted

    fn constraint(&self) -> Option<&str> {
        // invokes the inherent method of the same name
        self.constraint()
    }
}

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