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.
package/index.js CHANGED
@@ -1,230 +1,206 @@
1
- const native = require('./index.node');
2
-
3
- const _internal = new WeakMap();
4
-
1
+ 'use strict';
2
+ /**
3
+ * blackhole.db: a mongoose-compatible layer on top of the LMDB store in index.node.
4
+ *
5
+ * Documents are cached in memory the first time a model is used. Reads (including lookups by
6
+ * _id and by any equality filter) are served from the cache and adaptive hash indexes; writes
7
+ * go straight to the native store, one key at a time. See README.md for the details.
8
+ */
9
+ const { EventEmitter } = require('events');
10
+ const engine = require('./lib/engine');
11
+ const ObjectId = require('./lib/objectid');
12
+ const errors = require('./lib/errors');
13
+ const S = require('./lib/schema');
14
+ const { Document } = require('./lib/document');
15
+ const { Query } = require('./lib/query');
16
+ const { buildModel, Aggregate } = require('./lib/model');
17
+
18
+ const { Schema, Types: SchemaTypes } = S;
19
+
20
+ class Session {
21
+ constructor() { this.id = new ObjectId(); this._in = false; this.hasEnded = false; }
22
+ startTransaction() { this._in = true; }
23
+ async commitTransaction() { this._in = false; }
24
+ async abortTransaction() { this._in = false; }
25
+ async endSession() { this.hasEnded = true; }
26
+ endSession_() {}
27
+ inTransaction() { return this._in; }
28
+ async withTransaction(fn) { this._in = true; try { const r = await fn(this); this._in = false; return r; } catch (e) { this._in = false; throw e; } }
29
+ }
5
30
 
