-
Notifications
You must be signed in to change notification settings - Fork 75
/
alter.go
87 lines (71 loc) · 2.43 KB
/
alter.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
package mysql
import (
"fmt"
"strings"
schemasv1alpha1 "github.com/schemahero/schemahero/pkg/apis/schemas/v1alpha1"
)
func columnsMatch(col1 *Column, col2 *Column) bool {
if col1.DataType != col2.DataType {
return false
}
if col1.Constraints == nil && col2.Constraints != nil {
return false
}
if col1.Constraints != nil && col2.Constraints == nil {
return false
}
if col1.Constraints != nil && col2.Constraints != nil {
if col1.Constraints.NotNull != col2.Constraints.NotNull {
return false
}
}
return true
}
func AlterColumnStatement(tableName string, desiredColumns []*schemasv1alpha1.SQLTableColumn, existingColumn *Column) (string, error) {
// this could be an alter or a drop column command
columnStatement := ""
for _, desiredColumn := range desiredColumns {
if desiredColumn.Name == existingColumn.Name {
column, err := schemaColumnToMysqlColumn(desiredColumn)
if err != nil {
return "", err
}
if columnsMatch(existingColumn, column) {
return "", nil
}
changes := []string{}
if existingColumn.DataType != column.DataType {
changes = append(changes, fmt.Sprintf("%s type %s", columnStatement, column.DataType))
}
// too much complexity below!
if column.Constraints != nil || existingColumn.Constraints != nil {
// Add not null
if column.Constraints != nil && column.Constraints.NotNull != nil && *column.Constraints.NotNull == true {
if existingColumn.Constraints != nil || existingColumn.Constraints.NotNull != nil {
if *existingColumn.Constraints.NotNull == false {
changes = append(changes, fmt.Sprintf("%s set not null", columnStatement))
}
}
}
// Drop not null
if column.Constraints != nil && column.Constraints.NotNull != nil && *column.Constraints.NotNull == false {
if existingColumn.Constraints != nil || existingColumn.Constraints.NotNull != nil {
if *existingColumn.Constraints.NotNull == true {
changes = append(changes, fmt.Sprintf("%s drop not null", columnStatement))
}
}
}
}
if len(changes) == 0 {
// no changes
return "", nil
}
columnStatement = fmt.Sprintf("alter table `%s` alter column `%s`%s", tableName, existingColumn.Name, strings.Join(changes, " "))
}
}
if columnStatement == "" {
// wasn't found as a desired column, so drop
columnStatement = fmt.Sprintf("alter table `%s` drop column `%s`", tableName, existingColumn.Name)
}
return columnStatement, nil
}