-
Notifications
You must be signed in to change notification settings - Fork 8
/
generator.go
210 lines (180 loc) · 4.73 KB
/
generator.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package pqtsql
import (
"bytes"
"errors"
"fmt"
"io"
"github.com/piotrkowalczuk/pqt"
)
// Generator ...
type Generator struct{}
// NewGenerator ...
func NewGenerator() *Generator {
return &Generator{}
}
// Generate ...
func (g *Generator) Generate(s *pqt.Schema) ([]byte, error) {
code, err := g.generate(s)
if err != nil {
return nil, err
}
return code.Bytes(), nil
}
// GenerateTo ...
func (g *Generator) GenerateTo(s *pqt.Schema, w io.Writer) error {
code, err := g.generate(s)
if err != nil {
return err
}
_, err = code.WriteTo(w)
return err
}
func (g *Generator) generate(s *pqt.Schema) (*bytes.Buffer, error) {
code := bytes.NewBufferString("-- do not modify, generated by pqt\n\n")
if s.Name != "" {
fmt.Fprint(code, "CREATE SCHEMA ")
if s.IfNotExists {
fmt.Fprint(code, "IF NOT EXISTS ")
}
fmt.Fprintf(code, "%s; \n\n", s.Name)
}
for _, t := range s.Tables {
if err := g.generateCreateTable(code, t); err != nil {
return nil, err
}
}
return code, nil
}
func (g *Generator) generateCreateTable(buf *bytes.Buffer, t *pqt.Table) error {
if t == nil {
return nil
}
if t.Name == "" {
return errors.New("pqt: missing table name")
}
if len(t.Columns) == 0 {
return fmt.Errorf("pqt: table %s has no columns", t.Name)
}
constraints := tableConstraints(t)
buf.WriteString("CREATE ")
if t.Temporary {
buf.WriteString("TEMPORARY ")
}
buf.WriteString("TABLE ")
if t.IfNotExists {
buf.WriteString("IF NOT EXISTS ")
}
if t.Schema != nil {
buf.WriteString(t.Schema.Name)
buf.WriteRune('.')
buf.WriteString(t.Name)
} else {
buf.WriteString(t.Name)
}
buf.WriteString(" (\n")
for i, c := range t.Columns {
buf.WriteRune(' ')
buf.WriteString(c.Name)
buf.WriteRune(' ')
buf.WriteString(c.Type.String())
if c.Collate != "" {
buf.WriteRune(' ')
buf.WriteString(c.Collate)
}
if d, ok := c.DefaultOn(pqt.EventInsert); ok {
buf.WriteString(" DEFAULT ")
buf.WriteString(d)
}
if c.NotNull {
buf.WriteString(" NOT NULL")
}
if i < len(t.Columns)-1 || len(constraints) > 0 {
buf.WriteRune(',')
}
buf.WriteRune('\n')
}
if len(constraints) > 0 {
buf.WriteRune('\n')
}
for i, c := range constraints {
buf.WriteString(" ")
err := g.generateConstraint(buf, c)
if err != nil {
return err
}
if i < len(constraints)-1 {
buf.WriteRune(',')
}
buf.WriteRune('\n')
}
buf.WriteString(");\n\n")
return nil
}
func (g *Generator) generateConstraint(buf *bytes.Buffer, c *pqt.Constraint) error {
switch c.Type {
case pqt.ConstraintTypeUnique:
uniqueConstraintQuery(buf, c)
case pqt.ConstraintTypePrimaryKey:
primaryKeyConstraintQuery(buf, c)
case pqt.ConstraintTypeForeignKey:
return foreignKeyConstraintQuery(buf, c)
case pqt.ConstraintTypeCheck:
checkConstraintQuery(buf, c)
default:
return fmt.Errorf("pqt: unknown constraint type: %s", c.Type)
}
return nil
}
func uniqueConstraintQuery(buf *bytes.Buffer, c *pqt.Constraint) {
fmt.Fprintf(buf, `CONSTRAINT "%s" UNIQUE (%s)`, c.Name(), pqt.JoinColumns(c.Columns, ", "))
}
func primaryKeyConstraintQuery(buf *bytes.Buffer, c *pqt.Constraint) {
fmt.Fprintf(buf, `CONSTRAINT "%s" PRIMARY KEY (%s)`, c.Name(), pqt.JoinColumns(c.Columns, ", "))
}
func foreignKeyConstraintQuery(buf *bytes.Buffer, c *pqt.Constraint) error {
switch {
case len(c.Columns) == 0:
return errors.New("pqt: foreign key constraint require at least one column")
case len(c.ReferenceColumns) == 0:
return errors.New("pqt: foreign key constraint require at least one reference column")
case c.ReferenceTable == nil:
return errors.New("pqt: foreiqn key constraint missing reference table")
}
fmt.Fprintf(buf, `CONSTRAINT "%s" FOREIGN KEY (%s) REFERENCES %s (%s)`,
c.Name(),
pqt.JoinColumns(c.Columns, ", "),
c.ReferenceTable.FullName(),
pqt.JoinColumns(c.ReferenceColumns, ", "),
)
switch c.OnDelete {
case pqt.Cascade:
buf.WriteString(" ON DELETE CASCADE")
case pqt.Restrict:
buf.WriteString(" ON DELETE RESTRICT")
case pqt.SetNull:
buf.WriteString(" ON DELETE SET NULL")
case pqt.SetDefault:
buf.WriteString(" ON DELETE SET DEFAULT")
}
switch c.OnUpdate {
case pqt.Cascade:
buf.WriteString(" ON UPDATE CASCADE")
case pqt.Restrict:
buf.WriteString(" ON UPDATE RESTRICT")
case pqt.SetNull:
buf.WriteString(" ON UPDATE SET NULL")
case pqt.SetDefault:
buf.WriteString(" ON UPDATE SET DEFAULT")
}
return nil
}
func checkConstraintQuery(buf *bytes.Buffer, c *pqt.Constraint) {
fmt.Fprintf(buf, `CONSTRAINT "%s" CHECK (%s)`, c.Name(), c.Check)
}
func tableConstraints(t *pqt.Table) []*pqt.Constraint {
constraints := make([]*pqt.Constraint, 0, len(t.Constraints)+len(t.Columns))
for _, c := range t.Columns {
constraints = append(constraints, c.Constraints()...)
}
return append(constraints, t.Constraints...)
}