-
Notifications
You must be signed in to change notification settings - Fork 0
/
drift_views.go
53 lines (41 loc) · 1 KB
/
drift_views.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
package pgutil
import (
"fmt"
"strings"
)
type ViewModifier struct {
d ViewDescription
}
func NewViewModifier(_ SchemaDescription, d ViewDescription) ViewModifier {
return ViewModifier{
d: d,
}
}
func (m ViewModifier) Key() string {
return fmt.Sprintf("%q.%q", m.d.Namespace, m.d.Name)
}
func (m ViewModifier) ObjectType() string {
return "view"
}
func (m ViewModifier) Description() ViewDescription {
return m.d
}
func (m ViewModifier) Create() string {
return fmt.Sprintf("CREATE OR REPLACE VIEW %s AS %s", m.Key(), strings.TrimSpace(stripIdent(" "+m.d.Definition)))
}
func (m ViewModifier) Drop() string {
return fmt.Sprintf("DROP VIEW IF EXISTS %s;", m.Key())
}
func stripIdent(s string) string {
lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
min := len(lines[0])
for _, line := range lines {
if ident := len(line) - len(strings.TrimLeft(line, " ")); ident < min {
min = ident
}
}
for i, line := range lines {
lines[i] = line[min:]
}
return strings.Join(lines, "\n")
}