6
- const blackhole = {
7
- models: {},
8
- connect: async (path = 'blackhole.db') => {
9
- native.open(path);
10
- return blackhole.connection;
11
- },
12
- createConnection: (path) => blackhole.connect(path),
13
- disconnect: async () => {},
14
- model: (name, schema) => {
15
- if (!schema) return blackhole.models[name];
16
- return blackhole.models[name] = new Model(name, schema);
17
- },
18
- Schema: class Schema {
19
- constructor(definition, options = {}) {
20
- this.obj = definition; this.options = options;
21
- this.methods = {}; this.statics = {}; this.virtuals = {};
22
- this._hooks = { pre: {}, post: {} };
23
- this.paths = {};
24
- if (definition) this.add(definition);
31
+ class Connection extends EventEmitter {
32
+ constructor(blackhole) {
33
+ super();
34
+ this.blackhole = blackhole;
35
+ this.models = {};
36
+ this.readyState = 0;
37
+ this.name = undefined;
38
+ this.host = 'localhost';
39
+ this.port = 0;
40
+ this.collections = {};
41
+ this.base = blackhole;
42
+ this.config = {};
43
+ this.id = 0;
44
+ this.events = this;
45
+ this.native = null;
46
+ this.flushMode = 'sync';
47
+ this._flushTimer = null;
48
+ this._dirty = new Set();
49
+ this._exitHook = false;
25
50
  }
26
- add(obj, prefix = '') {
27
- for (let [k, v] of Object.entries(obj)) this.paths[prefix + k] = v;
51
+ get db() { return { databaseName: this.name, collection: (n) => this.collection(n), collections: async () => Object.values(this.collections), dropDatabase: async () => this.dropDatabase() }; }
52
+ get client() { return { close: async () => this.close(), db: () => this.db }; }
53
+
54
+ model(name, schema, collection, options) {
55
+ if (schema === undefined) {
56
+ const m = this.models[name] || this.blackhole.models[name];
57
+ if (!m) { const e = new errors.blackholeError(`Schema hasn't been registered for model "${name}".\nUse blackhole.model(name, schema)`); e.name = 'MissingSchemaError'; throw e; }
58
+ return m;
59
+ }
60
+ if (typeof schema === 'string') { collection = schema; schema = undefined; }
61
+ if (!(schema instanceof Schema)) { if (schema && typeof schema === 'object') schema = new Schema(schema); else if (schema && schema.schema instanceof Schema) schema = schema.schema; }
62
+ if (this.models[name]) {
63
+ if (this.models[name].schema === schema) return this.models[name];
64
+ const e = new errors.blackholeError(`Cannot overwrite \`${name}\` model once compiled.`);
65
+ e.name = 'OverwriteModelError';
66
+ throw e;
67
+ }
68
+ for (const { fn, opts } of this.blackhole._plugins) if (!schema.plugins.some((p) => p.fn === fn)) schema.plugin(fn, opts);
69
+ const m = buildModel(this, name, schema, typeof collection === 'string' ? collection : undefined);
70
+ this.models[name] = m;
71
+ this.blackhole.models[name] = m;
72
+ this.collections[m.collection.name] = m.collection;
73
+ this.blackhole.emit('model', m);
74
+ return m;
28
75
  }
29
- path(p, v) { if (v) this.paths[p] = v; return this.paths[p]; }
30
- plugin(fn, opts) { fn(this, opts); return this; }
31
- pre(ev, fn) { (this._hooks.pre[ev] ??= []).push(fn); return this; }
32
- post(ev, fn) { (this._hooks.post[ev] ??= []).push(fn); return this; }
33
- virtual(name) {
34
- return this.virtuals[name] = {
35
- get(fn) { this.getter = fn; return this; },
36
- set(fn) { this.setter = fn; return this; }
37
- };
76
+ modelNames() { return Object.keys(this.models); }
77
+ deleteModel(name) {
78
+ for (const n of [].concat(name)) { if (n instanceof RegExp) { for (const k of Object.keys(this.models)) if (n.test(k)) delete this.models[k], delete this.blackhole.models[k]; } else { delete this.models[n]; delete this.blackhole.models[n]; } }
79
+ return this;
38
80
  }
39
- index(fields, opts) { (this._indexes ??= []).push({ fields, opts }); return this; }
40
- },
41
- Types: { ObjectId: (v) => (v != null ? String(v) : undefined), Mixed: 'Mixed' },
42
- connection: { on: () => {}, once: () => {} },
43
- set: () => {},
44
- pluralize: (v) => v
45
- };
46
-
47
- blackhole.Schema.Types = blackhole.Types;
48
-
49
- function normalizeProjection(p) {
50
- if (!p) return null;
51
- if (typeof p === 'string') {
52
- const obj = {};
53
- for (const f of p.split(/\s+/).filter(Boolean)) {
54
- if (f.startsWith('-')) obj[f.slice(1)] = 0;
55
- else obj[f] = 1;
81
+ collection(name) { return this.collections[name] || { name, collectionName: name }; }
82
+ $docsOf(name) {
83
+ const m = this.models[name] || Object.values(this.models).find((x) => x.collection.name === name);
84
+ if (!m) return [];
85
+ m.$collection.load();
86
+ return [...m.$collection.docs.values()];
56
87
  }
57
- return obj;
58
- }
59
- return p;
60
- }
61
-
62
- class Query {
63
- constructor(model, filter, op, projection) {
64
- this.model = model; this._filter = filter; this._op = op;
65
- this._limit = -1; this._skip = -1; this._sort = null; this._isLean = false;
66
- this._projection = normalizeProjection(projection);
67
- }
68
- select(p) { this._projection = normalizeProjection(p); return this; }
69
- limit(n) { this._limit = n; return this; }
70
- skip(n) { this._skip = n; return this; }
71
- sort(s) { this._sort = s; return this; }
72
- lean(v = true) { this._isLean = v; return this; }
73
-
74
- async exec() {
75
- const filter = this._op === 'findById' ? { _id: this._filter } : (this._filter || {});
76
- const raw = JSON.parse(native.find(
77
- this.model._collection,
78
- JSON.stringify(filter),
79
- JSON.stringify(this._projection || {}),
80
- JSON.stringify(this._sort || {}),
81
- this._skip,
82
- this._limit,
83
- ));
84
-
85
- if (this._op === 'findOne' || this._op === 'findById') {
86
- const res = raw[0] || null;
87
- if (!res) return null;
88
- return this._isLean ? res : this.model._wrap(res);
88
+ openUri(uri, options = {}) { return this.blackhole.connect(uri, options); }
89
+ async asPromise() { return this; }
90
+ async close() { this.flushAll(); this.readyState = 0; this.emit('close'); }
91
+ async destroy() { return this.close(); }
92
+ useDb(name) { return this; }
93
+ startSession() { return Promise.resolve(new Session()); }
94
+ transaction(fn) { return new Session().withTransaction(fn); }
95
+ async dropDatabase() { for (const m of Object.values(this.models)) await m.collection.drop(); }
96
+ async dropCollection(name) { const m = Object.values(this.models).find((x) => x.collection.name === name); if (m) await m.collection.drop(); }
97
+ async syncIndexes() { return {}; }
98
+ plugin(fn, opts) { this.blackhole.plugin(fn, opts); return this; }
99
+ scheduleFlush(col) {
100
+ this._dirty.add(col);
101
+ if (this._flushTimer) return;
102
+ this._flushTimer = setTimeout(() => { this._flushTimer = null; this.flushAll(); }, Number(this.flushDelay) || 5);
103
+ if (this._flushTimer.unref) this._flushTimer.unref();
104
+ if (!this._exitHook) { this._exitHook = true; process.on('exit', () => this.flushAll()); }
89
105
  }
90
- return this._isLean ? raw : raw.map(r => this.model._wrap(r));
91
- }
92
- then(res, rej) { return this.exec().then(res, rej); }
93
- catch(rej) { return this.exec().catch(rej); }
106
+ flushAll() { let n = 0; for (const c of this._dirty) n += c.flush(); this._dirty.clear(); return n; }
94
107
  }
95
108
 
96
- class Document {
97
- constructor(data, model) {
98
- const id = data._id != null ? String(data._id) : null;
99
-
100
- const proxy = new Proxy(this, {
101
- set: (t, p, v) => {
102
- const state = _internal.get(proxy);
103
- if (p === 'id' || p === '_id') return true;
104
- if (state) state.modified.add(p);
105
- t[p] = v; return true;
106
- }
107
- });
108
-
109
- _internal.set(proxy, { model, id, modified: new Set(), isNew: id == null });
110
-
111
- for (let [k, v] of Object.entries(data)) {
112
- if (k !== '_id' && k !== 'id') proxy[k] = v;
109
+ class Blackhole extends EventEmitter {
110
+ constructor() {
111
+ super();
112
+ this.models = {};
113
+ this._plugins = [];
114
+ this.settings = {};
115
+ this.Schema = Schema;
116
+ this.Types = {
117
+ ObjectId, Buffer, Mixed: SchemaTypes.Mixed, Array: SchemaTypes.Array, Map: SchemaTypes.Map, Decimal128: Number, Subdocument: SchemaTypes.Embedded, DocumentArray: SchemaTypes.DocumentArray, UUID: String,
118
+ };
119
+ this.SchemaTypes = SchemaTypes;
120
+ this.Document = Document;
121
+ this.Query = Query;
122
+ this.Aggregate = Aggregate;
123
+ this.VirtualType = S.VirtualType;
124
+ this.SchemaType = S.SchemaTypeMarker;
125
+ this.Mixed = SchemaTypes.Mixed;
126
+ this.ObjectId = ObjectId;
127
+ this.Error = errors.blackholeError;
128
+ this.CastError = errors.CastError;
129
+ this.mongo = { ObjectId };
130
+ this.STATES = { disconnected: 0, connected: 1, connecting: 2, disconnecting: 3, uninitialized: 99, 0: 'disconnected', 1: 'connected', 2: 'connecting', 3: 'disconnecting', 99: 'uninitialized' };
131
+ this.version = '8.0.0-blackhole';
132
+ this.connection = new Connection(this);
133
+ this.connections = [this.connection];
134
+ this.optimized = true;
135
+ Schema.Types.ObjectId = SchemaTypes.ObjectId;
136
+ this.Schema.Types = SchemaTypes;
137
+ this.Model = Object.getPrototypeOf(Object);
138
+ this.pluralize = (v) => v;
113
139
  }
114
140
 
115
- for (let [n, f] of Object.entries(model.schema.methods)) this[n] = f.bind(proxy);
116
- return proxy;
117
- }
118
-
119
- get id() { return _internal.get(this).id; }
120
- get _id() { return _internal.get(this).id; }
121
-
122
- async save() {
123
- const state = _internal.get(this);
124
- await state.model._runHooks('pre', 'save', this);
125
- const data = this.toObject();
126
- const id = native.save(state.model._collection, state.id || '', JSON.stringify(data));
127
- state.id = id;
128
- state.isNew = false;
129
- state.modified.clear();
130
- await state.model._runHooks('post', 'save', this);
131
- return this;
132
- }
133
-
134
- async updateOne(u) { Object.assign(this, u); return this.save(); }
135
- async deleteOne() {
136
- const state = _internal.get(this);
137
- return native.delete_by_id(state.model._collection, state.id);
138
- }
139
- isModified(p) { return _internal.get(this).modified.has(p); }
140
- markModified(p) { _internal.get(this).modified.add(p); }
141
- validate() { return true; }
142
-
143
- toObject() {
144
- const o = { ...this };
145
- for (let k in o) if (typeof o[k] === 'function') delete o[k];
146
- return JSON.parse(JSON.stringify(o));
147
- }
148
-
149
- toJSON() {
150
- const o = this.toObject();
151
- o.id = this.id;
152
- const { model } = _internal.get(this);
153
- for (let [n, v] of Object.entries(model.schema.virtuals)) {
154
- if (v.getter) o[n] = v.getter.call(this);
141
+ _native() {
142
+ const conn = this.connection;
143
+ if (!conn.native) conn.native = this._loadNative();
144
+ return conn.native;
155
145
  }
156
- return o;
157
- }
158
- }
159
-
160
- class Model {
161
- constructor(name, schema) {
162
- this.name = name; this.schema = schema; this._collection = name;
163
- Object.assign(this, schema.statics);
164
- }
165
- _wrap(raw) { return new Document(raw, this); }
166
- async _runHooks(p, e, d) { for (let f of this.schema._hooks[p][e] ?? []) await f.call(d); }
167
-
168
- async create(data) {
169
- if (Array.isArray(data)) return Promise.all(data.map(d => this.create(d)));
170
- const doc = new Document(data, this);
171
- return doc.save();
172
- }
173
- async insertMany(arr) { return this.create(arr); }
174
-
175
- find(f, projection) { return new Query(this, f, 'find', projection); }
176
- findOne(f, projection) { return new Query(this, f, 'findOne', projection); }
177
- findById(id, projection) { return new Query(this, id, 'findById', projection); }
178
- async countDocuments(f) { return native.count(this._collection, JSON.stringify(f || {})); }
179
- async distinct(field) {
180
- const all = await this.find({}).lean();
181
- return [...new Set(all.map(x => x[field]))];
182
- }
183
-
184
- async updateOne(f, u) {
185
- const d = await this.findOne(f).exec();
186
- if (!d) return { matchedCount: 0 };
187
- Object.assign(d, u); await d.save();
188
- return { matchedCount: 1 };
189
- }
190
- async updateMany(f, u) {
191
- const ds = await this.find(f).exec();
192
- for (let d of ds) { Object.assign(d, u); await d.save(); }
193
- return { matchedCount: ds.length };
194
- }
195
- async findOneAndUpdate(f, u, opts = {}) {
196
- const d = await this.findOne(f).exec();
197
- if (!d) return opts.upsert ? this.create({ ...f, ...u }) : null;
198
- Object.assign(d, u); return d.save();
199
- }
200
- findByIdAndUpdate(id, u, o) { return this.findOneAndUpdate({ _id: id }, u, o); }
201
-
202
- async deleteOne(f) {
203
- const d = await this.findOne(f).exec();
204
- if (!d) return { deletedCount: 0 };
205
- await d.deleteOne(); return { deletedCount: 1 };
206
- }
207
- async deleteMany(f) {
208
- const ds = await this.find(f).exec();
209
- for (let d of ds) await d.deleteOne();
210
- return { deletedCount: ds.length };
211
- }
212
- async findOneAndDelete(f) {
213
- const d = await this.findOne(f).exec();
214
- if (d) await d.deleteOne(); return d;
215
- }
216
- findByIdAndDelete(id) { return this.findOneAndDelete({ _id: id }); }
217
-
218
- async aggregate(pipeline) {
219
- const raw = native.aggregate(this._collection, JSON.stringify(pipeline || []));
220
- return JSON.parse(raw);
221
- }
222
- async bulkWrite(ops) {
223
- for (let o of ops) {
224
- if (o.insertOne) await this.create(o.insertOne.document);
225
- if (o.deleteOne) await this.deleteOne(o.deleteOne.filter);
146
+ _loadNative() {
147
+ if (this._nativeOverride) return this._nativeOverride;
148
+ return require('./index.node');
149
+ }
150
+ /** Replace the native storage (tests use an in-memory implementation). */
151
+ setNative(impl) { this._nativeOverride = impl; this.connection.native = impl; return this; }
152
+
153
+ async connect(uri = 'blackhole.db', options = {}) {
154
+ let path = uri;
155
+ if (typeof uri === 'object' && uri !== null) { options = uri; path = options.dbName || 'blackhole.db'; }
156
+ else if (/^mongodb(\+srv)?:\/\//.test(String(uri))) { const seg = String(uri).split('?')[0].split('/').pop(); path = options.dbName || seg || 'blackhole.db'; }
157
+ const conn = this.connection;
158
+ conn.readyState = 2;
159
+ const native = this._native();
160
+ native.open(path);
161
+ conn.name = String(path).split(/[\\/]/).pop();
162
+ conn.readyState = 1;
163
+ if (options.flushMode) conn.flushMode = options.flushMode;
164
+ setImmediate(() => { conn.emit('connecting'); conn.emit('connected'); conn.emit('open'); });
165
+ return this;
166
+ }
167
+ createConnection(uri, options) {
168
+ // All connections share the single database that was opened.
169
+ const c = new Connection(this);
170
+ c.native = this.connection.native;
171
+ c.blackhole = this;
172
+ c.readyState = 1;
173
+ c.models = this.connection.models;
174
+ const p = Promise.resolve(c).then(() => { if (uri && !c.native) { this.connection.native = this._native(); this.connection.native.open(typeof uri === 'string' ? uri : 'blackhole.db'); c.native = this.connection.native; } return c; });
175
+ c.then = p.then.bind(p); c.catch = p.catch.bind(p);
176
+ return c;
226
177
  }
227
- }
178
+ async disconnect() { await this.connection.close(); }
179
+ get disconnect_() { return undefined; }
180
+ model(name, schema, collection, options) { return this.connection.model(name, schema, collection, options); }
181
+ modelNames() { return this.connection.modelNames(); }
182
+ deleteModel(name) { this.connection.deleteModel(name); return this; }
183
+ plugin(fn, opts) { this._plugins.push({ fn, opts }); return this; }
184
+ set(key, value) { if (arguments.length === 1) return this.settings[key]; this.settings[key] = value; if (key === 'flushMode') this.connection.flushMode = value; return this; }
185
+ get(key) { return this.settings[key]; }
186
+ isValidObjectId(v) { return v !== null && v !== undefined && (v instanceof ObjectId || ObjectId.isValid(v) || (typeof v === 'string' && v.length === 12)); }
187
+ isObjectIdOrHexString(v) { return v instanceof ObjectId || (typeof v === 'string' && /^[0-9a-fA-F]{24}$/.test(v)); }
188
+ startSession() { return this.connection.startSession(); }
189
+ syncIndexes() { return Promise.resolve({}); }
190
+ createCollection() { return Promise.resolve(); }
191
+ /** Write any queued writes now (only needed when flushMode is "async"). */
192
+ flush() { return this.connection.flushAll(); }
193
+ sanitizeFilter(f) { return f; }
194
+ trusted(o) { return o; }
195
+ skipMiddlewareFunction() { return undefined; }
196
+ overwriteMiddlewareResult(v) { return v; }
228
197
  }
229
198
 
199
+ const blackhole = new Blackhole();
200
+ Object.defineProperty(blackhole, 'Model', { value: Document });
201
+ blackhole.default = blackhole;
202
+ blackhole.Blackhole = Blackhole;
203
+ blackhole.blackhole = blackhole;
204
+ blackhole.engine = engine;
205
+ blackhole.Error = errors.blackholeError;
230
206
  module.exports = blackhole;