-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrift_columns.go
87 lines (73 loc) · 2.04 KB
/
drift_columns.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 pgutil
import (
"fmt"
)
type ColumnModifier struct {
t TableDescription
d ColumnDescription
}
func NewColumnModifier(_ SchemaDescription, t TableDescription, d ColumnDescription) ColumnModifier {
return ColumnModifier{
t: t,
d: d,
}
}
func (m ColumnModifier) Key() string {
return fmt.Sprintf("%q.%q.%q", m.t.Namespace, m.t.Name, m.d.Name)
}
func (m ColumnModifier) ObjectType() string {
return "column"
}
func (m ColumnModifier) Description() ColumnDescription {
return m.d
}
func (m ColumnModifier) Create() string {
nullableExpr := ""
if !m.d.IsNullable {
nullableExpr = " NOT NULL"
}
defaultExpr := ""
if m.d.Default != "" {
defaultExpr = fmt.Sprintf(" DEFAULT %s", m.d.Default)
}
return fmt.Sprintf("ALTER TABLE %q.%q ADD COLUMN IF NOT EXISTS %q %s%s%s;", m.t.Namespace, m.t.Name, m.d.Name, m.d.Type, nullableExpr, defaultExpr)
}
func (m ColumnModifier) Drop() string {
return fmt.Sprintf("ALTER TABLE %q.%q DROP COLUMN IF EXISTS %q;", m.t.Namespace, m.t.Name, m.d.Name)
}
func (m ColumnModifier) AlterExisting(existingSchema SchemaDescription, existingObject ColumnDescription) ([]ddlStatement, bool) {
statements := []string{}
alterColumn := func(format string, args ...any) {
statements = append(statements, fmt.Sprintf(fmt.Sprintf("ALTER TABLE %q.%q ALTER COLUMN %q %s;", m.t.Namespace, m.t.Name, m.d.Name, format), args...))
}
if m.d.Type != existingObject.Type {
alterColumn("SET DATA TYPE %s", m.d.Type)
}
if m.d.Default != existingObject.Default {
if m.d.Default == "" {
alterColumn("DROP DEFAULT")
} else {
alterColumn("SET DEFAULT %s", m.d.Default)
}
}
if m.d.IsNullable != existingObject.IsNullable {
if m.d.IsNullable {
alterColumn("DROP NOT NULL")
} else {
alterColumn("SET NOT NULL")
}
}
// TODO - handle CharacterMaximumLength
// TODO - handle IsIdentity
// TODO - handle IdentityGeneration
// TODO - handle IsGenerated
// TODO - handle GenerationExpression
return []ddlStatement{
newStatement(
m.Key(),
"replace",
m.ObjectType(),
statements...,
),
}, true
}