forked from ccorcos/tuple-database
-
Notifications
You must be signed in to change notification settings - Fork 3
/
endUserDatabase.test.ts
211 lines (182 loc) · 5.08 KB
/
endUserDatabase.test.ts
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
import { describe, it, expect } from "bun:test"
import { transactionalReadWrite } from "../database/sync/transactionalReadWrite"
import { TupleDatabase } from "../database/sync/TupleDatabase"
import { TupleDatabaseClient } from "../database/sync/TupleDatabaseClient"
import { compareTuple } from "../helpers/compareTuple"
import { ReadOnlyTupleDatabaseClientApi, SchemaSubspace } from "../main"
import { InMemoryTupleStorage } from "../storage/InMemoryTupleStorage"
import {
$,
evaluateQuery,
Fact,
Query,
substituteBinding,
TriplestoreSchema,
Value,
writeFact,
} from "./triplestore"
// We're going to build off of the triplestore example.
// So read triplestore.ts and triplestore.test.ts first.
type Obj = { id: string; [key: string]: Value | Value[] }
// Represent objects that we're typically used to as triples.
function objectToFacts(obj: Obj) {
const facts: Fact[] = []
const { id, ...rest } = obj
for (const [key, value] of Object.entries(rest)) {
if (Array.isArray(value)) {
for (const item of value) {
facts.push([id, key, item])
}
} else {
facts.push([id, key, value])
}
}
facts.sort(compareTuple)
return facts
}
describe("objectToFacts", () => {
it("works", () => {
expect(
objectToFacts({
id: "1",
name: "Chet",
age: 31,
tags: ["engineer", "musician"],
})
).toEqual([
["1", "age", 31],
["1", "name", "Chet"],
["1", "tags", "engineer"],
["1", "tags", "musician"],
])
})
})
// A user-defined query filters objects based on 1 or more properties.
type UserFilter = { id: string; [prop: string]: Value }
function userFilterToQuery(filter: UserFilter): Query {
const { id, ...props } = filter
return Object.entries(props).map(([a, v]) => [$("id"), a, v])
}
type Schema =
| SchemaSubspace<["data"], TriplestoreSchema>
// A list of user-defined filters.
| { key: ["filter", string]; value: UserFilter }
// And index for all objects ids that pass the filter.
| { key: ["index", string, string]; value: null }
const reindexFact = transactionalReadWrite<Schema>()((tx, fact: Fact) => {
const [e, a, v] = fact
// Get all the user-defined filters.
const filters = tx.scan({ prefix: ["filter"] }).map(({ value }) => value)
// Add this object id to the index if it passes the filter.
filters.forEach((filter) => {
// For performance, let's check some trivial cases:
// This fact is irrelevant to the filter.
if (!(a in filter)) {
return
}
// This fact directly breaks the filter.
if (v !== filter[a]) {
tx.remove(["index", filter.id, e])
return
}
// Evaluate if this object passes the whole filter:
const query = userFilterToQuery(filter)
const testQuery = substituteBinding(query, { id: e })
const result = evaluateQuery(tx.subspace(["data"]), testQuery)
if (result.length === 0) {
tx.remove(["index", filter.id, e])
} else {
tx.set(["index", filter.id, e], null)
}
})
})
const writeObjectFact = transactionalReadWrite<Schema>()((tx, fact: Fact) => {
writeFact(tx.subspace(["data"]), fact)
reindexFact(tx, fact)
})
const writeObject = transactionalReadWrite<Schema>()((tx, obj: Obj) => {
for (const fact of objectToFacts(obj)) {
writeObjectFact(tx, fact)
}
})
const createFilter = transactionalReadWrite<Schema>()(
(tx, filter: UserFilter) => {
tx.set(["filter", filter.id], filter)
// Evaluate the filter.
const query = userFilterToQuery(filter)
const ids = evaluateQuery(tx.subspace(["data"]), query).map(
({ id }) => id as string
)
// Write those ids to the index.
ids.forEach((id) => {
tx.set(["index", filter.id, id], null)
})
}
)
function readFilterIndex(
db: ReadOnlyTupleDatabaseClientApi<Schema>,
filterId: string
) {
return db.scan({ prefix: ["index", filterId] }).map(({ key }) => key[2])
}
describe("End-user Database", () => {
it("works", () => {
// Lets try it out.
const db = new TupleDatabaseClient<Schema>(
new TupleDatabase(new InMemoryTupleStorage())
)
writeObject(db, {
id: "person1",
name: "Chet",
age: 31,
tags: ["engineer", "musician"],
})
writeObject(db, {
id: "person2",
name: "Meghan",
age: 30,
tags: ["engineer", "botanist"],
})
writeObject(db, {
id: "person3",
name: "Saul",
age: 31,
tags: ["musician"],
})
writeObject(db, {
id: "person4",
name: "Tanishq",
age: 22,
tags: [],
})
// Create a filter with only one property.
createFilter(db, { id: "filter1", tags: "engineer" })
expect(readFilterIndex(db, "filter1")).toEqual(["person1", "person2"])
// Test that this filter gets maintained.
writeObjectFact(db, ["person4", "tags", "engineer"])
expect(readFilterIndex(db, "filter1")).toEqual([
"person1",
"person2",
"person4",
])
// Lets create a filter with two properties.
createFilter(db, {
id: "filter2",
tags: "musician",
age: 31,
})
expect(readFilterIndex(db, "filter2")).toEqual(["person1", "person3"])
// Test that this filter gets maintained.
writeObject(db, {
id: "person5",
name: "Sean",
age: 31,
tags: ["musician", "botanist"],
})
expect(readFilterIndex(db, "filter2")).toEqual([
"person1",
"person3",
"person5",
])
})
})