Skip to content

feat(dbsql): Uniqueness and foreign key violation detections - #246

Open
onelapahead wants to merge 2 commits into
hyperledger-firefly:mainfrom
kaleido-io:dbsql-unique-violation
Open

feat(dbsql): Uniqueness and foreign key violation detections#246
onelapahead wants to merge 2 commits into
hyperledger-firefly:mainfrom
kaleido-io:dbsql-unique-violation

Conversation

@onelapahead

@onelapahead onelapahead commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Description

Callers that want to return a 409 when a row already exists currently either run a pre-insert existence query (which races against concurrent inserts and yields an opaque 500 for the loser) or string-match the driver's error text. Neither are what we want.

This adds Database.IsUniqueViolation and Database.IsForeignKeyViolation, which inspect the full error chain for an integrity constraint violation so callers can rely on the database constraint for enforcement and map the resulting error to a meaningful response.

For PostgreSQL, you can do something like:

import "lib/pq"

// ...

features.ConstraintViolationClassifier = func(err error) *dbsql.ConstraintViolation {
    var pqErr *pq.Error
    if errors.As(err, &pqErr) && (pqErr.Code == dbsql.SQLStateUniqueViolation || pqErr.Code == dbsql.SQLStateForeignKeyViolation) {
        return &dbsql.ConstraintViolation{SQLState: string(pqErr.Code), Constraint: pqErr.Constraint}
    }
    return nil
}

Register that in your DB. So then an Insert can look roughly like:

if err := someTable.Insert(ctx, aResource); err != nil {
    if db.IsUniqueViolation(err, "a_uniqueness_index_for_resource") {
        return nil, i18n.NewError(ctx, msgs.MsgResourceAlreadyExists)
    }
    return nil, err
}

so we can actually detect such specific violations and test them more thoroughly. For multiple uniqueness constraints,etc. we can use switch.

Behavior change

i18n supporting Unwrap is really really useful so when we do i18n.WrapError, we can still do error.Is(err, sentinel) for sentinel pattern errors (whether from other libs, or sentinel errors we create).

If there is code that relies on the unwrap not being supported, and has written itself as such thats a breaking change. But an edge case that could be considered a bug, and has made i18n have some limitations as I try to use it, I think its a breaking change that can be documented in a minor release since it is contained and small. And its behavior that is hard to rely on - you would have to have code that could either return i18n errors or unwrapped errors, and if conditions trying to distinguish/check for the unwrapped errors.

Callers that want to return a 409 when a row already exists currently either
run a pre-insert existence query (which races against concurrent inserts and
yields an opaque FF00177 500 for the loser) or string-match the driver's error
text. Both are fragile.

This adds Database.IsUniqueViolation and Database.IsForeignKeyViolation, which
inspect the full error chain for an integrity constraint violation so callers
can rely on the database constraint for enforcement and map the resulting
error to a meaningful response:

- SQLFeatures.ConstraintViolationClassifier is an optional provider hook that
  returns the SQLSTATE and, where the driver exposes it, the violated
  constraint name
- When no classifier is set, the fallback matches SQLSTATE 23505 / 23503 via a
  SQLState() method on the error (lib/pq and pgx both implement it), without
  adding a Postgres driver dependency to this module
- The SQLite provider gets a built-in classifier using the driver's extended
  constraint codes
- Constraint-name filtering fails closed when the name cannot be determined

Also adds Unwrap() to i18n's ffError so errors.Is/errors.As can reach the
original cause through WrapError - previously the embedded error interface
hid the underlying Unwrap and the chain stopped at the ffError.

Signed-off-by: hfuss <hayden.fuss@kaleido.io>
Signed-off-by: hfuss <hayden.fuss@kaleido.io>
@onelapahead
onelapahead requested a review from a team as a code owner August 28, 2026 22:19
@onelapahead

Copy link
Copy Markdown
Contributor Author

On the point about Unwrap, there's actually code in FireFly expecting Unwrap to be supported in order to detect wrapped errors:

So this would fix those bugs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant