From fe967ee4529bd59481be74c126c4d5603dd3dabc Mon Sep 17 00:00:00 2001 From: Spas Bojanov Date: Wed, 17 Jun 2020 17:00:59 -0400 Subject: [PATCH] sql: fix NewUniquenessConstraintViolationError reporting Release note (bug fix): If NewUniquenessConstraintViolationError cannot initialize a row fetcher it will only report this error to the client without wrappibng it with information about the actual constraint violation which can be confusing. Old error: `ERROR: column-id "2" does not exist` New Error: ``` ERROR: duplicate key value (b)=(couldn't fetch value: column-id "2" does not exist) violates unique constraint "t_secondary" ``` See #46276. --- pkg/sql/logictest/testdata/logic_test/drop_index | 16 ++++++++++++++++ pkg/sql/row/errors.go | 6 +++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/pkg/sql/logictest/testdata/logic_test/drop_index b/pkg/sql/logictest/testdata/logic_test/drop_index index e698cb1515ad..539979693334 100644 --- a/pkg/sql/logictest/testdata/logic_test/drop_index +++ b/pkg/sql/logictest/testdata/logic_test/drop_index @@ -323,3 +323,19 @@ CREATE TABLE drop_index_test(a int); CREATE INDEX drop_index_test_index ON drop_ ---- NOTICE: the data for dropped indexes is reclaimed asynchronously HINT: The reclamation delay can be customized in the zone configuration for the table. + +# test correct error reporting from NewUniquenessConstraintViolationError; see #46376 +subtest new_uniqueness_constraint_error + +statement ok +CREATE TABLE t (a INT PRIMARY KEY, b DECIMAL(10,1) NOT NULL DEFAULT(0), UNIQUE INDEX t_secondary (b), FAMILY (a, b)); +INSERT INTO t VALUES (100, 500.5); + +statement ok +BEGIN; +DROP INDEX t_secondary CASCADE; +ALTER TABLE t DROP COLUMN b; +INSERT INTO t SELECT a + 1 FROM t; + +statement error pq: duplicate key value +UPSERT INTO t SELECT a + 1 FROM t; diff --git a/pkg/sql/row/errors.go b/pkg/sql/row/errors.go index 2457cab00a3a..6e5afe2cda87 100644 --- a/pkg/sql/row/errors.go +++ b/pkg/sql/row/errors.go @@ -123,7 +123,11 @@ func NewUniquenessConstraintViolationError( &sqlbase.DatumAlloc{}, tableArgs, ); err != nil { - return err + return pgerror.Newf(pgcode.UniqueViolation, + "duplicate key value (%s)=(%v) violates unique constraint %q", + strings.Join(index.ColumnNames, ","), + errors.Wrapf(err, "couldn't fetch value"), + index.Name) } f := singleKVFetcher{kvs: [1]roachpb.KeyValue{{Key: key}}} if value != nil {