forked from ariga/atlas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysqlcheck.go
226 lines (218 loc) · 6.94 KB
/
mysqlcheck.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
// Copyright 2021-present The Atlas Authors. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package mysqlcheck
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/iasthc/atlas/schemahcl"
"github.com/iasthc/atlas/sql/migrate"
"github.com/iasthc/atlas/sql/mysql"
"github.com/iasthc/atlas/sql/schema"
"github.com/iasthc/atlas/sql/sqlcheck"
"github.com/iasthc/atlas/sql/sqlcheck/condrop"
"github.com/iasthc/atlas/sql/sqlcheck/datadepend"
"github.com/iasthc/atlas/sql/sqlcheck/destructive"
"github.com/iasthc/atlas/sql/sqlcheck/incompatible"
"github.com/iasthc/atlas/sql/sqlcheck/naming"
)
var (
// codeImplicitUpdate is a MySQL specific code for reporting implicit update.
codeImplicitUpdate = sqlcheck.Code("MY101")
// codeInlineRef is a MySQL specific code for reporting columns with inline references.
codeInlineRef = sqlcheck.Code("MY102")
)
func addNotNull(p *datadepend.ColumnPass) (diags []sqlcheck.Diagnostic, err error) {
// Two types of reporting, implicit rows update and
// changes that may cause the migration to fail.
mightFail := func(tt string) {
diags = append(diags, sqlcheck.Diagnostic{
Pos: p.Change.Stmt.Pos,
Text: fmt.Sprintf(
"Adding a non-nullable %q column %q will fail in case table %q is not empty",
tt, p.Column.Name, p.Table.Name,
),
})
}
implicitUpdate := func(tt, v string) {
if !columnFilledAfter(p, v) {
diags = append(diags, sqlcheck.Diagnostic{
Code: codeImplicitUpdate,
Pos: p.Change.Stmt.Pos,
Text: fmt.Sprintf(
"Adding a non-nullable %q column %q on table %q without a default value implicitly sets existing rows with %s",
tt, p.Column.Name, p.Table.Name, v,
),
})
}
}
drv, ok := p.Dev.Driver.(*mysql.Driver)
if !ok {
return nil, fmt.Errorf("unexpected migrate driver %T", p.Dev.Driver)
}
switch ct := p.Column.Type.Type.(type) {
case *mysql.BitType, *schema.BoolType, *schema.IntegerType, *schema.DecimalType, *schema.FloatType, *schema.BinaryType:
tt, err := mysql.FormatType(p.Column.Type.Type)
if err != nil {
return nil, err
}
implicitUpdate(tt, "0")
case *schema.StringType:
switch ct.T {
case mysql.TypeVarchar, mysql.TypeChar:
implicitUpdate(ct.T, `""`)
case mysql.TypeText, mysql.TypeTinyText, mysql.TypeMediumText, mysql.TypeLongText:
// On MySQL, Existing rows are updated with ''. Skip it
// as we cannot propose and detect multi-steps migration
// (ALTER + UPDATE) at this stage.
if drv.Maria() {
implicitUpdate(ct.T, `""`)
}
}
case *schema.EnumType:
if len(ct.Values) == 0 {
return nil, fmt.Errorf("unexpected empty values for enum column %q.%q", p.Table.Name, p.Column.Name)
}
implicitUpdate("enum", strconv.Quote(ct.Values[0]))
case *mysql.SetType:
implicitUpdate("set", `""`)
case *schema.JSONType:
// On MySQL, Existing rows are updated with 'null' JSON. Same as TEXT
// columns, we cannot propose multi-steps migration (ALTER + UPDATE)
// as it cannot be detected at this stage.
if drv.Maria() {
implicitUpdate(ct.T, `""`)
}
case *schema.TimeType:
switch ct.T {
case mysql.TypeDate, mysql.TypeDateTime:
if drv.Maria() {
implicitUpdate(ct.T, "00:00:00")
} else {
// The suggested solution is to add a DEFAULT clause
// with valid value or set the column to nullable.
mightFail(ct.T)
}
case mysql.TypeYear:
implicitUpdate(ct.T, "0000")
case mysql.TypeTime:
implicitUpdate(ct.T, "00:00:00")
case mysql.TypeTimestamp:
v := "CURRENT_TIMESTAMP"
switch {
case drv.Maria():
// Maria has a special behavior for the first TIMESTAMP column.
// See: https://mariadb.com/kb/en/timestamp/#automatic-values
for i := 0; i < len(p.Table.Columns) && p.Table.Columns[i].Name != p.Column.Name; i++ {
tt, err := mysql.FormatType(p.Table.Columns[i].Type.Type)
if err != nil {
return nil, err
}
if strings.HasPrefix(tt, mysql.TypeTimestamp) {
v = "0000-00-00 00:00:00"
break
}
}
// Following MySQL 8.0.2, the explicit_defaults_for_timestamp
// system variable is now enabled by default.
case drv.GTE("8.0.2"):
v = "0000-00-00 00:00:00"
}
implicitUpdate(ct.T, v)
}
case *schema.SpatialType:
if drv.Maria() {
implicitUpdate(ct.T, `""`)
} else {
// The suggested solution is to add the column as
// null, update values and then set it to not-null.
mightFail(ct.T)
}
}
return
}
// columnFilledAfter checks if the column with the given value was filled after the current change.
func columnFilledAfter(pass *datadepend.ColumnPass, matchValue string) bool {
p, ok := pass.File.Parser.(interface {
ColumnFilledAfter(migrate.File, *schema.Table, *schema.Column, int, any) (bool, error)
})
if !ok {
return false
}
filled, _ := p.ColumnFilledAfter(pass.File, pass.Table, pass.Column, pass.Change.Stmt.Pos, matchValue)
return filled
}
// inlineRefs is an analyzer function that detects column definitions with the REFERENCES
// clause and suggest replacing them with an explicit foreign-key definition.
func inlineRefs(_ context.Context, p *sqlcheck.Pass) error {
var diags []sqlcheck.Diagnostic
parse, ok := p.File.Parser.(interface {
ColumnHasReferences(*migrate.Stmt, *schema.Column) (bool, error)
})
if !ok {
return nil
}
for _, sc := range p.File.Changes {
for _, c := range sc.Changes {
switch c := c.(type) {
case *schema.AddTable:
for i := range c.T.Columns {
if hasR, _ := parse.ColumnHasReferences(sc.Stmt, c.T.Columns[i]); hasR {
diags = append(diags, sqlcheck.Diagnostic{
Pos: sc.Stmt.Pos,
Code: codeInlineRef,
Text: fmt.Sprintf("Defining column %q on table %q with inline REFERENCES is ignored by MySQL", c.T.Columns[i].Name, c.T.Name),
})
}
}
case *schema.ModifyTable:
for _, mc := range c.Changes {
add, ok := mc.(*schema.AddColumn)
if !ok {
continue
}
if hasR, _ := parse.ColumnHasReferences(sc.Stmt, add.C); hasR {
diags = append(diags, sqlcheck.Diagnostic{
Pos: sc.Stmt.Pos,
Code: codeInlineRef,
Text: fmt.Sprintf("Defining column %q on table %q with inline REFERENCES is ignored by MySQL", add.C.Name, c.T.Name),
})
}
}
}
}
}
if len(diags) > 0 {
p.Reporter.WriteReport(sqlcheck.Report{Text: "inline REFERENCES detected", Diagnostics: diags})
}
return nil
}
func init() {
sqlcheck.Register(mysql.DriverName, func(r *schemahcl.Resource) ([]sqlcheck.Analyzer, error) {
ds, err := destructive.New(r)
if err != nil {
return nil, err
}
cd, err := condrop.New(r)
if err != nil {
return nil, err
}
dd, err := datadepend.New(r, datadepend.Handler{
AddNotNull: addNotNull,
})
if err != nil {
return nil, err
}
bc, err := incompatible.New(r)
if err != nil {
return nil, err
}
nm, err := naming.New(r)
if err != nil {
return nil, err
}
return []sqlcheck.Analyzer{ds, dd, cd, bc, nm, sqlcheck.AnalyzerFunc(inlineRefs)}, nil
})
}