Sfoglia il codice sorgente

report duplicate primary keys as readable key components

A composite key is stored length-prefixed ("<len>:<value>" repeated), and the
duplicate-key message printed that encoding verbatim ("duplicate primary key:
1:11:1"). Render the key from the row instead: a composite key becomes a
parenthesized tuple such as (1,11) and a single-column key keeps its one
component. Text components are SQL literals with embedded quotes doubled so a
value containing the encoding separator, a comma, or a quote stays readable.

Every PrimaryKeyViolationError site now builds its message through
newPrimaryKeyViolation with the schema and normalized row it already has:
point insert, bulk insert, transaction insert (overlay and durable), and
cascaded key update. SQLSTATE 23505 is unchanged on both the PostgreSQL and
HTTP paths.
Danilo Fragoso 1 settimana fa
parent
commit
0f85b8ab1a

+ 12 - 0
pkg/executor/foreign_key_cascade_test.go

@@ -95,6 +95,18 @@ func TestForeignKeyUpdateCascade(t *testing.T) {
 	if res := execMust(t, e, "SELECT pa, pb FROM cchild WHERE id = 10"); res.Rows[0][0] != "y" || res.Rows[0][1] != int64(2) {
 		t.Fatalf("composite child after cascade = %v, want ('y', 2)", res.Rows)
 	}
+
+	// A cascaded key move onto an existing row reports the key components, not
+	// the durable length-prefixed encoding.
+	execMust(t, e, "INSERT INTO cparent (a, b) VALUES ('z', 3)")
+	_, err := execSQL(e, "UPDATE cparent SET a = 'z', b = 3 WHERE a = 'y' AND b = 2")
+	var duplicate *storage.PrimaryKeyViolationError
+	if !errors.As(err, &duplicate) {
+		t.Fatalf("colliding cascade error = %v, want PrimaryKeyViolationError", err)
+	}
+	if got, want := err.Error(), "duplicate primary key: ('z',3)"; got != want {
+		t.Fatalf("colliding cascade message = %q, want %q", got, want)
+	}
 }
 
 // SET NULL clears the child columns on delete and on a key update, and a NOT

+ 27 - 0
pkg/httpserver/sqlstate_test.go

@@ -47,6 +47,33 @@ func TestHTTPUniqueViolationReturns23505(t *testing.T) {
 	}
 }
 
