-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
alter.go
92 lines (71 loc) · 1.9 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
88
89
90
91
92
package bob
import (
"errors"
"strings"
"github.com/lann/builder"
)
type AlterBuilder builder.Builder
type alter int
const (
alterDropColumn alter = iota
alterDropConstraint
alterRenameColumn
alterRenameConstraint
)
type alterData struct {
What alter
TableName string
FirstKey string
SecondKey string
Suffix string
}
func init() {
builder.Register(AlterBuilder{}, alterData{})
}
func (b AlterBuilder) whatToAlter(what alter) AlterBuilder {
return builder.Set(b, "What", what).(AlterBuilder)
}
func (b AlterBuilder) tableName(table string) AlterBuilder {
return builder.Set(b, "TableName", table).(AlterBuilder)
}
func (b AlterBuilder) firstKey(key string) AlterBuilder {
return builder.Set(b, "FirstKey", key).(AlterBuilder)
}
func (b AlterBuilder) secondKey(key string) AlterBuilder {
return builder.Set(b, "SecondKey", key).(AlterBuilder)
}
func (b AlterBuilder) Suffix(any string) AlterBuilder {
return builder.Set(b, "Suffix", any).(AlterBuilder)
}
func (b AlterBuilder) ToSql() (string, []interface{}, error) {
data := builder.GetStruct(b).(alterData)
return data.ToSql()
}
func (d *alterData) ToSql() (sqlStr string, args []interface{}, err error) {
if d.TableName == "" {
err = errors.New("table name must not be empty")
return
}
if d.FirstKey == "" {
err = errors.New("the second argument must not be empty")
return
}
var sql strings.Builder
sql.WriteString("ALTER TABLE ")
sql.WriteString(d.TableName + " ")
switch d.What {
case alterDropColumn:
sql.WriteString("DROP COLUMN " + d.FirstKey)
case alterDropConstraint:
sql.WriteString("DROP CONSTRAINT " + d.FirstKey)
case alterRenameColumn:
sql.WriteString("RENAME COLUMN " + d.FirstKey + " TO " + d.SecondKey)
case alterRenameConstraint:
sql.WriteString("RENAME CONSTRAINT " + d.FirstKey + " TO " + d.SecondKey)
}
if d.Suffix != "" {
sql.WriteString(" " + d.Suffix)
}
sqlStr = sql.String()
return
}