-
Notifications
You must be signed in to change notification settings - Fork 5
/
database.go
109 lines (89 loc) · 2.13 KB
/
database.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
package pivot
import (
"fmt"
"github.com/ghetzel/pivot/v3/backends"
"github.com/ghetzel/pivot/v3/dal"
"github.com/ghetzel/pivot/v3/mapper"
)
type DB interface {
backends.Backend
AttachCollection(*Collection) Model
C(string) *Collection
Migrate() error
Models() []Model
ApplySchemata(fileOrDirPath string) error
LoadFixtures(fileOrDirPath string) error
GetBackend() Backend
SetBackend(Backend)
}
type schemaModel struct {
Collection *dal.Collection
Model Model
}
func (self *schemaModel) String() string {
if self.Collection != nil {
return self.Collection.Name
} else {
return ``
}
}
type db struct {
backends.Backend
models []*schemaModel
}
func newdb(backend backends.Backend) *db {
return &db{
Backend: backend,
models: make([]*schemaModel, 0),
}
}
func (self *db) GetBackend() Backend {
return self.Backend
}
func (self *db) SetBackend(backend Backend) {
self.Backend = backend
}
// A version of GetCollection that panics if the collection does not exist.
func (self *db) C(name string) *Collection {
if collection, err := self.GetCollection(name); err == nil {
return collection
} else {
panic("C(" + name + "): " + err.Error())
}
}
func (self *db) AttachCollection(collection *Collection) Model {
if collection == nil {
panic("cannot attach nil Collection")
}
for _, sm := range self.models {
if sm.String() == collection.Name {
panic(fmt.Sprintf("Collection %q is already registered", collection.Name))
}
}
sm := &schemaModel{
Collection: collection,
Model: mapper.NewModel(self, collection),
}
self.models = append(self.models, sm)
return sm.Model
}
func (self *db) Migrate() error {
for _, sm := range self.models {
if err := sm.Model.Migrate(); err != nil {
return fmt.Errorf("failed to migrate %v: %v", sm, err)
}
}
return nil
}
func (self *db) Models() (models []Model) {
for _, sm := range self.models {
models = append(models, sm.Model)
}
return
}
func (self *db) ApplySchemata(fileOrDirPath string) error {
return ApplySchemata(fileOrDirPath, self)
}
func (self *db) LoadFixtures(fileOrDirPath string) error {
return LoadFixtures(fileOrDirPath, self)
}