-
Notifications
You must be signed in to change notification settings - Fork 6
/
table.go
324 lines (272 loc) · 8.82 KB
/
table.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package pqt
import (
"fmt"
"sort"
)
// Table is partially implemented postgres table synopsis.
type Table struct {
self bool
Name, ShortName, Collate, TableSpace string
IfNotExists, Temporary bool
// Schema references parent schema.
Schema *Schema
// Columns is a collection of columns that table contains.
Columns Columns
// Constraints is a collection of constraints that table contains.
Constraints Constraints
// OwnedRelationships is a collection of relationships that table owns.
OwnedRelationships []*Relationship
// InversedRelationships is a collection of relationships that table is inversed in.
InversedRelationships []*Relationship
// ManyToManyRelationships is a collection of relationships that table is inversed in.
ManyToManyRelationships []*Relationship
}
// NewTable allocates new table using given name and options.
func NewTable(name string, opts ...TableOption) *Table {
t := &Table{
Name: name,
ShortName: name,
Columns: make(Columns, 0),
Constraints: make([]*Constraint, 0),
InversedRelationships: make([]*Relationship, 0),
OwnedRelationships: make([]*Relationship, 0),
}
for _, opt := range opts {
opt(t)
}
return t
}
// SelfReference returns almost empty table that express self reference.
// Should be used with relationships.
func SelfReference() *Table {
return &Table{
self: true,
}
}
// FullName if schema is defined returns name in format <schema>.<name> or just <name> if not set.
func (t *Table) FullName() string {
if t.Schema != nil && t.Schema.Name != "" {
return t.Schema.Name + "." + t.Name
}
return t.Name
}
// AddColumn adds column to the table.
func (t *Table) AddColumn(c *Column) *Table {
if c.Reference != nil {
r := newRelationship(t, c.Reference.Table, nil, RelationshipTypeManyToOne, c.ReferenceOptions...)
r.OwnerColumns = Columns{c}
r.InversedColumns = Columns{c.Reference}
t.OwnedRelationships = append(t.OwnedRelationships, r)
if r.Bidirectional && r.InversedTable != nil {
r.InversedTable.InversedRelationships = append(r.InversedTable.InversedRelationships, r)
}
t.AddConstraint(&Constraint{
Type: ConstraintTypeForeignKey,
Table: r.InversedTable,
Columns: r.InversedColumns,
PrimaryTable: r.OwnerTable,
PrimaryColumns: r.OwnerColumns,
OnDelete: c.OnDelete,
OnUpdate: c.OnUpdate,
Match: c.Match,
})
// When constraint is created, redundant data from column needs to be removed.
c.Reference = nil
c.OnDelete = 0
c.OnUpdate = 0
c.Match = 0
}
return t.addColumn(c)
}
func (t *Table) addColumn(c *Column) *Table {
if t.Columns == nil {
t.Columns = make(Columns, 0, 1)
}
c.Table = t
t.Columns = append(t.Columns, c)
t.Constraints = append(t.Constraints, c.Constraints()...)
sort.Sort(&t.Columns)
return t
}
// AddRelationship adds relationship to the table.
func (t *Table) AddRelationship(r *Relationship, opts ...ColumnOption) *Table {
if r == nil {
return t
}
if r.Type == RelationshipTypeManyToMany {
return t.addRelationshipManyToMany(r, opts...)
}
return t.addRelationship(r, opts...)
}
func (t *Table) addRelationship(r *Relationship, opts ...ColumnOption) *Table {
switch {
case r.InversedTable != nil && r.InversedTable.self:
r.InversedTable = t
case r.OwnerTable != nil && r.OwnerTable.self:
r.OwnerTable = t
}
switch r.Type {
case RelationshipTypeOneToOne, RelationshipTypeManyToOne:
r.OwnerTable = t
case RelationshipTypeOneToMany:
r.InversedTable = t
}
r.OwnerTable.OwnedRelationships = append(r.OwnerTable.OwnedRelationships, r)
if r.Bidirectional {
r.InversedTable.InversedRelationships = append(r.InversedTable.InversedRelationships, r)
}
pk, ok := r.InversedTable.PrimaryKey()
if !ok {
return t
}
name := r.ColumnName
if name == "" {
name = r.InversedTable.Name + "_" + pk.Name
}
nt := fkType(pk.Type)
col := NewColumn(name, nt, append([]ColumnOption{WithReference(pk)}, opts...)...)
r.OwnerTable.addColumn(col)
r.OwnerColumns = Columns{col}
r.InversedColumns = Columns{pk}
return t
}
func (t *Table) addRelationshipManyToMany(r *Relationship, opts ...ColumnOption) *Table {
r.ThroughTable = t
r.ThroughTable.OwnedRelationships = append(r.ThroughTable.OwnedRelationships, r)
if r.Bidirectional {
r.OwnerTable.ManyToManyRelationships = append(r.OwnerTable.ManyToManyRelationships, r)
r.InversedTable.ManyToManyRelationships = append(r.InversedTable.ManyToManyRelationships, r)
}
ownerColumns := make(Columns, 0)
inversedColumns := make(Columns, 0)
if r.OwnerForeignKey != nil {
r.OwnerForeignKey.PrimaryTable = r.ThroughTable
r.ThroughTable.AddConstraint(r.OwnerForeignKey)
for _, oc := range r.OwnerForeignKey.PrimaryColumns {
r.ThroughTable.AddColumn(oc)
ownerColumns = append(ownerColumns, oc)
}
} else {
pk, ok := r.OwnerTable.PrimaryKey()
if !ok {
panic(fmt.Sprintf("missing owner table (%s) primary key for many to many relationship", r.OwnerTable.Name))
}
name := r.ColumnName
if name == "" {
name = r.OwnerTable.Name + "_" + pk.Name
}
nt := fkType(pk.Type)
oc := NewColumn(name, nt, append([]ColumnOption{WithReference(pk)}, opts...)...)
r.ThroughTable.AddColumn(oc)
ownerColumns = append(ownerColumns, oc)
}
if r.InversedForeignKey != nil {
r.InversedForeignKey.PrimaryTable = r.ThroughTable
r.ThroughTable.AddConstraint(r.InversedForeignKey)
for _, ic := range r.InversedForeignKey.PrimaryColumns {
r.ThroughTable.AddColumn(ic)
ownerColumns = append(ownerColumns, ic)
}
} else {
pk, ok := r.InversedTable.PrimaryKey()
if !ok {
panic(fmt.Sprintf("missing inversed table (%s) primary key for many to many relationship", r.InversedTable.Name))
}
name := r.ColumnName
if name == "" {
name = r.InversedTable.Name + "_" + pk.Name
}
nt := fkType(pk.Type)
ic := NewColumn(name, nt, append([]ColumnOption{WithReference(pk)}, opts...)...)
r.ThroughTable.AddColumn(ic)
inversedColumns = append(inversedColumns, ic)
}
r.ThroughTable.AddUnique(append(ownerColumns, inversedColumns...)...)
return t
}
// AddConstraint adds constraint to the table.
func (t *Table) AddConstraint(c *Constraint) *Table {
if t.Constraints == nil {
t.Constraints = make([]*Constraint, 0, 1)
}
c.PrimaryTable = t
t.Constraints = append(t.Constraints, c)
return t
}
// AddCheck adds check constraint to the table.
func (t *Table) AddCheck(check string, columns ...*Column) *Table {
return t.AddConstraint(Check(t, check, columns...))
}
// AddUnique adds unique constraint to the table.
func (t *Table) AddUnique(columns ...*Column) *Table {
return t.AddConstraint(Unique(t, columns...))
}
// AddIndex adds index to the table.
func (t *Table) AddIndex(columns ...*Column) *Table {
return t.AddConstraint(Index(t, columns...))
}
// AddUniqueIndex ...
func (t *Table) AddUniqueIndex(methodSuffix, where string, columns ...*Column) *Table {
return t.AddConstraint(UniqueIndex(t, methodSuffix, where, columns...))
}
// SetIfNotExists sets IfNotExists flag.
func (t *Table) SetIfNotExists(ine bool) *Table {
t.IfNotExists = ine
return t
}
// SetSchema sets schema name table belongs to.
func (t *Table) SetSchema(s *Schema) *Table {
t.Schema = s
return t
}
// PrimaryKey returns column that is primary key, or false if none.
func (t *Table) PrimaryKey() (*Column, bool) {
for _, c := range t.Columns {
if c.PrimaryKey {
return c, true
}
}
return nil, false
}
// TableOption configures how we set up the table.
type TableOption func(*Table)
// WithTableIfNotExists is table option that sets IfNotExists flag to true.
func WithTableIfNotExists() TableOption {
return func(t *Table) {
t.IfNotExists = true
}
}
// WithTemporary specified, the table is created as a temporary table.
// Temporary tables are automatically dropped at the end of a session, or optionally at the end of the current transaction (see ON COMMIT below).
// Existing permanent tables with the same name are not visible to the current session while the temporary table exists, unless they are referenced with schema-qualified names.
// Any indexes created on a temporary table are automatically temporary as well.
func WithTemporary() TableOption {
return func(t *Table) {
t.Temporary = true
}
}
// WithTableSpace pass the name of the tablespace in which the new table is to be created.
// If not specified, default_tablespace is consulted, or temp_tablespaces if the table is temporary.
func WithTableSpace(s string) TableOption {
return func(t *Table) {
t.TableSpace = s
}
}
// WithTableShortName pass the short name of the table.
func WithTableShortName(s string) TableOption {
return func(t *Table) {
t.ShortName = s
}
}
func fkType(t Type) Type {
switch t {
case TypeSerial():
return TypeInteger()
case TypeSerialBig():
return TypeIntegerBig()
case TypeSerialSmall():
return TypeIntegerSmall()
default:
return t
}
}