blackhole.db 2.0.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,299 @@
1
+ 'use strict';
2
+ // In-memory collection backed by the native LMDB store.
3
+ //
4
+ // Reads never touch the native layer after the first load: documents live in a Map keyed by
5
+ // _id, so lookups by _id are O(1) and every other equality lookup uses a hash index that is
6
+ // built the first time a path is queried and then kept up to date on every write. Writes
7
+ // go to the native store one key at a time (native.save / native.delete_by_id), which is
8
+ // O(1) in the size of the database.
9
+ const engine = require('./engine');
10
+ const ObjectId = require('./objectid');
11
+ const { DuplicateKeyError } = require('./errors');
12
+ const { serialize } = require('./schema');
13
+
14
+ const AUTO_INDEX_MIN_DOCS = 48;
15
+ const MAX_AUTO_INDEXES = 24;
16
+
17
+ const idKey = (id) => String(id);
18
+
19
+ function valueKey(v) {
20
+ if (v === null || v === undefined) return 'z';
21
+ switch (typeof v) {
22
+ case 'string': return `s${v}`;
23
+ case 'number': return `n${v}`;
24
+ case 'boolean': return `b${v}`;
25
+ default:
26
+ }
27
+ if (v instanceof ObjectId) return `s${v._hex}`;
28
+ if (v instanceof Date) return `d${v.getTime()}`;
29
+ return undefined; // objects are not indexable
30
+ }
31
+
32
+ function indexKeys(doc, path) {
33
+ const out = [];
34
+ for (const v of engine.values(doc, path)) {
35
+ if (Array.isArray(v)) for (const el of v) { const k = valueKey(el); if (k !== undefined) out.push(k); }
36
+ else { const k = valueKey(v); if (k !== undefined) out.push(k); }
37
+ }
38
+ if (out.length === 0) out.push('z');
39
+ return out;
40
+ }
41
+
42
+ class Collection {
43
+ constructor(name, db) {
44
+ this.name = name;
45
+ this.collectionName = name;
46
+ this.db = db;
47
+ this.docs = new Map(); // idKey -> plain document (hydrated)
48
+ this.seq = new Map(); // idKey -> insertion number (natural order for indexed lookups)
49
+ this.counter = 0;
50
+ this.loaded = false;
51
+ this.hydrate = null; // set by the model: raw JSON object -> hydrated object
52
+ this.indexes = new Map(); // path -> Map(valueKey -> Set(idKey))
53
+ this.uniques = []; // { fields: [paths], sparse, map: Map(key -> idKey), name }
54
+ this.pending = null; // async flush queue
55
+ this.queryCounts = new Map();
56
+ }
57
+
58
+ get size() { this.load(); return this.docs.size; }
59
+
60
+ load() {
61
+ if (this.loaded) return;
62
+ this.loaded = true;
63
+ const native = this.db.native;
64
+ if (!native) throw new Error('blackhole.db: the native module is not loaded');
65
+ const raw = native.find(this.name, '{}', '{}', '{}', -1, -1);
66
+ const rows = JSON.parse(raw);
67
+ for (const row of rows) {
68
+ const doc = this.hydrate ? this.hydrate(row) : row;
69
+ const k = idKey(doc._id);
70
+ this.docs.set(k, doc);
71
+ this.seq.set(k, this.counter++);
72
+ }
73
+ for (const u of this.uniques) this.rebuildUnique(u);
74
+ }
75
+
76
+ // ----- unique indexes -----
77
+ addUnique(fields, opts = {}) {
78
+ const paths = Object.keys(fields);
79
+ const sig = paths.join(',');
80
+ if (this.uniques.some((u) => u.sig === sig)) return;
81
+ const u = { fields: paths, sig, sparse: !!opts.sparse, partial: opts.partialFilterExpression, map: new Map(), name: `${paths.join('_')}_1` };
82
+ this.uniques.push(u);
83
+ if (this.loaded) this.rebuildUnique(u);
84
+ }
85
+
86
+ uniqueKeyOf(u, doc) {
87
+ if (u.partial && !engine.matches(doc, u.partial)) return undefined;
88
+ const parts = [];
89
+ let allMissing = true;
90
+ for (const f of u.fields) {
91
+ const v = engine.getPath(doc, f);
92
+ if (v !== undefined && v !== null) allMissing = false;
93
+ const k = valueKey(Array.isArray(v) ? JSON.stringify(v) : v);
94
+ parts.push(k === undefined ? JSON.stringify(v) : k);
95
+ }
96
+ if (u.sparse && allMissing) return undefined;
97
+ return parts.join('\u0001');
98
+ }
99
+
100
+ rebuildUnique(u) {
101
+ u.map.clear();
102
+ for (const [k, doc] of this.docs) { const uk = this.uniqueKeyOf(u, doc); if (uk !== undefined && !u.map.has(uk)) u.map.set(uk, k); }
103
+ }
104
+
105
+ checkUnique(doc, selfKey) {
106
+ for (const u of this.uniques) {
107
+ const uk = this.uniqueKeyOf(u, doc);
108
+ if (uk === undefined) continue;
109
+ const holder = u.map.get(uk);
110
+ if (holder !== undefined && holder !== selfKey) {
111
+ const keyValue = {};
112
+ for (const f of u.fields) keyValue[f] = engine.getPath(doc, f) === undefined ? null : engine.getPath(doc, f);
113
+ const keyPattern = {};
114
+ for (const f of u.fields) keyPattern[f] = 1;
115
+ throw new DuplicateKeyError(this.name, keyPattern, keyValue);
116
+ }
117
+ }
118
+ }
119
+
120
+ // ----- secondary hash indexes -----
121
+ ensureIndex(path) {
122
+ let idx = this.indexes.get(path);
123
+ if (idx) return idx;
124
+ if (this.indexes.size >= MAX_AUTO_INDEXES) return null;
125
+ idx = new Map();
126
+ for (const [k, doc] of this.docs) for (const key of indexKeys(doc, path)) { let s = idx.get(key); if (!s) idx.set(key, s = new Set()); s.add(k); }
127
+ this.indexes.set(path, idx);
128
+ return idx;
129
+ }
130
+
131
+ indexAdd(k, doc) {
132
+ for (const [path, idx] of this.indexes) for (const key of indexKeys(doc, path)) { let s = idx.get(key); if (!s) idx.set(key, s = new Set()); s.add(k); }
133
+ for (const u of this.uniques) { const uk = this.uniqueKeyOf(u, doc); if (uk !== undefined) u.map.set(uk, k); }
134
+ }
135
+
136
+ indexRemove(k, doc) {
137
+ for (const [path, idx] of this.indexes) for (const key of indexKeys(doc, path)) { const s = idx.get(key); if (s) { s.delete(k); if (!s.size) idx.delete(key); } }
138
+ for (const u of this.uniques) { const uk = this.uniqueKeyOf(u, doc); if (uk !== undefined && u.map.get(uk) === k) u.map.delete(uk); }
139
+ }
140
+
141
+ // ----- query planning -----
142
+ // Returns an array of idKeys that may match, or null when a full scan is required.
143
+ plan(filter) {
144
+ const conds = [];
145
+ const collect = (f) => {
146
+ for (const key of Object.keys(f)) {
147
+ const c = f[key];
148
+ if (key === '$and') { for (const sub of c) collect(sub); continue; }
149
+ if (key[0] === '$') continue;
150
+ conds.push([key, c]);
151
+ }
152
+ };
153
+ collect(filter);
154
+ let best = null;
155
+ for (const [path, cond] of conds) {
156
+ let keys;
157
+ if (cond instanceof RegExp) continue;
158
+ if (engine.isOpObject(cond)) {
159
+ if ('$eq' in cond && Object.keys(cond).length === 1) keys = [valueKey(cond.$eq)];
160
+ else if (Array.isArray(cond.$in) && cond.$in.every((x) => !(x instanceof RegExp))) keys = cond.$in.map(valueKey);
161
+ else continue;
162
+ } else if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !(cond instanceof ObjectId)) continue;
163
+ else keys = [valueKey(cond)];
164
+ if (keys.some((x) => x === undefined)) continue;
165
+ if (path === '_id') {
166
+ const ids = [];
167
+ for (const k of keys) { const hex = k.slice(1); if (this.docs.has(hex)) ids.push(hex); }
168
+ return ids;
169
+ }
170
+ if (this.docs.size < AUTO_INDEX_MIN_DOCS) continue;
171
+ const idx = this.ensureIndex(path);
172
+ if (!idx) continue;
173
+ const ids = new Set();
174
+ for (const k of keys) { const s = idx.get(k); if (s) for (const x of s) ids.add(x); }
175
+ if (!best || ids.size < best.size) best = ids;
176
+ if (best.size === 0) break;
177
+ }
178
+ if (!best) return null;
179
+ const arr = [...best];
180
+ if (arr.length > 1) arr.sort((a, b) => this.seq.get(a) - this.seq.get(b));
181
+ return arr;
182
+ }
183
+
184
+ // Lazily yields matching documents in natural order.
185
+ *scan(filter) {
186
+ this.load();
187
+ const empty = !filter || Object.keys(filter).length === 0;
188
+ if (empty) { yield* this.docs.values(); return; }
189
+ const ids = this.plan(filter);
190
+ if (ids) {
191
+ for (const k of ids) { const d = this.docs.get(k); if (d && engine.matches(d, filter)) yield d; }
192
+ return;
193
+ }
194
+ for (const d of this.docs.values()) if (engine.matches(d, filter)) yield d;
195
+ }
196
+
197
+ // ----- reads -----
198
+ getById(id) { this.load(); return this.docs.get(idKey(id)); }
199
+
200
+ find(filter, { sort, skip = 0, limit = 0 } = {}) {
201
+ const hasSort = sort && engine.normalizeSort(sort).length > 0;
202
+ if (!hasSort) {
203
+ const out = [];
204
+ let seen = 0;
205
+ for (const d of this.scan(filter)) {
206
+ if (seen++ < skip) continue;
207
+ out.push(d);
208
+ if (limit > 0 && out.length >= limit) break;
209
+ }
210
+ return out;
211
+ }
212
+ let all = [...this.scan(filter)];
213
+ engine.sortDocs(all, sort);
214
+ if (skip) all = all.slice(skip);
215
+ if (limit > 0) all = all.slice(0, limit);
216
+ return all;
217
+ }
218
+
219
+ findOne(filter, sort) {
220
+ if (sort && engine.normalizeSort(sort).length) return this.find(filter, { sort, limit: 1 })[0] || null;
221
+ for (const d of this.scan(filter)) return d;
222
+ return null;
223
+ }
224
+
225
+ count(filter) {
226
+ this.load();
227
+ if (!filter || Object.keys(filter).length === 0) return this.docs.size;
228
+ let n = 0;
229
+ for (const _ of this.scan(filter)) n++;
230
+ return n;
231
+ }
232
+
233
+ // ----- writes -----
234
+ insert(doc) {
235
+ this.load();
236
+ const k = idKey(doc._id);
237
+ if (this.docs.has(k)) {
238
+ throw new DuplicateKeyError(this.name, { _id: 1 }, { _id: doc._id });
239
+ }
240
+ this.checkUnique(doc, k);
241
+ this.docs.set(k, doc);
242
+ this.seq.set(k, this.counter++);
243
+ this.indexAdd(k, doc);
244
+ this.persist(k, doc);
245
+ return doc;
246
+ }
247
+
248
+ // Replaces the stored document (same _id).
249
+ replace(doc, previous) {
250
+ const k = idKey(doc._id);
251
+ const old = previous || this.docs.get(k);
252
+ this.checkUnique(doc, k);
253
+ if (old) this.indexRemove(k, old);
254
+ this.docs.set(k, doc);
255
+ if (!this.seq.has(k)) this.seq.set(k, this.counter++);
256
+ this.indexAdd(k, doc);
257
+ this.persist(k, doc);
258
+ return doc;
259
+ }
260
+
261
+ remove(id) {
262
+ this.load();
263
+ const k = idKey(id);
264
+ const old = this.docs.get(k);
265
+ if (!old) return false;
266
+ this.indexRemove(k, old);
267
+ this.docs.delete(k);
268
+ this.seq.delete(k);
269
+ this.persist(k, null);
270
+ return true;
271
+ }
272
+
273
+ // ----- persistence -----
274
+ persist(k, doc) {
275
+ if (this.db.flushMode === 'async') {
276
+ if (!this.pending) this.pending = new Map();
277
+ this.pending.set(k, doc);
278
+ this.db.scheduleFlush(this);
279
+ return;
280
+ }
281
+ this.write(k, doc);
282
+ }
283
+
284
+ write(k, doc) {
285
+ const native = this.db.native;
286
+ if (doc === null) native.delete_by_id(this.name, k);
287
+ else native.save(this.name, k, serialize(doc));
288
+ }
289
+
290
+ flush() {
291
+ if (!this.pending) return 0;
292
+ const jobs = this.pending;
293
+ this.pending = null;
294
+ for (const [k, doc] of jobs) this.write(k, doc);
295
+ return jobs.size;
296
+ }
297
+ }
298
+
299
+ module.exports = { Collection, valueKey, idKey };