Skip to content

Commit

Permalink
Add constraint name to error for unique constraint, check constraint,…
Browse files Browse the repository at this point in the history
… and foreign key constraint violations. Those constraint names are then propagated over the PostgreSQL wire protocol and will show up for example in JDBC exceptions (org.postgresql.util.PSQLException#getServerErrorMessage().getConstraint()). This commit improves PostgreSQL compatibility of CockroachDB error messages.
  • Loading branch information
alex.berger@nexiot.ch authored and alex-berger committed Oct 17, 2020
1 parent b1abf9c commit e7968ec
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
14 changes: 7 additions & 7 deletions pkg/sql/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,10 @@ func validateForeignKey(
return err
}
if values.Len() > 0 {
return pgerror.Newf(pgcode.ForeignKeyViolation,
return pgerror.WithConstraintName(pgerror.Newf(pgcode.ForeignKeyViolation,
"foreign key violation: MATCH FULL does not allow mixing of null and nonnull values %s for %s",
formatValues(colNames, values), fk.Name,
)
), fk.Name)
}
}
query, colNames, err := nonMatchingRowQuery(
Expand All @@ -296,9 +296,9 @@ func validateForeignKey(
return err
}
if values.Len() > 0 {
return pgerror.Newf(pgcode.ForeignKeyViolation,
return pgerror.WithConstraintName(pgerror.Newf(pgcode.ForeignKeyViolation,
"foreign key violation: %q row %s has no match in %q",
srcTable.Name, formatValues(colNames, values), targetTable.GetName())
srcTable.Name, formatValues(colNames, values), targetTable.GetName()), fk.Name)
}
return nil
}
Expand Down Expand Up @@ -361,11 +361,11 @@ func checkMutationInput(
if err != nil {
// If we ran into an error trying to read the check constraint, wrap it
// and return.
return errors.Wrapf(err, "failed to satisfy CHECK constraint (%s)", checks[i].Expr)
return pgerror.WithConstraintName(errors.Wrapf(err, "failed to satisfy CHECK constraint (%s)", checks[i].Expr), checks[i].Name)
}
return pgerror.Newf(
return pgerror.WithConstraintName(pgerror.Newf(
pgcode.CheckViolation, "failed to satisfy CHECK constraint (%s)", expr,
)
), checks[i].Name)
}
colIdx++
}
Expand Down
3 changes: 2 additions & 1 deletion pkg/sql/row/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,13 @@ func NewUniquenessConstraintViolationError(
"duplicate key value: decoding err=%s", err)
}

return pgerror.Newf(pgcode.UniqueViolation,
error := pgerror.Newf(pgcode.UniqueViolation,
"duplicate key value (%s)=(%s) violates unique constraint %q",
strings.Join(names, ","),
strings.Join(values, ","),
index.Name,
)
return pgerror.WithConstraintName(error, index.Name)
}

// NewLockNotAvailableError creates an error that represents an inability to
Expand Down

0 comments on commit e7968ec

Please sign in to comment.