-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
table.go
306 lines (269 loc) · 7.67 KB
/
table.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package rawsql
import (
"database/sql"
"fmt"
"reflect"
"strings"
"time"
"github.com/pingcap/tidb/pkg/parser"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/parser/test_driver"
"github.com/pingcap/tidb/pkg/parser/types"
"gorm.io/gorm"
"gorm.io/gorm/migrator"
)
type Table struct {
ColumnTypes []gorm.ColumnType
Indexes []gorm.Index
Name string
Comment string
}
type Parser interface {
ParseSQL(sql string) error
GetTables() map[string]*Table
}
type defaultParser struct {
tables map[string]*Table
}
func newDefaultParse() Parser {
return &defaultParser{tables: make(map[string]*Table)}
}
func (d *defaultParser) GetTables() map[string]*Table {
return d.tables
}
func (d *defaultParser) ParseSQL(sql string) error {
p := parser.New()
stmtNodes, _, err := p.Parse(sql, "", "")
if err != nil {
return err
}
for _, node := range stmtNodes {
switch node.(type) {
case *ast.CreateTableStmt:
create := node.(*ast.CreateTableStmt)
tableName := create.Table.Name.String()
if _, has := d.tables[tableName]; has {
panic(fmt.Sprintf("duplicated table %s", tableName))
}
d.tables[tableName] = &Table{
Name: tableName,
Comment: getTableComment(create),
ColumnTypes: d.getColumnTypes(create),
Indexes: d.getIndexes(create),
}
case *ast.AlterTableStmt:
alter := node.(*ast.AlterTableStmt)
tableName := alter.Table.Name.String()
table, has := d.tables[tableName]
if !has {
panic(fmt.Sprintf("table %s not exists", tableName))
}
for _, spec := range alter.Specs {
if spec.OldColumnName != nil {
cols := table.ColumnTypes
for i, v := range cols {
if v.Name() == spec.OldColumnName.Name.String() {
table.ColumnTypes = append(cols[:i], cols[i+1:]...)
}
}
}
for _, v := range spec.NewColumns {
ct := d.getColumnType(v)
for i, existColumn := range table.ColumnTypes {
if existColumn.Name() == v.Name.String() {
// remove duplicate column
table.ColumnTypes = append(
table.ColumnTypes[:i],
table.ColumnTypes[i+1:]...,
)
break
}
}
position := -1
if spec.Position != nil {
switch spec.Position.Tp {
case ast.ColumnPositionFirst:
position = 0
case ast.ColumnPositionAfter:
for i, existColumn := range table.ColumnTypes {
if existColumn.Name() == spec.Position.RelativeColumn.Name.String() {
position = i + 1
}
}
}
}
if position > 0 {
table.ColumnTypes = append(
table.ColumnTypes[:position],
append(
[]gorm.ColumnType{ct}, table.ColumnTypes[position:]...,
)...,
)
} else {
table.ColumnTypes = append(table.ColumnTypes, ct)
}
}
}
case *ast.DropTableStmt:
drop := node.(*ast.DropTableStmt)
for _, table := range drop.Tables {
if _, has := d.tables[table.Name.String()]; !has && !drop.IfExists {
panic(fmt.Sprintf("table %s not exists", table.Name.String()))
}
delete(d.tables, table.Name.String())
}
}
}
return nil
}
func getTableComment(create *ast.CreateTableStmt) string {
if create == nil {
return ""
}
if create.Table.TableInfo != nil && create.Table.TableInfo.Comment != "" {
return create.Table.TableInfo.Comment
}
for _, tp := range create.Options {
if tp.Tp == ast.TableOptionComment {
return tp.StrValue
}
}
return ""
}
func (d *defaultParser) getColumnTypes(create *ast.CreateTableStmt) (cols []gorm.ColumnType) {
if create == nil || len(create.Cols) == 0 {
return nil
}
var primaryConstraint *ast.Constraint
for _, constraint := range create.Constraints {
if constraint.Tp == ast.ConstraintPrimaryKey {
primaryConstraint = constraint
}
}
cols = make([]gorm.ColumnType, 0, len(create.Cols))
for _, col := range create.Cols {
ct := d.getColumnType(col)
if primaryConstraint != nil {
for _, pk := range primaryConstraint.Keys {
if pk.Column.Name.String() == ct.Name() {
ct.(*migrator.ColumnType).PrimaryKeyValue = sql.NullBool{
Bool: true,
Valid: true,
}
}
}
}
cols = append(cols, ct)
}
return cols
}
func (*defaultParser) getColumnType(col *ast.ColumnDef) gorm.ColumnType {
ct := &migrator.ColumnType{
NameValue: sql.NullString{Valid: true, String: col.Name.OrigColName()},
DataTypeValue: sql.NullString{
Valid: true,
String: strings.ToLower(types.TypeToStr(col.Tp.GetType(), col.Tp.GetCharset())),
},
ColumnTypeValue: sql.NullString{Valid: true, String: strings.ToLower(col.Tp.String())},
PrimaryKeyValue: sql.NullBool{
Bool: mysql.HasPriKeyFlag(col.Tp.GetFlag()),
Valid: mysql.HasPriKeyFlag(col.Tp.GetFlag()),
},
UniqueValue: sql.NullBool{
Bool: mysql.HasUniKeyFlag(col.Tp.GetFlag()),
Valid: mysql.HasUniKeyFlag(col.Tp.GetFlag()),
},
LengthValue: sql.NullInt64{Int64: int64(col.Tp.GetFlen()), Valid: col.Tp.IsVarLengthType()},
DecimalSizeValue: sql.NullInt64{Int64: int64(col.Tp.GetFlen()), Valid: col.Tp.IsDecimalValid()},
ScaleValue: sql.NullInt64{Int64: int64(col.Tp.GetDecimal()), Valid: col.Tp.IsDecimalValid()},
NullableValue: sql.NullBool{Bool: true, Valid: true},
SQLColumnType: &sql.ColumnType{},
ScanTypeValue: getType(col.Tp),
}
for _, opt := range col.Options {
if opt.Tp == ast.ColumnOptionNotNull {
ct.NullableValue.Bool = false
continue
}
if opt.Tp == ast.ColumnOptionComment {
ct.CommentValue = sql.NullString{
String: opt.Expr.(*test_driver.ValueExpr).Datum.GetString(),
Valid: true,
}
continue
}
if opt.Tp == ast.ColumnOptionAutoIncrement {
ct.AutoIncrementValue = sql.NullBool{Bool: true, Valid: true}
continue
}
if opt.Tp == ast.ColumnOptionDefaultValue {
if v, ok := opt.Expr.(*test_driver.ValueExpr); ok {
ct.DefaultValueValue = sql.NullString{
Valid: v.Datum.GetValue() != nil, String: fmt.Sprint(v.Datum.GetValue()),
}
continue
}
if v2, ok := opt.Expr.(*ast.FuncCallExpr); ok {
ct.DefaultValueValue = sql.NullString{Valid: true, String: v2.FnName.String()}
}
}
if opt.Tp == ast.ColumnOptionPrimaryKey {
ct.PrimaryKeyValue = sql.NullBool{
Valid: true,
Bool: true,
}
}
}
return ct
}
func (d *defaultParser) getIndexes(create *ast.CreateTableStmt) []gorm.Index {
if create == nil || len(create.Constraints) == 0 {
return nil
}
indexs := make([]gorm.Index, 0, len(create.Constraints))
table := create.Table.Name.String()
for _, cons := range create.Constraints {
idx := &migrator.Index{
TableName: table, NameValue: cons.Name, ColumnList: []string{},
PrimaryKeyValue: sql.NullBool{
Bool: ast.ConstraintPrimaryKey == cons.Tp,
Valid: ast.ConstraintPrimaryKey == cons.Tp,
},
UniqueValue: sql.NullBool{Bool: ast.ConstraintUniq == cons.Tp, Valid: ast.ConstraintUniq == cons.Tp},
}
for _, col := range cons.Keys {
idx.ColumnList = append(idx.ColumnList, col.Column.Name.String())
}
indexs = append(indexs, idx)
}
return indexs
}
var (
intT = reflect.TypeOf(int32(0))
longT = reflect.TypeOf(int64(0))
boolT = reflect.TypeOf(false)
stringT = reflect.TypeOf("")
floatT = reflect.TypeOf(float32(0))
doubleT = reflect.TypeOf(float64(0))
timeT = reflect.TypeOf(time.Time{})
)
func getType(tp *types.FieldType) reflect.Type {
if tp == nil {
return nil
}
switch tp.GetType() {
case mysql.TypeTiny, mysql.TypeShort, mysql.TypeLong:
return intT
case mysql.TypeFloat:
return floatT
case mysql.TypeDouble:
return doubleT
case mysql.TypeTimestamp, mysql.TypeLonglong, mysql.TypeInt24:
return longT
case mysql.TypeDate, mysql.TypeDatetime, mysql.TypeNewDate:
return timeT
default:
return stringT
}
}