-
Notifications
You must be signed in to change notification settings - Fork 269
/
schema.go
62 lines (56 loc) · 1.75 KB
/
schema.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2020 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"github.com/pingcap/tidb/pkg/parser"
"github.com/pingcap/tidb/pkg/parser/ast"
)
const (
tableType = "BASE TABLE"
)
// createTableToSmithSchema converts a `CREATE TABLE` statement to a schema representation needed by go-sqlsmith.
// for one column in `columns`:
// - columns[0]: DB name
// - columns[1]: table name
// - columns[2]: table type (only use `BASE TABLE` now)
// - columns[3]: column name
// - columns[4]: column type
//
// for `indexes`:
// - list of index name
func createTableToSmithSchema(dbName, sql string) (columns [][5]string, indexes []string, err error) {
parser2 := parser.New() // we should have clear `SQL_MODE.
stmt, err := parser2.ParseOneStmt(sql, "", "")
if err != nil {
return nil, nil, err
}
createStmt := stmt.(*ast.CreateTableStmt)
for _, col := range createStmt.Cols {
columns = append(columns, [5]string{
dbName,
createStmt.Table.Name.O,
tableType,
col.Name.Name.O,
col.Tp.String(),
})
}
for _, cons := range createStmt.Constraints {
switch cons.Tp {
case ast.ConstraintPrimaryKey, ast.ConstraintKey, ast.ConstraintIndex, ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:
indexes = append(indexes, cons.Name)
default:
continue
}
}
return
}