+// A duplicate composite key over HTTP keeps SQLSTATE 23505 and reports the key
+// components instead of the length-prefixed durable encoding.
+func TestHTTPCompositePrimaryKeyViolationReportsComponents(t *testing.T) {
+	server := setupKVTestServer(t)
+	queryHTTP(t, server, "CREATE TABLE pairs (a INTEGER, b INTEGER, PRIMARY KEY (a, b))")
+	queryHTTP(t, server, "INSERT INTO pairs (a, b) VALUES (1, 11)")
+
+	body, _ := json.Marshal(QueryRequest{SQL: "INSERT INTO pairs (a, b) VALUES (1, 11)"})
+	r := httptest.NewRequest(http.MethodPost, "/query", strings.NewReader(string(body)))
+	w := httptest.NewRecorder()
+	server.handleQuery(w, r)
+
+	if w.Code != http.StatusConflict {
+		t.Fatalf("status = %d, want 409; body %s", w.Code, w.Body.String())
+	}
+	var resp httpErrorBody
+	if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+		t.Fatalf("decode: %v", err)
+	}
+	if resp.Error.Code != "23505" {
+		t.Fatalf("code = %q, want 23505", resp.Error.Code)
+	}
+	if want := "duplicate primary key: (1,11)"; resp.Error.Message != want {
+		t.Fatalf("message = %q, want %q", resp.Error.Message, want)
+	}
+}
+
 // A constraint the commit discovers must report its SQLSTATE instead of the
 // generic TRANSACTION_ERROR the transaction endpoints use for other failures.
 func TestHTTPCommitCheckViolationReturns23514(t *testing.T) {

+ 17 - 3
pkg/pgserver/composite_primary_key_test.go

@@ -20,14 +20,28 @@ func TestCompositePrimaryKeyWireBehavior(t *testing.T) {
 	if msgs := query("INSERT INTO pairs (a, b, v) VALUES ('x', 'y', 'one')"); errorCode(msgs[0]) != "" {
 		t.Fatalf("INSERT failed: %s", errorMessage(msgs[0]))
 	}
-	if code := errorCode(query("INSERT INTO pairs (a, b, v) VALUES ('x', 'y', 'two')")[0]); code != ErrCodeUniqueViolation {
-		t.Fatalf("duplicate composite key SQLSTATE = %q, want 23505", code)
+	if msgs := query("INSERT INTO pairs (a, b, v) VALUES ('x', 'y', 'two')"); errorCode(msgs[0]) != ErrCodeUniqueViolation {
+		t.Fatalf("duplicate composite key SQLSTATE = %q, want 23505", errorCode(msgs[0]))
+	} else if got, want := errorMessage(msgs[0]), "Execution error: duplicate primary key: ('x','y')"; got != want {
+		t.Fatalf("duplicate composite key message = %q, want %q", got, want)
+	}
+
+	// A numeric composite key renders as a tuple, not the length-prefixed
+	// durable encoding.
+	if msgs := query("CREATE TABLE numbered (a INTEGER, b INTEGER, PRIMARY KEY (a, b))"); errorCode(msgs[0]) != "" {
+		t.Fatalf("CREATE TABLE numbered failed: %s", errorMessage(msgs[0]))
+	}
+	query("INSERT INTO numbered (a, b) VALUES (1, 11)")
+	if msgs := query("INSERT INTO numbered (a, b) VALUES (1, 11)"); errorCode(msgs[0]) != ErrCodeUniqueViolation {
+		t.Fatalf("duplicate numeric composite key SQLSTATE = %q, want 23505", errorCode(msgs[0]))
+	} else if got, want := errorMessage(msgs[0]), "Execution error: duplicate primary key: (1,11)"; got != want {
+		t.Fatalf("duplicate numeric composite key message = %q, want %q", got, want)
 	}
 	if code := errorCode(query("INSERT INTO pairs (a, v) VALUES ('x', 'missing b')")[0]); code != "23502" {
 		t.Fatalf("missing key component SQLSTATE = %q, want 23502", code)
 	}
 
-	// Only the accepted row survived the two rejected inserts.
+	// Only the accepted row survived the rejected inserts.
 	selectRows := query("SELECT v FROM pairs WHERE a = 'x' AND b = 'y'")
 	var dataRows []*Message
 	for _, msg := range selectRows {

+ 69 - 0
pkg/storage/composite_key_test.go

@@ -118,6 +118,75 @@ func TestCompositePrimaryKeyInsertErrors(t *testing.T) {
 	}
 }
 
+// A duplicate composite key reports its components in declaration order, not the
+// length-prefixed durable encoding, and a component that itself contains the
+// encoding separator or a quote keeps its own tuple position.
+func TestCompositePrimaryKeyViolationMessage(t *testing.T) {
+	_, _, schemas, tables := newTestSession(t)
+	compositeTestTable(t, schemas)
+
+	cases := []struct {
+		row  Row
+		want string
+	}{
+		{Row{"a": "x", "b": "y"}, "duplicate primary key: ('x','y')"},
+		{Row{"a": "a:b", "b": "c"}, "duplicate primary key: ('a:b','c')"},
+		{Row{"a": "a,b", "b": "it's"}, "duplicate primary key: ('a,b','it''s')"},
+	}
+	for _, tc := range cases {
+		if err := tables.Insert("t", tc.row); err != nil {
+			t.Fatalf("insert %v: %v", tc.row, err)
+		}
+		err := tables.Insert("t", tc.row)
+		var duplicate *PrimaryKeyViolationError
+		if !errors.As(err, &duplicate) {
+			t.Fatalf("duplicate insert %v error = %v, want PrimaryKeyViolationError", tc.row, err)
+		}
+		if got := err.Error(); got != tc.want {
+			t.Fatalf("duplicate insert %v message = %q, want %q", tc.row, got, tc.want)
+		}
+	}
+}
+
+// The transaction paths report the same rendering for a key staged in the
+// overlay and for one already durable outside the transaction.
+func TestSessionCompositePrimaryKeyViolationMessage(t *testing.T) {
+	_, _, schemas, tables := newTestSession(t)
+	compositeTestTable(t, schemas)
+
+	if err := tables.Insert("t", Row{"a": "durable", "b": "x:y"}); err != nil {
+		t.Fatalf("insert durable: %v", err)
+	}
+
+	s := NewSession(schemas, tables)
+	if err := s.Begin(); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.Insert("t", Row{"a": "staged", "b": "y,z"}); err != nil {
+		t.Fatalf("insert staged: %v", err)
+	}
+
+	for _, tc := range []struct {
+		row  Row
+		want string
+	}{
+		{Row{"a": "staged", "b": "y,z"}, "duplicate primary key: ('staged','y,z')"},
+		{Row{"a": "durable", "b": "x:y"}, "duplicate primary key: ('durable','x:y')"},
+	} {
+		err := s.Insert("t", tc.row)
+		var duplicate *PrimaryKeyViolationError
+		if !errors.As(err, &duplicate) {
+			t.Fatalf("transaction duplicate %v error = %v, want PrimaryKeyViolationError", tc.row, err)
+		}
+		if got := err.Error(); got != tc.want {
+			t.Fatalf("transaction duplicate %v message = %q, want %q", tc.row, got, tc.want)
+		}
+	}
+	if err := s.Rollback(); err != nil {
+		t.Fatalf("rollback: %v", err)
+	}
+}
+
 func TestCompositePrimaryKeyUpdateAndDelete(t *testing.T) {
 	_, _, schemas, tables := newTestSession(t)
 	compositeTestTable(t, schemas)

+ 41 - 1
pkg/storage/constraints.go

@@ -10,13 +10,53 @@ import (
 // executor errors so wire adapters can report integrity SQLSTATE 23505.
 type PrimaryKeyViolationError struct {
 	Table string
-	Key   string
+	// Key is the primary key rendered for a reader, never the durable
+	// length-prefixed encoding.
+	Key string
 }
 
 func (e *PrimaryKeyViolationError) Error() string {
 	return fmt.Sprintf("duplicate primary key: %s", e.Key)
 }
 
+// newPrimaryKeyViolation reports the duplicate key its write collided with. The
+// message renders the key from the row instead of the durable key: a composite
+// key is stored length-prefixed ("<len>:<value>" repeated), so splitting that
+// encoding to label the violation would corrupt any component that itself
+// contains the separator.
+func newPrimaryKeyViolation(table string, schema *Schema, row Row) *PrimaryKeyViolationError {
+	return &PrimaryKeyViolationError{Table: table, Key: primaryKeyLabel(schema, row)}
+}
+
+// primaryKeyLabel renders a row's primary-key components for a reader: a
+// single-column key is that one component and a composite key is a parenthesized
+// tuple such as (1,11). A text component is rendered as a SQL literal with
+// embedded quotes doubled, so a value containing a comma or a quote stays
+// distinguishable from the tuple syntax.
+func primaryKeyLabel(schema *Schema, row Row) string {
+	columns := schema.PrimaryKeyList()
+	parts := make([]string, len(columns))
+	for i, column := range columns {
+		value, _ := rowColumnValue(row, column)
+		parts[i] = primaryKeyComponent(value)
+	}
+	if len(parts) == 1 {
+		return parts[0]
+	}
+	return "(" + strings.Join(parts, ",") + ")"
+}
+
+func primaryKeyComponent(value interface{}) string {
+	switch v := value.(type) {
+	case string:
+		return "'" + strings.ReplaceAll(v, "'", "''") + "'"
+	case []byte:
+		return "'" + strings.ReplaceAll(string(v), "'", "''") + "'"
+	default:
+		return fmt.Sprintf("%v", v)
+	}
+}
+
 // NotNullViolationError identifies the final row that violates a required column.
 type NotNullViolationError struct {
 	Table  string

+ 1 - 1
pkg/storage/foreign_key_cascade.go

@@ -391,7 +391,7 @@ func (s *Session) stageCascadeUpdate(table string, oldRow, newRow Row, exp *casc
 	newKey := s.table.dataKey(table, newPK)
 	if oldKey != newKey {
 		if _, gerr := s.getByPKLocked(table, newPK); gerr == nil {
-			return &PrimaryKeyViolationError{Table: table, Key: newPK}
+			return newPrimaryKeyViolation(table, schema, newRow)
 		} else if gerr != ErrKeyNotFound {
 			return gerr
 		}

+ 3 - 3
pkg/storage/table.go

@@ -736,7 +736,7 @@ func (m *TableManager) InsertWithRowID(table string, row Row) (int64, error) {
 		return 0, err
 	}
 	if !committed {
-		return 0, &PrimaryKeyViolationError{Table: table, Key: strings.TrimPrefix(key, m.dataPrefix(table))}
+		return 0, newPrimaryKeyViolation(table, schema, nr)
 	}
 
 	m.applyUniquePlan(uniquePlan, nil)
@@ -854,7 +854,7 @@ func (m *TableManager) InsertBulkWithLastRowID(table string, rows []Row) (int, i
 	for i, op := range ops {
 		key := string(op.Key)
 		if _, duplicate := seen[key]; duplicate {
-			return 0, 0, &PrimaryKeyViolationError{Table: table, Key: key}
+			return 0, 0, newPrimaryKeyViolation(table, schema, normalized[i])
 		}
 		seen[key] = struct{}{}
 		keys[i] = op.Key
@@ -878,7 +878,7 @@ func (m *TableManager) InsertBulkWithLastRowID(table string, rows []Row) (int, i
 	}
 	for i, found := range existing {
 		if found {
-			return 0, 0, &PrimaryKeyViolationError{Table: table, Key: string(ops[i].Key)}
+			return 0, 0, newPrimaryKeyViolation(table, schema, normalized[i])
 		}
 	}
 

+ 36 - 0
pkg/storage/table_test.go

@@ -1,6 +1,7 @@
 package storage
 
 import (
+	"errors"
 	"fmt"
 	"testing"
 	"time"
@@ -289,15 +290,50 @@ func TestInsertBulkStringPrimaryKeyCount(t *testing.T) {
 	}
 	if n, err := tables.InsertBulk("labels", []Row{{"id": "a", "value": "duplicate"}}); err == nil || n != 0 {
 		t.Fatalf("existing duplicate: n=%d err=%v", n, err)
+	} else if got, want := err.Error(), "duplicate primary key: 'a'"; got != want {
+		t.Fatalf("existing duplicate message = %q, want %q", got, want)
 	}
 	if n, err := tables.InsertBulk("labels", []Row{{"id": "c"}, {"id": "c"}}); err == nil || n != 0 {
 		t.Fatalf("batch duplicate: n=%d err=%v", n, err)
+	} else if got, want := err.Error(), "duplicate primary key: 'c'"; got != want {
+		t.Fatalf("batch duplicate message = %q, want %q", got, want)
 	}
 	if _, err := tables.GetByPK("labels", "c"); err == nil {
 		t.Fatal("duplicate batch persisted a row")
 	}
 }
 
+// A single-column key reports its value; a TEXT key containing the row-key
+// separator or a quote is rendered as a SQL literal.
+func TestSingleColumnPrimaryKeyViolationMessage(t *testing.T) {
+	_, _, schemas, tables := newTestSession(t)
+	createTestTable(t, schemas, "nums", []Column{{Name: "id", Type: "INTEGER", PrimaryKey: true}})
+	createTestTable(t, schemas, "texts", []Column{{Name: "id", Type: "TEXT", PrimaryKey: true}})
+
+	cases := []struct {
+		table string
+		value interface{}
+		want  string
+	}{
+		{"nums", int64(1), "duplicate primary key: 1"},
+		{"texts", "a:1", "duplicate primary key: 'a:1'"},
+		{"texts", "o'brien", "duplicate primary key: 'o''brien'"},
+	}
+	for _, tc := range cases {
+		if err := tables.Insert(tc.table, Row{"id": tc.value}); err != nil {
+			t.Fatalf("insert %s %v: %v", tc.table, tc.value, err)
+		}
+		err := tables.Insert(tc.table, Row{"id": tc.value})
+		var duplicate *PrimaryKeyViolationError
+		if !errors.As(err, &duplicate) {
+			t.Fatalf("duplicate insert %s %v error = %v, want PrimaryKeyViolationError", tc.table, tc.value, err)
+		}
+		if got := err.Error(); got != tc.want {
+			t.Fatalf("duplicate insert %s %v message = %q, want %q", tc.table, tc.value, got, tc.want)
+		}
+	}
+}
+
 func TestSelectByIndexUsesPointReadsAfterBuild(t *testing.T) {
 	kv := newTestKVServer(t)
 	defer kv.close()

+ 4 - 4
pkg/storage/tx.go

@@ -1205,20 +1205,20 @@ func (s *Session) insertLocked(table string, row Row) (int64, error) {
 	}
 	rowid, _ := rowIDFromRow(nr)
 	tl := strings.ToLower(table)
-	// prepareInsert returned the durable key; duplicate reporting shows the same
-	// encoded primary-key component the key carries.
+	// The durable key stays internal; the duplicate message renders the key
+	// components from the normalized row.
 	pk := strings.TrimPrefix(key, s.table.dataPrefix(table))
 
 	if e, ok := s.overlay[tl][key]; ok {
 		if !e.absent {
-			return 0, &PrimaryKeyViolationError{Table: table, Key: pk}
+			return 0, newPrimaryKeyViolation(table, schema, nr)
 		}
 	} else {
 		durableKey := s.durableDataKeyLocked(table, pk)
 		_, lsn, err := s.table.getKeyWithLSN(durableKey)
 		if err == nil {
 			s.reads[durableKey] = lsn
-			return 0, &PrimaryKeyViolationError{Table: table, Key: pk}
+			return 0, newPrimaryKeyViolation(table, schema, nr)
 		}
 		if err != nil && err != ErrKeyNotFound {
 			return 0, err