forked from gobuffalo/fizz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tables.go
290 lines (266 loc) · 7.16 KB
/
tables.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package fizz
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/gobuffalo/plush"
"github.com/pkg/errors"
)
// Table is the table definition for fizz.
type Table struct {
Name string `db:"name"`
Columns []Column
Indexes []Index
ForeignKeys []ForeignKey
primaryKeys []string
Options map[string]interface{}
columnsCache map[string]struct{}
}
func (t Table) String() string {
return t.Fizz()
}
// Fizz returns the fizz DDL to create the table.
func (t Table) Fizz() string {
var buff bytes.Buffer
timestampsOpt := t.Options["timestamps"].(bool)
// Write table options
o := make([]string, 0, len(t.Options))
for k, v := range t.Options {
// Special handling for timestamps option
if k == "timestamps" {
continue
}
vv, _ := json.Marshal(v)
o = append(o, fmt.Sprintf("%s: %s", k, string(vv)))
}
if len(o) > 0 {
sort.SliceStable(o, func(i, j int) bool { return o[i] < o[j] })
buff.WriteString(fmt.Sprintf("create_table(\"%s\", {%s}) {\n", t.Name, strings.Join(o, ", ")))
} else {
buff.WriteString(fmt.Sprintf("create_table(\"%s\") {\n", t.Name))
}
// Write columns
if timestampsOpt {
for _, c := range t.Columns {
if c.Name == "created_at" || c.Name == "updated_at" {
continue
}
buff.WriteString(fmt.Sprintf("\t%s\n", c.String()))
}
} else {
for _, c := range t.Columns {
buff.WriteString(fmt.Sprintf("\t%s\n", c.String()))
}
}
if timestampsOpt {
buff.WriteString("\tt.Timestamps()\n")
}
// Write primary key (single column pk will be written in inline form as the column opt)
if len(t.primaryKeys) > 1 {
pks := make([]string, len(t.primaryKeys))
for i, pk := range t.primaryKeys {
pks[i] = fmt.Sprintf("\"%s\"", pk)
}
buff.WriteString(fmt.Sprintf("\tt.PrimaryKey(%s)\n", strings.Join(pks, ", ")))
}
// Write indexes
for _, i := range t.Indexes {
buff.WriteString(fmt.Sprintf("\t%s\n", i.String()))
}
// Write foreign keys
for _, fk := range t.ForeignKeys {
buff.WriteString(fmt.Sprintf("\t%s\n", fk.String()))
}
buff.WriteString("}")
return buff.String()
}
// UnFizz returns the fizz DDL to remove the table.
func (t Table) UnFizz() string {
return fmt.Sprintf("drop_table(\"%s\")", t.Name)
}
func (t *Table) DisableTimestamps() {
t.Options["timestamps"] = false
}
// Column adds a column to the table definition.
func (t *Table) Column(name string, colType string, options Options) error {
if _, found := t.columnsCache[name]; found {
return fmt.Errorf("duplicated column %s", name)
}
var primary bool
if _, ok := options["primary"]; ok {
if t.primaryKeys != nil {
return errors.New("could not define multiple primary keys")
}
primary = true
t.primaryKeys = []string{name}
}
c := Column{
Name: name,
ColType: colType,
Options: options,
Primary: primary,
}
if t.columnsCache == nil {
t.columnsCache = make(map[string]struct{})
}
t.columnsCache[name] = struct{}{}
// Ensure id is first
if name == "id" {
t.Columns = append([]Column{c}, t.Columns...)
} else {
t.Columns = append(t.Columns, c)
}
return nil
}
// ForeignKey adds a new foreign key to the table definition.
func (t *Table) ForeignKey(column string, refs interface{}, options Options) error {
fkr, err := parseForeignKeyRef(refs)
if err != nil {
return errors.Wrap(err, "could not parse foreign key")
}
fk := ForeignKey{
Column: column,
References: fkr,
Options: options,
}
if options["name"] != nil {
fk.Name = options["name"].(string)
} else {
fk.Name = fmt.Sprintf("%s_%s_%s_fk", t.Name, fk.References.Table, strings.Join(fk.References.Columns, "_"))
}
t.ForeignKeys = append(t.ForeignKeys, fk)
return nil
}
// Index adds a new index to the table definition.
func (t *Table) Index(columns interface{}, options Options) error {
i := Index{}
switch tp := columns.(type) {
default:
return errors.Errorf("unexpected type %T for %s index columns", tp, t.Name) // %T prints whatever type t has
case string:
i.Columns = []string{tp}
case []string:
if len(tp) == 0 {
return errors.Errorf("expected at least one column to apply %s index", t.Name)
}
i.Columns = tp
case []interface{}:
if len(tp) == 0 {
return errors.Errorf("expected at least one column to apply %s index", t.Name)
}
cl := make([]string, len(tp))
for i, c := range tp {
cl[i] = c.(string)
}
i.Columns = cl
}
if options["name"] != nil {
i.Name = options["name"].(string)
} else {
i.Name = fmt.Sprintf("%s_%s_idx", t.Name, strings.Join(i.Columns, "_"))
}
i.Unique = options["unique"] != nil && options["unique"].(bool)
t.Indexes = append(t.Indexes, i)
return nil
}
// Timestamp is a shortcut to add a timestamp column with default options.
func (t *Table) Timestamp(name string) error {
return t.Column(name, "timestamp", Options{})
}
// Timestamps adds created_at and updated_at columns to the Table definition.
func (t *Table) Timestamps() error {
if err := t.Timestamp("created_at"); err != nil {
return err
}
return t.Timestamp("updated_at")
}
// PrimaryKey adds a primary key to the table. It's useful to define a composite
// primary key.
func (t *Table) PrimaryKey(pk ...string) error {
if len(pk) == 0 {
return errors.New("missing columns for primary key")
}
if t.primaryKeys != nil {
return errors.New("duplicate primary key")
}
if !t.HasColumns(pk...) {
return errors.New("columns must be declared before the primary key")
}
if len(pk) == 1 {
for i, c := range t.Columns {
if c.Name == pk[0] {
t.Columns[i].Primary = true
break
}
}
}
t.primaryKeys = make([]string, 0)
t.primaryKeys = append(t.primaryKeys, pk...)
return nil
}
// PrimaryKeys gets the list of registered primary key fields.
func (t *Table) PrimaryKeys() []string {
return t.primaryKeys
}
// ColumnNames returns the names of the Table's columns.
func (t *Table) ColumnNames() []string {
cols := make([]string, len(t.Columns))
for i, c := range t.Columns {
cols[i] = c.Name
}
return cols
}
// HasColumns checks if the Table has all the given columns.
func (t *Table) HasColumns(args ...string) bool {
for _, a := range args {
if _, ok := t.columnsCache[a]; !ok {
return false
}
}
return true
}
// NewTable creates a new Table.
func NewTable(name string, opts map[string]interface{}) Table {
if opts == nil {
opts = make(map[string]interface{})
}
// auto-timestamp as default
if enabled, exists := opts["timestamps"]; !exists || enabled == true {
opts["timestamps"] = true
}
return Table{
Name: name,
Columns: []Column{},
Indexes: []Index{},
Options: opts,
columnsCache: map[string]struct{}{},
}
}
func (f fizzer) CreateTable(name string, opts map[string]interface{}, help plush.HelperContext) error {
t := NewTable(name, opts)
if help.HasBlock() {
ctx := help.Context.New()
ctx.Set("t", &t)
if _, err := help.BlockWith(ctx); err != nil {
return errors.WithStack(err)
}
}
if t.Options["timestamps"].(bool) {
if !t.HasColumns("created_at", "updated_at") {
t.Timestamps()
}
}
f.add(f.Bubbler.CreateTable(t))
return nil
}
func (f fizzer) DropTable(name string) {
f.add(f.Bubbler.DropTable(Table{Name: name}))
}
func (f fizzer) RenameTable(old, new string) {
f.add(f.Bubbler.RenameTable([]Table{
{Name: old},
{Name: new},
}))
}