forked from slicebit/qb
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmetadata.go
85 lines (69 loc) · 1.68 KB
/
metadata.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
package qb
import (
"errors"
"fmt"
)
// MetaData creates a new MetaData object and returns it as a pointer
func MetaData() *MetaDataElem {
return &MetaDataElem{
tables: []TableElem{},
}
}
// MetaDataElem is the container for database structs and tables
type MetaDataElem struct {
tables []TableElem
}
// AddTable appends table to tables slice
func (m *MetaDataElem) AddTable(table TableElem) {
m.tables = append(m.tables, table)
}
// Table returns the metadata registered table object. It returns nil if table is not found
func (m *MetaDataElem) Table(name string) TableElem {
for _, t := range m.tables {
if t.Name == name {
return t
}
}
panic(fmt.Errorf("Table %s not found", name))
}
// Tables returns the current tables slice
func (m *MetaDataElem) Tables() []TableElem {
return m.tables
}
// CreateAll creates all the tables added to metadata
func (m *MetaDataElem) CreateAll(engine *Engine) error {
tx, err := engine.DB().Begin()
if err != nil {
return err
}
for _, t := range m.tables {
_, err = tx.Exec(t.Create(engine.Dialect()))
if err != nil {
return err
}
}
err = tx.Commit()
if len(m.tables) == 0 {
return errors.New("Metadata is empty. You need to register tables by calling db.AddTable(model{})")
}
return err
}
// DropAll drops all the tables which is added to metadata
func (m *MetaDataElem) DropAll(engine *Engine) error {
tx, err := engine.DB().Begin()
if err != nil {
return err
}
for i := len(m.tables) - 1; i >= 0; i-- {
drop := m.tables[i].Drop(engine.Dialect())
_, err = tx.Exec(drop)
if err != nil {
return err
}
}
err = tx.Commit()
if len(m.tables) == 0 {
return errors.New("Metadata is empty")
}
return err
}