Skip to content

Commit

Permalink
parser: check invalid column define option for generated columns (pin…
Browse files Browse the repository at this point in the history
…gcap#201)

* parser: add check on column options

* add related tests

* add more tests

* fix ident problems

* fix bug

* Code refine according to reviewer's opinion
  • Loading branch information
spongedu authored and kennytm committed Apr 26, 2019
1 parent 4591c1c commit 9926c21
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
25 changes: 25 additions & 0 deletions ast/ddl.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,14 @@ const (
ColumnOptionCollate
)

var (
invalidOptionForGeneratedColumn = map[ColumnOptionType]struct{}{
ColumnOptionAutoIncrement: {},
ColumnOptionOnUpdate: {},
ColumnOptionDefaultValue: {},
}
)

// ColumnOption is used for parsing column constraint info from SQL.
type ColumnOption struct {
node
Expand Down Expand Up @@ -672,6 +680,23 @@ func (n *ColumnDef) Accept(v Visitor) (Node, bool) {
return v.Leave(n)
}

// Validate checks if a column definition is legal.
// For example, generated column definitions that contain such
// column options as `ON UPDATE`, `AUTO_INCREMENT`, `DEFAULT`
// are illegal.
func (n *ColumnDef) Validate() bool {
generatedCol := false
illegalOpt4gc := false
for _, opt := range n.Options {
if opt.Tp == ColumnOptionGenerated {
generatedCol = true
}
_, found := invalidOptionForGeneratedColumn[opt.Tp]
illegalOpt4gc = illegalOpt4gc || found
}
return !(generatedCol && illegalOpt4gc)
}

// CreateTableStmt is a statement to create a table.
// See https://dev.mysql.com/doc/refman/5.7/en/create-table.html
type CreateTableStmt struct {
Expand Down
7 changes: 6 additions & 1 deletion parser.go

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

7 changes: 6 additions & 1 deletion parser.y
Original file line number Diff line number Diff line change
Expand Up @@ -1550,7 +1550,12 @@ ColumnDefList:
ColumnDef:
ColumnName Type ColumnOptionListOpt
{
$$ = &ast.ColumnDef{Name: $1.(*ast.ColumnName), Tp: $2.(*types.FieldType), Options: $3.([]*ast.ColumnOption)}
colDef := &ast.ColumnDef{Name: $1.(*ast.ColumnName), Tp: $2.(*types.FieldType), Options: $3.([]*ast.ColumnOption)}
if !colDef.Validate() {
yylex.AppendError(yylex.Errorf("Invalid column definition"))
return 1
}
$$ = colDef
}

ColumnName:
Expand Down

0 comments on commit 9926c21

Please sign in to comment.