Repository navigation
vschema: Let a table declare its primary key - #50
Conversation
Add a repeated string primary_key field to vschema.Table, listing in order the columns that make up the table's primary key. It is regenerated with the pinned protoc 3.21.3 and the repo's pinned protoc-gen-go and vtprotobuf (Go outputs) and with pbjs/pbts (vtadmin web types). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Morgan Tocker <mtocker@squareup.com>
The planner plans a multi-shard DELETE or UPDATE with a LIMIT as DML with input: it selects the primary keys of the matching rows, then deletes or updates by primary key. That needs BaseTable.PrimaryKey, which today is only filled in by schema tracking. A deployment without schema tracking can already declare columns in the VSchema, but cannot declare a primary key, so these statements fail to plan with VT09015. Build BaseTable.PrimaryKey from the new primary_key field of the VSchema table. Empty names, duplicate names (case-insensitively) and, when column_list_authoritative is set, names missing from columns are rejected. The field is accepted for every table type, as columns are. When schema tracking knows the table, its primary key replaces the declared one rather than being appended to it. A tracked table without a primary key therefore ends up without one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Morgan Tocker <mtocker@squareup.com>
There was a problem hiding this comment.
🟡 Changes recommended
The sharded REPLACE rewrite can run without complete index metadata when schema tracking is disabled, causing secondary unique-key conflicts to fail instead of replacing the existing row.
1 open issue
2 files not reviewed
go/vt/proto/vschema/vschema.pb.go: Generated filego/vt/proto/vschema/vschema_vtproto.pb.go: Generated file
What changed in this PR
Adds declarative primary keys to VSchema so vtgate can plan multi-shard DELETE ... LIMIT and UPDATE ... LIMIT without schema tracking.
Changes:
- Adds an ordered
primary_keyfield and regenerates Go and vtadmin bindings. - Validates declared keys while preserving schema-tracker precedence.
- Adds builder, serialization, tracker-override, and planner regression tests.
| File | Description |
|---|---|
web/vtadmin/src/proto/vtadmin.js |
Adds generated primary-key serialization support. |
web/vtadmin/src/proto/vtadmin.d.ts |
Adds generated primary-key type declarations. |
proto/vschema.proto |
Defines the ordered primary-key field and precedence. |
go/vt/vtgate/vschema_manager.go |
Replaces declared keys with tracked metadata. |
go/vt/vtgate/vschema_manager_test.go |
Tests declared keys and tracker overrides. |
go/vt/vtgate/vindexes/vschema.go |
Validates and copies declared primary keys. |
go/vt/vtgate/vindexes/vschema_test.go |
Tests validation, ordering, and JSON round trips. |
go/vt/vtgate/planbuilder/testdata/vschemas/primary_key_schema.json |
Provides declarative-key planner fixtures. |
go/vt/vtgate/planbuilder/testdata/primary_key_cases.json |
Adds expected DML plans and missing-key errors. |
go/vt/vtgate/planbuilder/plan_test.go |
Registers the declarative primary-key planning tests. |
go/vt/proto/vschema/vschema.pb.go |
Adds the generated Go field and descriptor. |
go/vt/proto/vschema/vschema_vtproto.pb.go |
Adds generated cloning and wire-format support. |
Review effort: Balanced
A primary key declared in the VSchema says nothing about the table's other unique keys. The sharded REPLACE rewrite (DELETE by primary key and unique keys, then INSERT) needs the full set. With only a declared primary key it would miss a row that clashes on a secondary unique key, and the INSERT would fail after the DELETE had already run. Mark a primary key that comes only from the VSchema with BaseTable.PrimaryKeyDeclared. Schema tracking clears the mark when it supplies the table's indexes. The REPLACE rewrite now ignores a declared primary key, so a sharded REPLACE without tracked index metadata keeps returning VT12001, as it did before the field existed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Morgan Tocker <mtocker@squareup.com>
|
🤖 Review of 99628f9: 0 blocking, 5 non-blocking. Inspected the full diff (13 files) and the code around each change at the head: BlockingNone. The declared key only takes effect where schema tracking has no entry for the table, tracking replaces it cleanly, and the one planner path where a declared key is not equivalent to a tracked one (REPLACE) is gated off. Non-blocking
Verified
This review was generated by Claude Code (claude-sonnet-5-5). |
aparajon
left a comment
There was a problem hiding this comment.
🤖 Stamping with comments: 0 blocking, 5 non-blocking (see the review comment above).
This stamp was left by Claude Code (claude-sonnet-5-5).
State that the primary_key list must be exactly the table's primary key (or another unique key whose columns are NOT NULL in every row), that vtgate trusts it as unique, and that DML planned by key, such as a multi-shard DELETE or UPDATE with a LIMIT, relies on it for correctness. Note that field number 8 is used by this fork only, so an upstream sync must check it for a conflict. Only comments change. The generated Go code differs by the comment text, and the vtproto and vtadmin web outputs and the descriptor bytes are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Morgan Tocker <mtocker@squareup.com>
Replace BaseTable.PrimaryKeyDeclared with PrimaryKeyTracked, which is true only when schema tracking handled the table. The REPLACE rewrite in createOperatorFromInsert now requires it, so a code path that sets PrimaryKey without setting the flag fails closed: a sharded REPLACE keeps returning VT12001. The field is tagged json:"-", so the JSON rendering of BaseTable does not change. VSchemaManager.updateTableInfo sets the flag whenever tracking handled the table, including a table with no primary key. buildTables leaves it false, and the AddPrimaryKey test helper, which stands in for schema tracking, sets it. Update the tests to assert the new flag. TestDeclaredPrimaryKeyAndSchemaTracking no longer runs twice, since BuildVSchema builds fresh tables on every call, so a second pass cannot detect accumulation. The VSchema comparison tests ignore PrimaryKeyTracked, which they do not cover. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Morgan Tocker <mtocker@squareup.com>
Add planner cases that query the unsharded fixtures that declare a primary key and that have none. Declare a primary key on a reference table that has a source in TestVSchemaPrimaryKey. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Morgan Tocker <mtocker@squareup.com>
|
🤖 Thanks. Addressed in 99628f9..1fdb57f:
🤖 Addressed by Claude Code |
This reverts commit fd1e737 (#50). No user of this fork needs a declared primary key. The planner reads it only for two-phase DML (a multi-shard DELETE or UPDATE with LIMIT, and a multi-table DELETE or UPDATE). Those shapes stay unsupported without schema tracking. Signed-off-by: Morgan Tocker <mtocker@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Why
The planner plans a multi-shard
DELETE ... LIMIT norUPDATE ... LIMIT nas DML with input: it selects the primary keys of the matching rows, then deletes or updates by primary key.That needs
BaseTable.PrimaryKey, which is only filled in by vtgate's schema tracker today. When it is empty the planner returnsVT09015: schema tracking required.A deployment without schema tracking can already declare columns in the VSchema (
columns,column_list_authoritative), but it cannot declare a primary key, so these statements can never be planned there. This adds the declarative equivalent.What
proto/vschema.proto:Tablegetsrepeated string primary_key = 8, the ordered primary-key columns. The generated Go code is regenerated. The comment states that the list must be exactly the table's primary key (or another unique key whose columns are NOT NULL in every row), because vtgate trusts it as unique and DML planned by key, such as a multi-shardDELETE/UPDATEwithLIMIT, relies on it for correctness. The vtadmin web types are unchanged by the comment.Table. The proto comment says so.vindexes.BuildVSchemacopiesprimary_keyintoBaseTable.PrimaryKey. The same builder is used byApplyVSchemavalidation, so no other validation path needed a change.column_list_authoritativeis true every primary-key column must be incolumns. When the column list is not authoritative, primary-key columns are not checked against it.source), in the same waycolumnsis.BaseTable.PrimaryKeyTrackedrecords the provenance: it is true only when schema tracking handled the table. It is taggedjson:"-", so the JSON rendering ofBaseTabledoes not change.createOperatorFromInsertonly rewrites a sharded (or foreign-key)REPLACEinto delete-then-insert when index metadata came from schema tracking (PrimaryKeyTracked) or unique keys are known. A declared primary key says nothing about the table's other unique keys, so a shardedREPLACEwithout tracked index metadata keeps returningVT12001.How
The builder change is in
buildTables, next to the column handling. It leavesPrimaryKeyTrackedfalse. The tracker change inVSchemaManager.updateTableInforesetsPrimaryKeybefore it applies the tracked primary index, and setsPrimaryKeyTracked. Without the reset the declared columns and the tracked columns would be concatenated. TheAddPrimaryKeytest helper stands in for schema tracking, so it setsPrimaryKeyTrackedtoo.Risk
Low. The field is new and optional, so existing VSchemas build exactly as before. The behavior changes for existing deployments are in
updateTableInfo, wherePrimaryKeyis reset before the tracked primary key is applied (previously it was always empty at that point, because the VSchema builder never set it), and increateOperatorFromInsert, where theREPLACErewrite now requiresPrimaryKeyTracked(or known unique keys). Tracked tables are marked tracked, so theirREPLACEplanning is unchanged.A wrong or stale declared key can make a
LIMITstatement touch rows beyond the limit, because vtgate cannot validate the declaration against the database. Before this change such a table failed closed withVT09015. This is the same kind of trust the VSchema already places incolumn_vindexes, and it is documented on the proto field.Rollout: a binary built before this change ignores a declared
primary_keyas an unknown field, so planning behaves as it did before. A client built before this change that reads a VSchema withGetVSchemaand re-applies its JSON output dropsprimary_key, because unknown fields are discarded. New vtgates then plan withVT09015again, so this fails closed.Testing
vindexes: the field is copied in the declared order, including on a reference table with asource. Each validation error is covered, and the field round-trips through JSON ("primary_key": ["a", "b"]) and throughBuildKeyspace.vtgate:TestDeclaredPrimaryKeyAndSchemaTrackingcovers declared-only (not tracked), tracked-equal, tracked-overrides-declared and tracked-without-primary-key (tracked). It fails without the reset.planbuilder:primary_key_cases.jsonwith a dedicated test VSchema. ScatterDELETE ... LIMITandUPDATE ... LIMITon tables whose primary key (single and composite) comes only from the VSchema plan asDMLWithInput, and a table without a declared primary key still givesVT09015. A shardedREPLACEon a table with a declared key still givesVT12001. UnshardedDELETE/UPDATE ... LIMITon tables with and without a declared key are passed through.go build ./go/vt/vtgate/...,go vetandgofmton the touched packages are clean.go test ./go/vt/vtgate/vindexes/... ./go/vt/vtgate/planbuilder/... ./go/vt/vtgate/passes except as noted below.TestSelectDateTypesingo/vt/vtgatefails today because it depends on the current date (a month-end rollover), and the vtgate end-to-end packages need a local MySQL. Both are unrelated to this change.🤖 Generated with Claude Code