-
Notifications
You must be signed in to change notification settings - Fork 4
/
schema_command.go
116 lines (92 loc) · 1.93 KB
/
schema_command.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
package migrator
import (
"fmt"
"strings"
)
type command interface {
toSQL() string
}
type createTableCommand struct {
t Table
}
func (c createTableCommand) toSQL() string {
if c.t.Name == "" {
return ""
}
context := c.t.columns.render()
if context == "" {
context = "`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT"
}
if res := c.t.indexes.render(); res != "" {
context += ", " + res
}
if res := c.t.foreigns.render(); res != "" {
context += ", " + res
}
engine := c.t.Engine
if engine == "" {
engine = "InnoDB"
}
charset := c.t.Charset
collation := c.t.Collation
if charset == "" && collation == "" {
charset = "utf8mb4"
collation = "utf8mb4_unicode_ci"
}
if charset == "" && collation != "" {
parts := strings.Split(collation, "_")
charset = parts[0]
}
if charset != "" && collation == "" {
collation = charset + "_unicode_ci"
}
return fmt.Sprintf(
"CREATE TABLE `%s` (%s) ENGINE=%s DEFAULT CHARSET=%s COLLATE=%s",
c.t.Name,
context,
engine,
charset,
collation,
)
}
type dropTableCommand struct {
table string
soft bool
option string
}
func (c dropTableCommand) toSQL() string {
sql := "DROP TABLE"
if c.soft {
sql += " IF EXISTS"
}
sql += fmt.Sprintf(" `%s`", c.table)
var validOptions = list{"RESTRICT", "CASCADE"}
if validOptions.has(strings.ToUpper(c.option)) {
sql += " " + strings.ToUpper(c.option)
}
return sql
}
type renameTableCommand struct {
old string
new string
}
func (c renameTableCommand) toSQL() string {
return fmt.Sprintf("RENAME TABLE `%s` TO `%s`", c.old, c.new)
}
type alterTableCommand struct {
name string
pool TableCommands
}
func (c alterTableCommand) toSQL() string {
if c.name == "" || len(c.pool) == 0 {
return ""
}
return "ALTER TABLE `" + c.name + "` " + c.poolToSQL()
}
func (c alterTableCommand) poolToSQL() string {
var sql []string
for _, tc := range c.pool {
sql = append(sql, tc.toSQL())
}
return strings.Join(sql, ", ")
}