-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcolumn.go
More file actions
286 lines (233 loc) · 6.77 KB
/
column.go
File metadata and controls
286 lines (233 loc) · 6.77 KB
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
package element
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"strconv"
"strings"
ptypes "github.com/auxten/postgresql-parser/pkg/sql/types"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/format"
"github.com/pingcap/tidb/pkg/parser/types"
sqlite "github.com/rqlite/sql"
"github.com/sunary/sqlize/sqltemplates"
)
const (
// UppercaseRestoreFlag ...
UppercaseRestoreFlag = format.RestoreStringSingleQuotes | format.RestoreKeyWordUppercase | format.RestoreNameUppercase | format.RestoreNameBackQuotes
// LowerRestoreFlag ...
LowerRestoreFlag = format.RestoreStringSingleQuotes | format.RestoreKeyWordLowercase | format.RestoreNameLowercase | format.RestoreNameBackQuotes
)
type SqlAttr struct {
MysqlType *types.FieldType
PgType *ptypes.T
LiteType *sqlite.Type
Options []*ast.ColumnOption
Comment string
}
// Column ...
type Column struct {
Node
CurrentAttr SqlAttr
PreviousAttr SqlAttr
}
// GetType ...
func (c Column) GetType() byte {
if c.CurrentAttr.MysqlType != nil {
return c.CurrentAttr.MysqlType.GetType()
}
return 0
}
// DataType ...
func (c Column) DataType() string {
return c.typeDefinition(false)
}
// Constraint ...
func (c Column) Constraint() string {
for _, opt := range c.CurrentAttr.Options {
switch opt.Tp {
case ast.ColumnOptionPrimaryKey:
return "PK"
case ast.ColumnOptionReference:
return "FK"
}
}
return ""
}
// HasDefaultValue ...
func (c Column) HasDefaultValue() bool {
for _, opt := range c.CurrentAttr.Options {
if opt.Tp == ast.ColumnOptionDefaultValue {
return true
}
}
return false
}
func (c Column) hashValue() string {
strHash := sql.EscapeSqlName(c.Name)
strHash += " " + c.typeDefinition(false)
hash := md5.Sum([]byte(strHash))
return hex.EncodeToString(hash[:])
}
func (c Column) migrationUp(tbName, after string, ident int) []string {
switch c.Action {
case MigrateNoAction:
return nil
case MigrateAddAction:
strSql := sql.EscapeSqlName(c.Name)
if ident > len(c.Name) {
strSql += strings.Repeat(" ", ident-len(c.Name))
}
strSql += c.definition(false)
if ident < 0 {
if after != "" {
return []string{fmt.Sprintf(sql.AlterTableAddColumnAfterStm(), sql.EscapeSqlName(tbName), strSql, sql.EscapeSqlName(after))}
}
return []string{fmt.Sprintf(sql.AlterTableAddColumnFirstStm(), sql.EscapeSqlName(tbName), strSql)}
}
return append([]string{strSql}, c.migrationCommentUp(tbName)...)
case MigrateRemoveAction:
if sql.IsSqlite() {
return nil
}
return []string{fmt.Sprintf(sql.AlterTableDropColumnStm(), sql.EscapeSqlName(tbName), sql.EscapeSqlName(c.Name))}
case MigrateModifyAction:
def, isPk := c.pkDefinition(false)
if isPk {
if _, isPrevPk := c.pkDefinition(true); isPrevPk {
// avoid repeat define primary key
def = strings.Replace(def, " "+sql.PrimaryOption(), "", 1)
}
}
return []string{fmt.Sprintf(sql.AlterTableModifyColumnStm(), sql.EscapeSqlName(tbName), sql.EscapeSqlName(c.Name)+def)}
case MigrateRevertAction:
prevDef, isPrevPk := c.pkDefinition(true)
if isPrevPk {
if _, isPk := c.pkDefinition(false); isPk {
// avoid repeat define primary key
prevDef = strings.Replace(prevDef, " "+sql.PrimaryOption(), "", 1)
}
}
return []string{fmt.Sprintf(sql.AlterTableModifyColumnStm(), sql.EscapeSqlName(tbName), sql.EscapeSqlName(c.Name)+prevDef)}
case MigrateRenameAction:
return []string{fmt.Sprintf(sql.AlterTableRenameColumnStm(), sql.EscapeSqlName(tbName), sql.EscapeSqlName(c.OldName), sql.EscapeSqlName(c.Name))}
default:
return nil
}
}
func (c Column) migrationCommentUp(tbName string) []string {
if c.CurrentAttr.Comment == "" || sql.GetDialect() != sqltemplates.PostgresDialect {
return nil
}
// apply for postgres only
return []string{fmt.Sprintf(sql.ColumnComment(), tbName, c.Name, c.CurrentAttr.Comment)}
}
func (c Column) migrationDown(tbName, after string) []string {
switch c.Action {
case MigrateNoAction:
return nil
case MigrateAddAction:
c.Action = MigrateRemoveAction
case MigrateRemoveAction:
c.Action = MigrateAddAction
case MigrateModifyAction:
c.Action = MigrateRevertAction
case MigrateRenameAction:
c.Name, c.OldName = c.OldName, c.Name
default:
return nil
}
return c.migrationUp(tbName, after, -1)
}
func (c Column) pkDefinition(isPrev bool) (string, bool) {
attr := c.CurrentAttr
if isPrev {
attr = c.PreviousAttr
}
strSql := " " + c.typeDefinition(isPrev)
isPrimaryKey := false
hasComment := false
for _, opt := range attr.Options {
if opt.Tp == ast.ColumnOptionPrimaryKey {
isPrimaryKey = true
}
b := bytes.NewBufferString("")
var ctx *format.RestoreCtx
if sql.IsLowercase() {
ctx = format.NewRestoreCtx(LowerRestoreFlag, b)
} else {
ctx = format.NewRestoreCtx(UppercaseRestoreFlag, b)
}
if sql.IsPostgres() && opt.Tp == ast.ColumnOptionDefaultValue {
strSql += " " + opt.StrValue
continue
}
if sql.IsSqlite() {
// SQLite overrides, that pingcap doesn't support
if opt.Tp == ast.ColumnOptionDefaultValue {
// Parsed StrValue may be quoted in single quotes, which breaks SQL expression.
// We need to unquote it and, if it's a TEXT column. quote it again with double quotes.
expression, err := strconv.Unquote(opt.StrValue)
if err != nil {
expression = opt.StrValue
}
if len(expression) >= 2 && expression[0] == '\'' && expression[len(expression)-1] == '\'' {
// remove single quotes. strconv may not detect it
expression = expression[1 : len(expression)-1]
}
if c.typeDefinition(isPrev) == "TEXT" {
expression = strconv.Quote(expression)
}
strSql += " DEFAULT " + expression
continue
}
if opt.Tp == ast.ColumnOptionAutoIncrement {
strSql += " AUTOINCREMENT"
continue
}
if opt.Tp == ast.ColumnOptionUniqKey {
strSql += " UNIQUE"
continue
}
if opt.Tp == ast.ColumnOptionCheck {
strSql += " CHECK (" + opt.StrValue + ")"
continue
}
}
if opt.Tp == ast.ColumnOptionReference && opt.Refer == nil { // manual add
continue
}
_ = opt.Restore(ctx)
optStr := b.String()
if opt.Tp == ast.ColumnOptionDefaultValue {
optStr = strings.ReplaceAll(optStr, "DEFAULT _UTF8MB4", "DEFAULT ")
}
if !hasComment {
strSql += " " + optStr
}
if opt.Tp == ast.ColumnOptionComment {
hasComment = true
}
}
return strSql, isPrimaryKey
}
func (c Column) definition(isPrev bool) string {
def, _ := c.pkDefinition(isPrev)
return def
}
func (c Column) typeDefinition(isPrev bool) string {
attr := c.CurrentAttr
if isPrev {
attr = c.PreviousAttr
}
switch {
case sql.IsPostgres() && attr.PgType != nil:
return attr.PgType.SQLString()
case sql.IsSqlite() && attr.LiteType != nil:
return attr.LiteType.Name.Name
case attr.MysqlType != nil:
return attr.MysqlType.String()
}
return "" // column type is empty
}