Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

planner: Support assign DEFAULT in ON DUPLICATE KEY UPDATE statement #13168

Merged
merged 19 commits into from
Nov 21, 2019
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions ddl/db_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2043,11 +2043,7 @@ func (s *testIntegrationSuite3) TestInsertIntoGeneratedColumnWithDefaultExpr(c *
tk.MustExec("create table t5 (a int default 10, b int as (a+1))")
tk.MustGetErrCode("insert into t5 values (20, default(a))", mysql.ErrBadGeneratedColumn)

tk.MustExec("drop table t1")
tk.MustExec("drop table t2")
tk.MustExec("drop table t3")
tk.MustExec("drop table t4")
tk.MustExec("drop table t5")
tk.MustExec("drop table t1, t2, t3, t4, t5")
}

func (s *testIntegrationSuite3) TestSqlFunctionsInGeneratedColumns(c *C) {
Expand Down
35 changes: 35 additions & 0 deletions executor/write_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,41 @@ func (s *testSuite4) TestInsertIgnoreOnDup(c *C) {
r.Check(testkit.Rows("1 1", "2 2"))
}

func (s *testSuite4) TestInsertOnDupUpdateDefault(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
// Assign `DEFAULT` in `INSERT ... ON DUPLICATE KEY UPDATE ...` statement
tk.MustExec("drop table if exists t1, t2;")
tk.MustExec("create table t1 (a int unique, b int default 20, c int default 30);")
tk.MustExec("insert into t1 values (1,default,default);")
tk.MustExec("insert into t1 values (1,default,default) on duplicate key update b=default;")
tk.MustQuery("select * from t1;").Check(testkit.Rows("1 20 30"))
tk.MustExec("insert into t1 values (1,default,default) on duplicate key update c=default, b=default;")
tk.MustQuery("select * from t1;").Check(testkit.Rows("1 20 30"))
tk.MustExec("insert into t1 values (1,default,default) on duplicate key update c=default, a=2")
tk.MustQuery("select * from t1;").Check(testkit.Rows("2 20 30"))
tk.MustExec("insert into t1 values (2,default,default) on duplicate key update c=default(b)")
tk.MustQuery("select * from t1;").Check(testkit.Rows("2 20 20"))
tk.MustExec("insert into t1 values (2,default,default) on duplicate key update a=default(b)+default(c)")
tk.MustQuery("select * from t1;").Check(testkit.Rows("50 20 20"))
// With generated columns
tk.MustExec("create table t2 (a int unique, b int generated always as (-a) virtual, c int generated always as (-a) stored);")
tk.MustExec("insert into t2 values (1,default,default);")
tk.MustExec("insert into t2 values (1,default,default) on duplicate key update a=2, b=default;")
tk.MustQuery("select * from t2").Check(testkit.Rows("2 -2 -2"))
tk.MustExec("insert into t2 values (2,default,default) on duplicate key update a=3, c=default;")
tk.MustQuery("select * from t2").Check(testkit.Rows("3 -3 -3"))
tk.MustExec("insert into t2 values (3,default,default) on duplicate key update c=default, b=default, a=4;")
tk.MustQuery("select * from t2").Check(testkit.Rows("4 -4 -4"))
tk.MustExec("insert into t2 values (10,default,default) on duplicate key update b=default, a=20, c=default;")
tk.MustQuery("select * from t2").Check(testkit.Rows("4 -4 -4", "10 -10 -10"))
tk.MustGetErrCode("insert into t2 values (4,default,default) on duplicate key update b=default(a);", mysql.ErrBadGeneratedColumn)
tk.MustGetErrCode("insert into t2 values (4,default,default) on duplicate key update a=default(b), b=default(b);", mysql.ErrBadGeneratedColumn)
tk.MustGetErrCode("insert into t2 values (4,default,default) on duplicate key update a=default(a), c=default(c);", mysql.ErrBadGeneratedColumn)
tk.MustGetErrCode("insert into t2 values (4,default,default) on duplicate key update a=default(a), c=default(a);", mysql.ErrBadGeneratedColumn)
tk.MustExec("drop table t1, t2")
}

func (s *testSuite4) TestReplace(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
Expand Down
7 changes: 4 additions & 3 deletions expression/expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -614,9 +614,10 @@ func ColumnInfos2ColumnsAndNames(ctx sessionctx.Context, dbName, tblName model.C
continue
}
names = append(names, &types.FieldName{
ColName: col.Name,
TblName: tblName,
DBName: dbName,
ColName: col.Name,
TblName: tblName,
DBName: dbName,
OrigTblName: tblName,
})
newCol := &Column{
RetType: &col.FieldType,
Expand Down
11 changes: 11 additions & 0 deletions planner/core/logical_plan_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -3101,6 +3101,17 @@ func (b *PlanBuilder) buildUpdateLists(
return newList, p, allAssignmentsAreConstant, nil
}

// extractDefaultExpr extract a `DefaultExpr` without any parameter from a `ExprNode`
// return it and if successful extract it
// Note the sql function `DEFAULT(a)` is not same with keyword `DEFAULT`
// Sql function `DEFAULT(a)` will return `false`
func extractDefaultExpr(node ast.ExprNode) (*ast.DefaultExpr, bool) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we only return one value, which is the expr? the second bool value can be derived by expr == nil

Copy link
Contributor Author

@Deardrops Deardrops Nov 15, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this way is easier to understand:

var isDefaultExpr bool
if expr, isDefaultExpr := extractDefaultExpr(assign.Expr); isDefaultExpr {
	expr.Name = assign.Column
}
...
if isDefaultExpr {
	...
}

vs

var expr ast.ExprNode
if expr = extractDefaultExpr(assign.Expr); expr != nil {
	expr.Name = assign.Column
}
...
if expr != nil {
	...
}

if expr, ok := node.(*ast.DefaultExpr); ok && expr.Name == nil {
return expr, true
}
return nil, false
}

func (b *PlanBuilder) buildDelete(ctx context.Context, delete *ast.DeleteStmt) (Plan, error) {
b.pushSelectOffset(0)
b.pushTableHints(delete.TableHints, typeDelete, 0)
Expand Down
59 changes: 32 additions & 27 deletions planner/core/planbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -1797,27 +1797,13 @@ func (b *PlanBuilder) buildInsert(ctx context.Context, insert *ast.InsertStmt) (

mockTablePlan.SetSchema(insertPlan.Schema4OnDuplicate)
mockTablePlan.names = insertPlan.names4OnDuplicate
columnByName := make(map[string]*table.Column, len(insertPlan.Table.Cols()))
for _, col := range insertPlan.Table.Cols() {
columnByName[col.Name.L] = col
}
onDupColSet, dupCols, dupColNames, err := insertPlan.validateOnDup(insert.OnDuplicate, columnByName, tableInfo)

onDupColSet, err := insertPlan.resolveOnDuplicate(insert.OnDuplicate, tableInfo, func(node ast.ExprNode) (expression.Expression, error) {
return b.rewriteInsertOnDuplicateUpdate(ctx, node, mockTablePlan, insertPlan)
})
if err != nil {
return nil, err
}
for i, assign := range insert.OnDuplicate {
// Construct the function which calculates the assign value of the column.
expr, err1 := b.rewriteInsertOnDuplicateUpdate(ctx, assign.Expr, mockTablePlan, insertPlan)
if err1 != nil {
return nil, err1
}

insertPlan.OnDuplicate = append(insertPlan.OnDuplicate, &expression.Assignment{
Col: dupCols[i],
ColName: dupColNames[i].ColName,
Expr: expr,
})
}

// Calculate generated columns.
mockTablePlan.schema = insertPlan.tableSchema
Expand All @@ -1831,29 +1817,48 @@ func (b *PlanBuilder) buildInsert(ctx context.Context, insert *ast.InsertStmt) (
return insertPlan, err
}

func (p *Insert) validateOnDup(onDup []*ast.Assignment, colMap map[string]*table.Column, tblInfo *model.TableInfo) (map[string]struct{}, []*expression.Column, types.NameSlice, error) {
func (p *Insert) resolveOnDuplicate(onDup []*ast.Assignment, tblInfo *model.TableInfo, yield func(ast.ExprNode) (expression.Expression, error)) (map[string]struct{}, error) {
onDupColSet := make(map[string]struct{}, len(onDup))
dupCols := make([]*expression.Column, 0, len(onDup))
dupColNames := make(types.NameSlice, 0, len(onDup))
colMap := make(map[string]*table.Column, len(p.Table.Cols()))
for _, col := range p.Table.Cols() {
colMap[col.Name.L] = col
}
for _, assign := range onDup {
// Check whether the column to be updated exists in the source table.
idx, err := expression.FindFieldName(p.tableColNames, assign.Column)
if err != nil {
return nil, nil, nil, err
return nil, err
} else if idx < 0 {
return nil, nil, nil, ErrUnknownColumn.GenWithStackByArgs(assign.Column.OrigColName(), "field list")
return nil, ErrUnknownColumn.GenWithStackByArgs(assign.Column.OrigColName(), "field list")
}

// Check whether the column to be updated is the generated column.
column := colMap[assign.Column.Name.L]
defaultExpr, isDefaultExpr := extractDefaultExpr(assign.Expr)
if isDefaultExpr {
defaultExpr.Name = assign.Column
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

defaultExpr := extractDefaultExpr(assign.Expr);
if defaultExpr != nil {
...
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wjhuang2016 Address comment, PTAL

}
if column.IsGenerated() {
return nil, nil, nil, ErrBadGeneratedColumn.GenWithStackByArgs(assign.Column.Name.O, tblInfo.Name.O)
if isDefaultExpr {
continue
}
return nil, ErrBadGeneratedColumn.GenWithStackByArgs(assign.Column.Name.O, tblInfo.Name.O)
}

onDupColSet[column.Name.L] = struct{}{}
dupCols = append(dupCols, p.tableSchema.Columns[idx])
dupColNames = append(dupColNames, p.tableColNames[idx])

expr, err := yield(assign.Expr)
if err != nil {
return nil, err
}

p.OnDuplicate = append(p.OnDuplicate, &expression.Assignment{
Col: p.tableSchema.Columns[idx],
ColName: p.tableColNames[idx].ColName,
Expr: expr,
})
}
return onDupColSet, dupCols, dupColNames, nil
return onDupColSet, nil
}

func (b *PlanBuilder) getAffectCols(insertStmt *ast.InsertStmt, insertPlan *Insert) (affectedValuesCols []*table.Column, err error) {
Expand Down