-
Notifications
You must be signed in to change notification settings - Fork 4
/
lockingdb.go
97 lines (80 loc) · 1.93 KB
/
lockingdb.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
package gotalog
import (
"fmt"
"sync"
)
type lockingClauseStore map[string]*clause
func (store lockingClauseStore) clauses() []*clause {
clauses := make([]*clause, len(store))
i := 0
for _, c := range store {
clauses[i] = c
i = i + 1
}
return clauses
}
type lockingDatabase struct {
predicates map[string]*predicate
clauses map[string]lockingClauseStore
m sync.RWMutex
}
// NewLockingDatabase constructs a new in-memory database with simple locking behavior.
func NewLockingDatabase() Database {
return &lockingDatabase{
predicates: make(map[string]*predicate),
clauses: make(map[string]lockingClauseStore),
}
}
func (db *lockingDatabase) newPredicate(n string, a int) *predicate {
id := predicateID(n, a)
db.m.RLock()
if existing, ok := db.predicates[id]; ok {
db.m.RUnlock()
return existing
}
db.m.RUnlock()
p := &predicate{
Name: n,
Arity: a,
primitive: nil,
id: id,
}
p.clauses = func() []*clause {
db.m.RLock()
defer db.m.RUnlock()
return db.clauses[p.id].clauses()
}
db.m.Lock()
db.predicates[p.id] = p
db.clauses[p.id] = lockingClauseStore{}
db.m.Unlock()
return p
}
// assertions should only be made for clauses' whose
// predicates originate within the same database.
func (db *lockingDatabase) assert(c *clause) error {
if !isSafe(c) {
return fmt.Errorf("cannot assert unsafe clauses")
}
pred := c.head.pred
// Ignore assertions on primitive predicates
if pred.primitive != nil {
return fmt.Errorf("cannot assert on primitive predicates")
}
db.m.Lock()
db.clauses[pred.id][c.getID()] = c
db.m.Unlock()
return nil
}
func (db *lockingDatabase) retract(c *clause) error {
pred := c.head.pred
db.m.Lock()
delete(db.clauses[pred.id], c.getID())
// If a predicate has no clauses associated with it, remove it from the db.
if len(db.clauses[pred.id]) == 0 {
delete(db.predicates, pred.id)
delete(db.clauses, pred.id)
}
defer db.m.Unlock()
return nil
}