-
Notifications
You must be signed in to change notification settings - Fork 6
/
collection.go
127 lines (109 loc) · 2.47 KB
/
collection.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
package y
import (
"log"
"reflect"
)
type index struct {
cells map[int64][]int
keys []int64
}
func (idx *index) add(key int64, cell int) {
cells, ok := idx.cells[key]
if !ok {
idx.keys = append(idx.keys, key)
}
idx.cells[key] = append(cells, cell)
}
func makeIndex() *index {
return &index{
cells: make(map[int64][]int),
}
}
// Collection contains items and indexes
type Collection struct {
items []reflect.Value
idx map[string]*index
schema
}
func (c *Collection) lookidx(name string) *index {
idx, ok := c.idx[name]
if !ok {
log.Panicf(
"y/collection: The index \"%s\" not found in collection \"%s\".",
name, c.table)
}
return idx
}
func (c *Collection) add(v value) {
cell := len(c.items)
c.items = append(c.items, v.addr())
for name := range c.schema.xinfo.idx {
key := c.schema.fval(v, name).Int()
c.lookidx(name).add(key, cell)
}
}
func (c *Collection) cells(cells []int) []reflect.Value {
items := make([]reflect.Value, len(cells))
for i, cell := range cells {
items[i] = c.items[cell]
}
return items
}
// Empty returns false if no items exist
func (c *Collection) Empty() bool {
return c.Size() == 0
}
// First returns the first item
func (c *Collection) First() interface{} {
return c.items[0].Interface()
}
// Size returns count of items
func (c *Collection) Size() int {
return len(c.items)
}
// List returns all items
func (c *Collection) List() interface{} {
size := c.Size()
items := reflect.MakeSlice(c.schema.sliceOf(), size, size)
for i, item := range c.items {
items.Index(i).Set(item)
}
return items.Interface()
}
// Join links related collection
func (c *Collection) Join(j *Collection) {
fk := j.schema.fk(c.schema)
cidx := c.lookidx(fk.target)
jidx := j.lookidx(fk.from)
name := j.schema.t.Name()
for jkey, jcells := range jidx.cells {
if ccells, ok := cidx.cells[jkey]; ok {
for _, ccell := range ccells {
citem := c.items[ccell].Elem()
// one-to-many
target := citem.FieldByName(name + "Array")
if target.CanSet() {
items := j.cells(jcells)
target.Set(reflect.Append(target, items...))
continue
}
// one-to-one
target = citem.FieldByName(name)
if target.CanSet() && len(jcells) == 1 {
target.Set(j.items[jcells[0]])
}
}
}
}
}
func makeCollection(p *Proxy) *Collection {
// create the index map
idx := make(map[string]*index)
for name := range p.schema.xinfo.idx {
idx[name] = makeIndex()
}
return &Collection{
idx: idx,
schema: p.schema,
}
}