Skip to content

Commit

Permalink
Multi Table Delete Planner Support (#14855)
Browse files Browse the repository at this point in the history
Signed-off-by: Harshit Gangal <[email protected]>
  • Loading branch information
harshit-gangal authored Jan 3, 2024
1 parent 3331023 commit 0467851
Show file tree
Hide file tree
Showing 17 changed files with 920 additions and 83 deletions.
52 changes: 32 additions & 20 deletions changelog/19.0/19.0.0/summary.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@
- **[New Stats](#new-stats)**
- [Stream Consolidations](#stream-consolidations)
- [Build Version in `/debug/vars`](#build-version-in-debug-vars)
- **[VTGate](#vtgate)**
- **[Planned Reparent Shard](#planned-reparent-shard)**
- [`--tolerable-replication-lag` Sub-flag](#tolerable-repl-lag)
- **[Query Compatibility](#query-compatibility)**
- [Multi Table Delete Support](#multi-table-delete)
- [`SHOW VSCHEMA KEYSPACES` Query](#show-vschema-keyspaces)
- [`FOREIGN_KEY_CHECKS` is now a Vitess Aware Variable](#fk-checks-vitess-aware)
- **[Vttestserver](#vttestserver)**
- [`--vtcombo-bind-host` flag](#vtcombo-bind-host)
- **[Query Compatibility](#query-compatibility)**
- [`SHOW VSCHEMA KEYSPACES` Query](#show-vschema-keyspaces)
- **[Planned Reparent Shard](#planned-reparent-shard)**
- [`--tolerable-replication-lag` Sub-flag](#tolerable-repl-lag)
- **[Minor Changes](#minor-changes)**
- **[Apply VSchema](#apply-vschema)**
- [`--strict` sub-flag and `strict` gRPC field](#strict-flag-and-field)
- **[Apply VSchema](#apply-vschema)**
- [`--strict` sub-flag and `strict` gRPC field](#strict-flag-and-field)

## <a id="major-changes"/>Major Changes

Expand All @@ -32,6 +32,7 @@ upgrading to v19.

Vitess will however, continue to support importing from MySQL 5.7 into Vitess even in v19.


### <a id="deprecations-and-deletions"/>Deprecations and Deletions

- The `MYSQL_FLAVOR` environment variable is now removed from all Docker Images.
Expand All @@ -42,6 +43,7 @@ Vitess will however, continue to support importing from MySQL 5.7 into Vitess ev
`--vreplication_healthcheck_topology_refresh`, `--vreplication_healthcheck_retry_delay`, and `--vreplication_healthcheck_timeout`.
- The `--vreplication_tablet_type` flag is now deprecated and ignored.


### <a id="docker"/>Docker

#### <a id="mysql-image"/>New MySQL Image
Expand All @@ -51,7 +53,8 @@ This lightweight image is a replacement of `vitess/lite` to only run `mysqld`.

Several tags are available to let you choose what version of MySQL you want to use: `vitess/mysql:8.0.30`, `vitess/mysql:8.0.34`.

### <a id="new-stats"/>new stats

### <a id="new-stats"/>New Stats

#### <a id="stream-consolidations"/>Stream Consolidations

Expand All @@ -61,27 +64,34 @@ Prior to 19.0 VTTablet reported how much time non-streaming executions spend wai

The build version (e.g., `19.0.0-SNAPSHOT`) has been added to `/debug/vars`, allowing users to programmatically inspect Vitess components' build version at runtime.

### <a id="vtgate"/>VTGate

#### <a id="fk-checks-vitess-aware"/>`FOREIGN_KEY_CHECKS` is now a Vitess Aware Variable
### <a id="planned-reparent-shard"/>Planned Reparent Shard

When VTGate receives a query to change the `FOREIGN_KEY_CHECKS` value for a session, instead of sending the value down to MySQL, VTGate now keeps track of the value and changes the queries by adding `SET_VAR(FOREIGN_KEY_CHECKS=On/Off)` style query optimizer hints wherever required.
#### <a id="tolerable-repl-lag"/>`--tolerable-replication-lag` Sub-flag

### <a id="vttestserver"/>Vttestserver
A new sub-flag `--tolerable-replication-lag` has been added to the command `PlannedReparentShard` that allows users to specify the amount of replication lag that is considered acceptable for a tablet to be eligible for promotion when Vitess makes the choice of a new primary.
This feature is opt-in and not specifying this sub-flag makes Vitess ignore the replication lag entirely.

#### <a id="vtcombo-bind-host"/>`--vtcombo-bind-host` flag
A new flag in VTOrc with the same name has been added to control the behaviour of the PlannedReparentShard calls that VTOrc issues.

A new flag `--vtcombo-bind-host` has been added to vttestserver that allows the users to configure the bind host that vtcombo uses. This is especially useful when running vttestserver as a docker image and you want to run vtctld commands and look at the vtcombo `/debug/status` dashboard.

### <a id="query-compatibility"/>Query Compatibility

#### <a id="multi-table-delete"/> Multi Table Delete Support

Support is added for sharded multi-table delete with target on single table using multiple table join.

Example: `Delete t1 from t1 join t2 on t1.id = t2.id join t3 on t1.col = t3.col where t3.foo = 5 and t2.bar = 7`

More details about how it works is available in [MySQL Docs](https://dev.mysql.com/doc/refman/8.0/en/delete.html)

#### <a id="show-vschema-keyspaces"/>`SHOW VSCHEMA KEYSPACES` Query

A SQL query, `SHOW VSCHEMA KEYSPACES` is now supported in Vitess. This query prints the vschema information
for all the keyspaces. It is useful for seeing the foreign key mode, whether the keyspace is sharded, and if there is an
error in the VSchema for the keyspace.

An example output of the query looks like -
An example output of the query looks like -
```sql
mysql> show vschema keyspaces;
+----------+---------+-------------+---------+
Expand All @@ -93,14 +103,16 @@ mysql> show vschema keyspaces;
2 rows in set (0.01 sec)
```

### <a id="planned-reparent-shard"/>Planned Reparent Shard
#### <a id="fk-checks-vitess-aware"/>`FOREIGN_KEY_CHECKS` is now a Vitess Aware Variable

#### <a id="tolerable-repl-lag"/>`--tolerable-replication-lag` Sub-flag
When VTGate receives a query to change the `FOREIGN_KEY_CHECKS` value for a session, instead of sending the value down to MySQL, VTGate now keeps track of the value and changes the queries by adding `SET_VAR(FOREIGN_KEY_CHECKS=On/Off)` style query optimizer hints wherever required.

A new sub-flag `--tolerable-replication-lag` has been added to the command `PlannedReparentShard` that allows users to specify the amount of replication lag that is considered acceptable for a tablet to be eligible for promotion when Vitess makes the choice of a new primary.
This feature is opt-in and not specifying this sub-flag makes Vitess ignore the replication lag entirely.
### <a id="vttestserver"/>Vttestserver

#### <a id="vtcombo-bind-host"/>`--vtcombo-bind-host` flag

A new flag `--vtcombo-bind-host` has been added to vttestserver that allows the users to configure the bind host that vtcombo uses. This is especially useful when running vttestserver as a docker image and you want to run vtctld commands and look at the vtcombo `/debug/status` dashboard.

A new flag in VTOrc with the same name has been added to control the behaviour of the PlannedReparentShard calls that VTOrc issues.

## <a id="minor-changes"/>Minor Changes

Expand Down
39 changes: 39 additions & 0 deletions go/test/endtoend/vtgate/queries/dml/dml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"testing"

"github.com/stretchr/testify/assert"

"vitess.io/vitess/go/test/endtoend/utils"
)

func TestMultiEqual(t *testing.T) {
Expand All @@ -39,3 +41,40 @@ func TestMultiEqual(t *testing.T) {
qr = mcmp.Exec("delete from user_tbl where (id, region_id) in ((1,1), (2,4))")
assert.EqualValues(t, 1, qr.RowsAffected)
}

// TestMultiTableDelete executed multi-table delete queries
func TestMultiTableDelete(t *testing.T) {
utils.SkipIfBinaryIsBelowVersion(t, 19, "vtgate")

mcmp, closer := start(t)
defer closer()

// initial rows
mcmp.Exec("insert into order_tbl(region_id, oid, cust_no) values (1,1,4), (1,2,2), (2,3,5), (2,4,55)")
mcmp.Exec("insert into oevent_tbl(oid, ename) values (1,'a'), (2,'b'), (3,'a'), (4,'c')")

// check rows
mcmp.AssertMatches(`select region_id, oid, cust_no from order_tbl order by oid`,
`[[INT64(1) INT64(1) INT64(4)] [INT64(1) INT64(2) INT64(2)] [INT64(2) INT64(3) INT64(5)] [INT64(2) INT64(4) INT64(55)]]`)
mcmp.AssertMatches(`select oid, ename from oevent_tbl order by oid`,
`[[INT64(1) VARCHAR("a")] [INT64(2) VARCHAR("b")] [INT64(3) VARCHAR("a")] [INT64(4) VARCHAR("c")]]`)

// multi table delete
qr := mcmp.Exec(`delete o from order_tbl o join oevent_tbl ev where o.oid = ev.oid and ev.ename = 'a'`)
assert.EqualValues(t, 2, qr.RowsAffected)

// check rows
mcmp.AssertMatches(`select region_id, oid, cust_no from order_tbl order by oid`,
`[[INT64(1) INT64(2) INT64(2)] [INT64(2) INT64(4) INT64(55)]]`)
mcmp.AssertMatches(`select oid, ename from oevent_tbl order by oid`,
`[[INT64(1) VARCHAR("a")] [INT64(2) VARCHAR("b")] [INT64(3) VARCHAR("a")] [INT64(4) VARCHAR("c")]]`)

qr = mcmp.Exec(`delete o from order_tbl o join oevent_tbl ev where o.cust_no = ev.oid`)
assert.EqualValues(t, 1, qr.RowsAffected)

// check rows
mcmp.AssertMatches(`select region_id, oid, cust_no from order_tbl order by oid`,
`[[INT64(2) INT64(4) INT64(55)]]`)
mcmp.AssertMatches(`select oid, ename from oevent_tbl order by oid`,
`[[INT64(1) VARCHAR("a")] [INT64(2) VARCHAR("b")] [INT64(3) VARCHAR("a")] [INT64(4) VARCHAR("c")]]`)
}
8 changes: 8 additions & 0 deletions go/vt/sqlparser/ast_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2551,3 +2551,11 @@ func (node *Delete) isSingleAliasExpr() bool {
_, isAliasExpr := node.TableExprs[0].(*AliasedTableExpr)
return isAliasExpr
}

func (node TableExprs) MultiTable() bool {
if len(node) > 1 {
return true
}
_, singleTbl := node[0].(*AliasedTableExpr)
return !singleTbl
}
18 changes: 18 additions & 0 deletions go/vt/vtgate/engine/cached_size.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

94 changes: 94 additions & 0 deletions go/vt/vtgate/engine/delete_multi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
Copyright 2023 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package engine

import (
"context"

topodatapb "vitess.io/vitess/go/vt/proto/topodata"
"vitess.io/vitess/go/vt/vterrors"

"vitess.io/vitess/go/sqltypes"
querypb "vitess.io/vitess/go/vt/proto/query"
)

var _ Primitive = (*DeleteMulti)(nil)

const DM_VALS = "dm_vals"

// DeleteMulti represents the instructions to perform a delete.
type DeleteMulti struct {
Delete Primitive
Input Primitive

txNeeded
}

func (del *DeleteMulti) RouteType() string {
return "DELETEMULTI"
}

func (del *DeleteMulti) GetKeyspaceName() string {
return del.Input.GetKeyspaceName()
}

func (del *DeleteMulti) GetTableName() string {
return del.Input.GetTableName()
}

func (del *DeleteMulti) Inputs() ([]Primitive, []map[string]any) {
return []Primitive{del.Input, del.Delete}, nil
}

// TryExecute performs a non-streaming exec.
func (del *DeleteMulti) TryExecute(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable, _ bool) (*sqltypes.Result, error) {
inputRes, err := vcursor.ExecutePrimitive(ctx, del.Input, bindVars, false)
if err != nil {
return nil, err
}

bv := &querypb.BindVariable{
Type: querypb.Type_TUPLE,
}
for _, row := range inputRes.Rows {
bv.Values = append(bv.Values, sqltypes.TupleToProto(row))
}
return vcursor.ExecutePrimitive(ctx, del.Delete, map[string]*querypb.BindVariable{
DM_VALS: bv,
}, false)
}

// TryStreamExecute performs a streaming exec.
func (del *DeleteMulti) TryStreamExecute(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {
res, err := del.TryExecute(ctx, vcursor, bindVars, wantfields)
if err != nil {
return err
}
return callback(res)
}

// GetFields fetches the field info.
func (del *DeleteMulti) GetFields(context.Context, VCursor, map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
return nil, vterrors.VT13001("unreachable code for MULTI DELETE")
}

func (del *DeleteMulti) description() PrimitiveDescription {
return PrimitiveDescription{
OperatorType: "DeleteMulti",
TargetTabletType: topodatapb.TabletType_PRIMARY,
}
}
70 changes: 70 additions & 0 deletions go/vt/vtgate/engine/delete_multi_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
Copyright 2023 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package engine

import (
"context"
"testing"

"github.com/stretchr/testify/require"

"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/vt/vtgate/vindexes"
)

func TestDeleteMulti(t *testing.T) {
input := &fakePrimitive{results: []*sqltypes.Result{
sqltypes.MakeTestResult(sqltypes.MakeTestFields("id", "int64"), "1", "2", "3"),
}}

del := &DeleteMulti{
Input: input,
Delete: &Delete{
DML: &DML{
RoutingParameters: &RoutingParameters{
Opcode: Scatter,
Keyspace: &vindexes.Keyspace{
Name: "ks",
Sharded: true,
},
},
Query: "dummy_delete",
},
},
}

vc := newDMLTestVCursor("-20", "20-")
_, err := del.TryExecute(context.Background(), vc, nil, false)
require.NoError(t, err)
vc.ExpectLog(t, []string{
`ResolveDestinations ks [] Destinations:DestinationAllShards()`,
`ExecuteMultiShard ` +
`ks.-20: dummy_delete {dm_vals: type:TUPLE values:{type:TUPLE value:"\x89\x02\x011"} values:{type:TUPLE value:"\x89\x02\x012"} values:{type:TUPLE value:"\x89\x02\x013"}} ` +
`ks.20-: dummy_delete {dm_vals: type:TUPLE values:{type:TUPLE value:"\x89\x02\x011"} values:{type:TUPLE value:"\x89\x02\x012"} values:{type:TUPLE value:"\x89\x02\x013"}} true false`,
})

vc.Rewind()
input.rewind()
err = del.TryStreamExecute(context.Background(), vc, nil, false, func(result *sqltypes.Result) error { return nil })
require.NoError(t, err)
vc.ExpectLog(t, []string{
`ResolveDestinations ks [] Destinations:DestinationAllShards()`,
`ExecuteMultiShard ` +
`ks.-20: dummy_delete {dm_vals: type:TUPLE values:{type:TUPLE value:"\x89\x02\x011"} values:{type:TUPLE value:"\x89\x02\x012"} values:{type:TUPLE value:"\x89\x02\x013"}} ` +
`ks.20-: dummy_delete {dm_vals: type:TUPLE values:{type:TUPLE value:"\x89\x02\x011"} values:{type:TUPLE value:"\x89\x02\x012"} values:{type:TUPLE value:"\x89\x02\x013"}} true false`,
})
}
Loading

0 comments on commit 0467851

Please sign in to comment.