mm_datas 0.0.0-stage → 5.3.0
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/example/custom_demo.js +237 -0
- package/example/model/item_model.json +46 -0
- package/example/model/map_model.json +53 -0
- package/example/model/player_model.json +65 -0
- package/example/model/role_model.json +61 -0
- package/example/model/skill_model.json +60 -0
- package/example/preset_demo.js +44 -0
- package/example/rpg_cache.js +179 -0
- package/example/rpg_crud.js +170 -0
- package/example/rpg_demo.js +61 -0
- package/example/rpg_model/bag_model.json +74 -0
- package/example/rpg_model/character_model.json +165 -0
- package/example/rpg_model/character_skill_model.json +61 -0
- package/example/rpg_model/drop_model.json +103 -0
- package/example/rpg_model/item_model.json +189 -0
- package/example/rpg_model/job_model.json +96 -0
- package/example/rpg_model/level_exp_model.json +111 -0
- package/example/rpg_model/map_model.json +166 -0
- package/example/rpg_model/map_state_model.json +63 -0
- package/example/rpg_model/monster_model.json +115 -0
- package/example/rpg_model/npc_model.json +103 -0
- package/example/rpg_model/quest_model.json +106 -0
- package/example/rpg_model/quest_progress_model.json +61 -0
- package/example/rpg_model/save_model.json +42 -0
- package/example/rpg_model/skill_model.json +124 -0
- package/example/rpg_persistence.js +151 -0
- package/example/rpg_relations.js +196 -0
- package/example/rpg_world.js +149 -0
- package/example/storage_demo.js +194 -0
- package/index.js +122 -0
- package/lib/backend.js +597 -0
- package/lib/errors.js +35 -0
- package/lib/manager.js +717 -0
- package/lib/model.js +540 -0
- package/lib/pool.js +277 -0
- package/lib/relation.js +175 -0
- package/lib/store.js +430 -0
- package/package.json +64 -5
- package/test.js +748 -0
- package/tool/data/index.js +107 -0
- package/tool/data/tool.json +211 -0
- package/README.md +0 -3
package/lib/manager.js
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* DataManager —— 管理数据类(mm_data 的唯一管理类)
|
|
5
|
+
*
|
|
6
|
+
* 由 mm_admin 实例池 reg('mm_data').get(name) 创建/缓存,一个实例 = 一个具名数据集合:
|
|
7
|
+
* const role = dataAdmin('role'); // role.name === 'role',就是「角色数据集合」
|
|
8
|
+
*
|
|
9
|
+
* 所有实例通过 mm_admin 的 setServer 共享同一个 store(含 models / seq / tables),
|
|
10
|
+
* 因此跨集合关联、完整性检查、存档都无需额外的全局注册表。
|
|
11
|
+
*
|
|
12
|
+
* 「model schema 约束」:集合一旦声明 schema,每个 object 的每个属性值都必须符合规则,
|
|
13
|
+
* 所有写入路径(add/addMany/set/patch/upsert/generate/seed)统一执行。
|
|
14
|
+
* schema 是标准 JSON Schema(draft-07 子集),类型只允许 string/number/boolean/object/array/null,
|
|
15
|
+
* 不使用 int / integer;规则判定全部委托 mm_validator。
|
|
16
|
+
*/
|
|
17
|
+
const fs = require('fs');
|
|
18
|
+
const path = require('path');
|
|
19
|
+
const M = require('./model.js');
|
|
20
|
+
const S = require('./store.js');
|
|
21
|
+
const R = require('./relation.js');
|
|
22
|
+
const { raise } = require('./errors.js');
|
|
23
|
+
const { reg } = require('mm_admin');
|
|
24
|
+
|
|
25
|
+
const EXAMPLE_MODEL_DIR = path.join(__dirname, '..', 'example', 'rpg_model');
|
|
26
|
+
|
|
27
|
+
function normalizeQuery(model, query, options) {
|
|
28
|
+
if (query !== null && query !== undefined && typeof query !== 'object') {
|
|
29
|
+
const q = {};
|
|
30
|
+
q[model.key] = query;
|
|
31
|
+
return q;
|
|
32
|
+
}
|
|
33
|
+
const ok = query && typeof query === 'object' && Object.keys(query).length > 0;
|
|
34
|
+
if (!ok && !(options && options.allow_all)) {
|
|
35
|
+
raise('QUERY_REQUIRED', '写操作必须带 query 条件,不允许全表更新/删除');
|
|
36
|
+
}
|
|
37
|
+
return query || {};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function applyOps(row, ops) {
|
|
41
|
+
ops = ops || {};
|
|
42
|
+
if (ops.$set) Object.assign(row, M.clone(ops.$set));
|
|
43
|
+
if (ops.$inc) {
|
|
44
|
+
for (const f in ops.$inc) row[f] = (typeof row[f] === 'number' ? row[f] : 0) + ops.$inc[f];
|
|
45
|
+
}
|
|
46
|
+
if (ops.$mul) {
|
|
47
|
+
for (const f in ops.$mul) row[f] = (typeof row[f] === 'number' ? row[f] : 0) * ops.$mul[f];
|
|
48
|
+
}
|
|
49
|
+
if (ops.$push) {
|
|
50
|
+
for (const f in ops.$push) {
|
|
51
|
+
if (!Array.isArray(row[f])) row[f] = [];
|
|
52
|
+
row[f].push(M.clone(ops.$push[f]));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (ops.$pull) {
|
|
56
|
+
for (const f in ops.$pull) {
|
|
57
|
+
if (!Array.isArray(row[f])) continue;
|
|
58
|
+
row[f] = row[f].filter(function (v) { return v !== ops.$pull[f]; });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return row;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function renderValue(val, index, manager) {
|
|
65
|
+
if (typeof val !== 'string') return val;
|
|
66
|
+
let out = val;
|
|
67
|
+
out = out.replace(/\{\{\s*\$index\s*\}\}/g, String(index));
|
|
68
|
+
out = out.replace(/\{\{\s*random\((\d+),\s*(\d+)\)\s*\}\}/g, function (_, a, b) {
|
|
69
|
+
const mn = parseInt(a, 10);
|
|
70
|
+
const mx = parseInt(b, 10);
|
|
71
|
+
return String(Math.floor(Math.random() * (mx - mn + 1)) + mn);
|
|
72
|
+
});
|
|
73
|
+
out = out.replace(/\{\{\s*ref:([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\s*\}\}/g, function (_, m, f) {
|
|
74
|
+
try {
|
|
75
|
+
const rows = manager._store.getRows(m);
|
|
76
|
+
if (!rows.length) return '0';
|
|
77
|
+
return String(rows[Math.floor(Math.random() * rows.length)][f]);
|
|
78
|
+
} catch (e) { return '0'; }
|
|
79
|
+
});
|
|
80
|
+
if (/^-?\d+(\.\d+)?$/.test(out)) return Number(out);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
class DataManager {
|
|
85
|
+
/**
|
|
86
|
+
* mm_admin 的 get(name, config, server) 会以 new Class(cg, server) 构造
|
|
87
|
+
* @param {object} config 配置(含 name / namespace / def)
|
|
88
|
+
* @param {object} server 由 pool.setServer 注入的共享 store
|
|
89
|
+
*/
|
|
90
|
+
constructor(config, server) {
|
|
91
|
+
this.config = config || {};
|
|
92
|
+
this.name = this.config.name;
|
|
93
|
+
this.server = server || null;
|
|
94
|
+
this._store = server || this.config.store || S.createStore('memory', {});
|
|
95
|
+
if (!this._store.models) this._store.models = new Map();
|
|
96
|
+
if (!this._store.seq) this._store.seq = new Map();
|
|
97
|
+
this._namespace = this.config.namespace || 'mm_data';
|
|
98
|
+
|
|
99
|
+
const def = this.config.def;
|
|
100
|
+
if (!this._store.models.has(this.name)) {
|
|
101
|
+
this._register(this.name, def || {}, {});
|
|
102
|
+
} else if (def && Object.keys(def).length) {
|
|
103
|
+
this._register(this.name, def, { replace: true });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------- 共享上下文 / 模型注册 ----------
|
|
108
|
+
|
|
109
|
+
get store() { return this._store; }
|
|
110
|
+
get pool() { return reg(this._namespace); }
|
|
111
|
+
|
|
112
|
+
_hasTable(name) {
|
|
113
|
+
if (typeof this._store.tableNames === 'function') {
|
|
114
|
+
return this._store.tableNames().indexOf(name) !== -1;
|
|
115
|
+
}
|
|
116
|
+
return (this._store.getRows(name) || []).length > 0;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 取模型定义;未注册的名字惰性建成自由集合 */
|
|
120
|
+
model(name) {
|
|
121
|
+
const n = name || this.name;
|
|
122
|
+
let m = this._store.models.get(n);
|
|
123
|
+
if (!m) {
|
|
124
|
+
m = M.normalize(n, {});
|
|
125
|
+
this._store.models.set(n, m);
|
|
126
|
+
if (!this._hasTable(n)) this._store.setTable(n, []);
|
|
127
|
+
}
|
|
128
|
+
return m;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
has(name) { return this._store.models.has(name || this.name); }
|
|
132
|
+
|
|
133
|
+
_register(name, def, options) {
|
|
134
|
+
options = options || {};
|
|
135
|
+
const existed = this._store.models.has(name);
|
|
136
|
+
if (existed && !options.replace) return this._store.models.get(name);
|
|
137
|
+
const model = M.normalize(name, def);
|
|
138
|
+
this._store.models.set(name, model);
|
|
139
|
+
if (!this._hasTable(name)) this._store.setTable(name, []);
|
|
140
|
+
if (options.reset) {
|
|
141
|
+
this._store.clear(name);
|
|
142
|
+
this._store.seq.delete(name);
|
|
143
|
+
}
|
|
144
|
+
if (model.seed && options.seed !== false) {
|
|
145
|
+
this._seed(name, model.seed, { raw: options.raw !== false });
|
|
146
|
+
}
|
|
147
|
+
return model;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
_raw() {
|
|
151
|
+
const src = this.model().raw || {};
|
|
152
|
+
const out = Object.assign({}, src, { schema: M.clone(src.schema || {}) });
|
|
153
|
+
if (src.relations) out.relations = src.relations.map(function (r) { return Object.assign({}, r); });
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
_nextId(model) {
|
|
158
|
+
if (!this._store.seq.has(model.name)) {
|
|
159
|
+
let max = 0;
|
|
160
|
+
const rows = this._store.getRows(model.name);
|
|
161
|
+
for (let i = 0; i < rows.length; i++) {
|
|
162
|
+
const v = rows[i][model.key];
|
|
163
|
+
if (typeof v === 'number' && v > max) max = v;
|
|
164
|
+
}
|
|
165
|
+
this._store.seq.set(model.name, max);
|
|
166
|
+
}
|
|
167
|
+
const n = this._store.seq.get(model.name) + 1;
|
|
168
|
+
this._store.seq.set(model.name, n);
|
|
169
|
+
return n;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
_autoSave() {
|
|
173
|
+
if (this._store && typeof this._store.touch === 'function') {
|
|
174
|
+
this._store.touch();
|
|
175
|
+
} else if (this._store.autoSave) {
|
|
176
|
+
this._store.save();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
_checkWritable(model, options) {
|
|
181
|
+
if (model.readonly && !(options && options.force)) {
|
|
182
|
+
raise('READONLY', model.name + ' 是静态只读集合;写入请传 { force:true },或用 seed/reload 换版');
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 唯一的写入校验入口:schema 严格约束 + 引用完整性 */
|
|
187
|
+
_validateWrite(model, row, add, options) {
|
|
188
|
+
options = options || {};
|
|
189
|
+
const errs = M.validate(model, row, { add: !!add });
|
|
190
|
+
if (errs) raise('SCHEMA_VALIDATION', errs.join('; '));
|
|
191
|
+
if (!options.skip_refs) {
|
|
192
|
+
const refErrs = R.validateRefs(this, model, row);
|
|
193
|
+
if (refErrs.length) raise('REF_MISSING', refErrs.join('; '));
|
|
194
|
+
}
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** 更新前对所有受影响行的「最终形态」做完整校验,全部通过才落盘(原子性) */
|
|
199
|
+
_safeUpdate(name, query, mutator, options) {
|
|
200
|
+
options = options || {};
|
|
201
|
+
const model = this.model(name);
|
|
202
|
+
if (options.raw) return this._store.update(name, query, mutator);
|
|
203
|
+
const hits = this._store.getRows(name).filter(function (r) { return S.match(r, query); });
|
|
204
|
+
for (let i = 0; i < hits.length; i++) {
|
|
205
|
+
const next = M.clone(hits[i]);
|
|
206
|
+
mutator(next);
|
|
207
|
+
this._validateWrite(model, next, false);
|
|
208
|
+
}
|
|
209
|
+
return this._store.update(name, query, mutator);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ---------- 内部引擎(带集合名,供 relation.js 与批量装载复用) ----------
|
|
213
|
+
|
|
214
|
+
_existsBy(name, query) { return this._store.exists(name, query); }
|
|
215
|
+
_getBy(name, query) { return this._store.get(name, query, this.model(name).key); }
|
|
216
|
+
|
|
217
|
+
_listBy(name, query, options) {
|
|
218
|
+
options = options || {};
|
|
219
|
+
const model = this.model(name);
|
|
220
|
+
const q = (query !== null && typeof query !== 'object')
|
|
221
|
+
? (function () { const o = {}; o[model.key] = query; return o; })()
|
|
222
|
+
: (query || {});
|
|
223
|
+
const res = this._store.list(name, q, options, model.key);
|
|
224
|
+
res.list = R.hydrate(this, model, res.list, options.with);
|
|
225
|
+
return res;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
_seed(name, rows, options) {
|
|
229
|
+
options = options || {};
|
|
230
|
+
const model = this.model(name);
|
|
231
|
+
const list = rows || [];
|
|
232
|
+
// 序列用本地副本推进:校验失败时不触碰表、也不污染 seq
|
|
233
|
+
let seqVal = this._store.seq.get(name);
|
|
234
|
+
if (seqVal === undefined) {
|
|
235
|
+
seqVal = 0;
|
|
236
|
+
const cur = this._store.getRows(name);
|
|
237
|
+
for (let i = 0; i < cur.length; i++) {
|
|
238
|
+
const v = cur[i][model.key];
|
|
239
|
+
if (typeof v === 'number' && v > seqVal) seqVal = v;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const prepared = [];
|
|
243
|
+
for (let i = 0; i < list.length; i++) {
|
|
244
|
+
let row = M.fillDefaults(model, list[i]);
|
|
245
|
+
if (model.auto && row[model.key] === undefined) row[model.key] = ++seqVal;
|
|
246
|
+
if (!options.raw) this._validateWrite(model, row, true, { skip_refs: !!options.skip_refs });
|
|
247
|
+
prepared.push(row);
|
|
248
|
+
}
|
|
249
|
+
// 全部校验通过后才替换,保证 seed 的原子性
|
|
250
|
+
this._store.clear(name);
|
|
251
|
+
this._store.seq.set(name, seqVal);
|
|
252
|
+
for (let i = 0; i < prepared.length; i++) this._store.insert(name, prepared[i]);
|
|
253
|
+
this._autoSave();
|
|
254
|
+
return { collection: name, count: list.length };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
_add(name, body, options) {
|
|
258
|
+
options = options || {};
|
|
259
|
+
const model = this.model(name);
|
|
260
|
+
this._checkWritable(model, options);
|
|
261
|
+
let row = M.fillDefaults(model, body || {});
|
|
262
|
+
// 先校验、后分配主键:被拒绝的写入不消耗自增序列
|
|
263
|
+
if (!options.raw) this._validateWrite(model, row, true);
|
|
264
|
+
if (model.auto && row[model.key] === undefined) row[model.key] = this._nextId(model);
|
|
265
|
+
const q = {};
|
|
266
|
+
q[model.key] = row[model.key];
|
|
267
|
+
if (this._store.exists(name, q)) raise('DUPLICATE_KEY', '主键重复: ' + row[model.key]);
|
|
268
|
+
Object.assign(row, R.snapshotFields(this, model, row));
|
|
269
|
+
this._store.insert(name, row);
|
|
270
|
+
this._autoSave();
|
|
271
|
+
return {
|
|
272
|
+
obj: R.hydrate(this, model, [row], options.with)[0],
|
|
273
|
+
id: row[model.key], msg: '新增成功', affected: 1
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
_addMany(name, rows, options) {
|
|
278
|
+
options = options || {};
|
|
279
|
+
const model = this.model(name);
|
|
280
|
+
this._checkWritable(model, options);
|
|
281
|
+
const list = rows || [];
|
|
282
|
+
const ids = [];
|
|
283
|
+
const prepared = [];
|
|
284
|
+
// 两段式:整批校验通过后,才分配主键并落盘(原子性 + 不浪费序列)
|
|
285
|
+
for (let i = 0; i < list.length; i++) {
|
|
286
|
+
let row = M.fillDefaults(model, list[i]);
|
|
287
|
+
if (!options.raw) this._validateWrite(model, row, true);
|
|
288
|
+
prepared.push(row);
|
|
289
|
+
}
|
|
290
|
+
for (let i = 0; i < prepared.length; i++) {
|
|
291
|
+
const row = prepared[i];
|
|
292
|
+
if (model.auto && row[model.key] === undefined) row[model.key] = this._nextId(model);
|
|
293
|
+
Object.assign(row, R.snapshotFields(this, model, row));
|
|
294
|
+
this._store.insert(name, row);
|
|
295
|
+
ids.push(row[model.key]);
|
|
296
|
+
}
|
|
297
|
+
this._autoSave();
|
|
298
|
+
return { msg: '批量新增完成', affected: ids.length, ids: ids };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
_get(name, query, options) {
|
|
302
|
+
options = options || {};
|
|
303
|
+
const model = this.model(name);
|
|
304
|
+
const q = (query === null || typeof query !== 'object')
|
|
305
|
+
? (function () { const o = {}; o[model.key] = query; return o; })()
|
|
306
|
+
: query;
|
|
307
|
+
const row = this._store.get(name, q, model.key);
|
|
308
|
+
if (!row) return null;
|
|
309
|
+
return R.hydrate(this, model, [row], options.with)[0];
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
_set(name, query, body, options) {
|
|
313
|
+
options = options || {};
|
|
314
|
+
const model = this.model(name);
|
|
315
|
+
query = normalizeQuery(model, query, options);
|
|
316
|
+
this._checkWritable(model, options);
|
|
317
|
+
const changes = M.clone(body || {});
|
|
318
|
+
const self = this;
|
|
319
|
+
const mutator = function (row) {
|
|
320
|
+
const merged = Object.assign({}, row, changes);
|
|
321
|
+
Object.assign(row, changes, R.snapshotFields(self, model, merged));
|
|
322
|
+
};
|
|
323
|
+
const affected = this._safeUpdate(name, query, mutator, options);
|
|
324
|
+
this._autoSave();
|
|
325
|
+
return { msg: '更新成功', affected: affected };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
_patch(name, query, ops, options) {
|
|
329
|
+
options = options || {};
|
|
330
|
+
const model = this.model(name);
|
|
331
|
+
query = normalizeQuery(model, query, options);
|
|
332
|
+
this._checkWritable(model, options);
|
|
333
|
+
const self = this;
|
|
334
|
+
const mutator = function (row) {
|
|
335
|
+
applyOps(row, ops);
|
|
336
|
+
Object.assign(row, R.snapshotFields(self, model, row));
|
|
337
|
+
};
|
|
338
|
+
const affected = this._safeUpdate(name, query, mutator, options);
|
|
339
|
+
this._autoSave();
|
|
340
|
+
return { msg: '增量更新完成', affected: affected };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
_upsert(name, query, body, options) {
|
|
344
|
+
const model = this.model(name);
|
|
345
|
+
const q = (query === null || typeof query !== 'object')
|
|
346
|
+
? (function () { const o = {}; o[model.key] = query; return o; })()
|
|
347
|
+
: query;
|
|
348
|
+
if (this._store.get(name, q, model.key)) return this._set(name, q, body, options);
|
|
349
|
+
return this._add(name, Object.assign({}, q, body), options);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
_del(name, query, options) {
|
|
353
|
+
options = options || {};
|
|
354
|
+
const model = this.model(name);
|
|
355
|
+
query = normalizeQuery(model, query, options);
|
|
356
|
+
this._checkWritable(model, options);
|
|
357
|
+
const affected = this._store.remove(name, query);
|
|
358
|
+
this._autoSave();
|
|
359
|
+
return { msg: '删除成功', affected: affected };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
_generate(name, count, template, options) {
|
|
363
|
+
options = options || {};
|
|
364
|
+
const model = this.model(name);
|
|
365
|
+
const gen = model.generate || {};
|
|
366
|
+
const tpl = template || gen.template;
|
|
367
|
+
if (!tpl) raise('SCHEMA_VALIDATION', '缺少造数模板 template,或在集合定义里写 generate.template');
|
|
368
|
+
const total = count || gen.count || 10;
|
|
369
|
+
const rows = [];
|
|
370
|
+
for (let i = 0; i < total; i++) {
|
|
371
|
+
const row = {};
|
|
372
|
+
for (const f in tpl) row[f] = renderValue(tpl[f], i, this);
|
|
373
|
+
rows.push(row);
|
|
374
|
+
}
|
|
375
|
+
return this._addMany(name, rows, options);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ---------- 面向使用者的集合 API(无需再传集合名) ----------
|
|
379
|
+
|
|
380
|
+
get key() { return this.model().key; }
|
|
381
|
+
get kind() { return this.model().kind; }
|
|
382
|
+
get readonly() { return this.model().readonly; }
|
|
383
|
+
get version() { return this.model().version; }
|
|
384
|
+
get schemaless() { return this.model().schemaless; }
|
|
385
|
+
get constrained() { return this.model().constrained; }
|
|
386
|
+
get strict() { return this.model().strict; }
|
|
387
|
+
get size() { return this._store.count(this.name, {}); }
|
|
388
|
+
get length() { return this.size; }
|
|
389
|
+
|
|
390
|
+
/** 返回用户定义的标准 JSON Schema 文档(自由集合返回 null) */
|
|
391
|
+
schema() { return this.model().jsonSchema || null; }
|
|
392
|
+
definition() { return this._raw(); }
|
|
393
|
+
info() {
|
|
394
|
+
const m = this.model();
|
|
395
|
+
return {
|
|
396
|
+
name: m.name, key: m.key, kind: m.kind, readonly: m.readonly,
|
|
397
|
+
strict: m.strict, constrained: m.constrained, version: m.version, rows: this.size,
|
|
398
|
+
fields: Object.keys(m.schema), relations: m.relations.map(function (r) { return r.name; }),
|
|
399
|
+
schema_draft: m.jsonSchema ? m.jsonSchema.$schema : null,
|
|
400
|
+
schema: m.jsonSchema || null,
|
|
401
|
+
validator: M.validatorInfo().engine_tools
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** 定义 / 重定义当前集合,默认保留已有数据 */
|
|
406
|
+
define(def, options) {
|
|
407
|
+
return this._register(this.name, def, Object.assign({ replace: true, seed: false }, options || {}));
|
|
408
|
+
}
|
|
409
|
+
redefine(def, options) { return this.define(def, options); }
|
|
410
|
+
|
|
411
|
+
field(field, def) {
|
|
412
|
+
const raw = this._raw();
|
|
413
|
+
// 字段定义本身也是标准 JSON Schema 的子 schema;不声明 type 即无类型约束
|
|
414
|
+
raw.schema = M.setField(raw.schema, field, def === undefined ? {} : def);
|
|
415
|
+
return this.define(raw);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
ref(field, target, options) {
|
|
419
|
+
if (!target || typeof target !== 'string') raise('REF_UNKNOWN', 'ref 目标必须是集合名字符串');
|
|
420
|
+
const raw = this._raw();
|
|
421
|
+
const prev = M.getField(raw.schema, field);
|
|
422
|
+
const base = typeof prev === 'string' ? { type: prev } : Object.assign({}, prev || {});
|
|
423
|
+
raw.schema = M.setField(raw.schema, field, Object.assign(base, {
|
|
424
|
+
ref: Object.assign({ model: target, onMissing: 'error' }, options || {})
|
|
425
|
+
}));
|
|
426
|
+
return this.define(raw);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
hasMany(as, options) {
|
|
430
|
+
options = options || {};
|
|
431
|
+
if (!options.model) raise('REF_UNKNOWN', 'hasMany 必须指定目标集合 model');
|
|
432
|
+
const raw = this._raw();
|
|
433
|
+
raw.relations = (raw.relations || []).filter(function (r) { return (r.name || r.as) !== as; });
|
|
434
|
+
raw.relations.push(Object.assign({ name: as, as: as, type: 'one-to-many', local: this.key }, options));
|
|
435
|
+
return this.define(raw);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** 当前 schema 校验器信息(规则由 mm_validator 执行) */
|
|
439
|
+
validator() { return M.validatorInfo(); }
|
|
440
|
+
|
|
441
|
+
/** 只校验、不写入 */
|
|
442
|
+
validate(body, options) {
|
|
443
|
+
options = options || {};
|
|
444
|
+
const model = this.model();
|
|
445
|
+
const row = M.fillDefaults(model, body || {});
|
|
446
|
+
const result = M.check(model, row);
|
|
447
|
+
if (!options.skip_refs && result.ok) {
|
|
448
|
+
const errs = R.validateRefs(this, model, row);
|
|
449
|
+
if (errs.length) return { ok: false, errors: errs };
|
|
450
|
+
}
|
|
451
|
+
return result;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
add(body, options) { return this._add(this.name, body, options); }
|
|
455
|
+
addMany(rows, options) { return this._addMany(this.name, rows, options); }
|
|
456
|
+
get(query, options) { return this._get(this.name, query, options); }
|
|
457
|
+
list(query, options) { return this._listBy(this.name, query, options); }
|
|
458
|
+
count(query) { return this._store.count(this.name, query || {}); }
|
|
459
|
+
set(query, body, options) { return this._set(this.name, query, body, options); }
|
|
460
|
+
patch(query, ops, options) { return this._patch(this.name, query, ops, options); }
|
|
461
|
+
upsert(query, body, options) { return this._upsert(this.name, query, body, options); }
|
|
462
|
+
del(query, options) { return this._del(this.name, query, options); }
|
|
463
|
+
delMany(query, options) { return this.del(query, options); }
|
|
464
|
+
generate(count, template, options) { return this._generate(this.name, count, template, options); }
|
|
465
|
+
seed(rows, options) { return this._seed(this.name, rows, options); }
|
|
466
|
+
reload(rows, options) {
|
|
467
|
+
options = options || {};
|
|
468
|
+
if (options.version) this.model().version = options.version;
|
|
469
|
+
return this._seed(this.name, rows || this.model().seed || [], Object.assign({ raw: true }, options));
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
all(options) { return this.list({}, Object.assign({ limit: -1 }, options || {})).list; }
|
|
473
|
+
where(query, options) { return this.list(query || {}, options).list; }
|
|
474
|
+
first(query, options) { return this.list(query || {}, Object.assign({ limit: 1 }, options || {})).list[0] || null; }
|
|
475
|
+
toArray() { return this.all(); }
|
|
476
|
+
toJSON() { return this.all(); }
|
|
477
|
+
[Symbol.iterator]() { return this.all()[Symbol.iterator](); }
|
|
478
|
+
each(fn) { const rows = this.all(); for (let i = 0; i < rows.length; i++) fn(rows[i], i); return this; }
|
|
479
|
+
map(fn) { return this.all().map(fn); }
|
|
480
|
+
|
|
481
|
+
/** 取同池的另一个集合(跨集合关联的显式入口) */
|
|
482
|
+
collection(name, def) {
|
|
483
|
+
const pool = reg(this._namespace);
|
|
484
|
+
if (typeof pool.data === 'function') return pool.data(name, def);
|
|
485
|
+
return pool.get(name, { namespace: this._namespace, def: def });
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** 反查:找出所有集合中引用了本集合某个键的记录 */
|
|
489
|
+
reverse(keyValue, options) {
|
|
490
|
+
options = options || {};
|
|
491
|
+
const out = [];
|
|
492
|
+
const names = Array.from(this._store.models.keys());
|
|
493
|
+
for (let i = 0; i < names.length; i++) {
|
|
494
|
+
const m = this._store.models.get(names[i]);
|
|
495
|
+
for (const f in m.schema) {
|
|
496
|
+
const ref = m.schema[f].ref;
|
|
497
|
+
if (!ref || ref.model !== this.name) continue;
|
|
498
|
+
const q = {};
|
|
499
|
+
q[f] = keyValue;
|
|
500
|
+
const rows = this._listBy(names[i], q, { limit: options.limit || 1000 }).list;
|
|
501
|
+
for (let j = 0; j < rows.length; j++) out.push({ collection: names[i], field: f, row: rows[j] });
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return { list: out, count: out.length };
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
verify() {
|
|
508
|
+
const dangling = [];
|
|
509
|
+
let checked = 0;
|
|
510
|
+
for (const name of this._store.models.keys()) {
|
|
511
|
+
const model = this._store.models.get(name);
|
|
512
|
+
const rows = this._store.getRows(name);
|
|
513
|
+
for (let j = 0; j < rows.length; j++) {
|
|
514
|
+
const row = rows[j];
|
|
515
|
+
for (const f in model.schema) {
|
|
516
|
+
const ref = model.schema[f].ref;
|
|
517
|
+
if (!ref || row[f] === undefined || row[f] === null) continue;
|
|
518
|
+
checked++;
|
|
519
|
+
const target = this.model(ref.model);
|
|
520
|
+
const q = {};
|
|
521
|
+
q[ref.key || target.key] = row[f];
|
|
522
|
+
if (!this._store.exists(target.name, q)) {
|
|
523
|
+
dangling.push({ collection: name, key: row[model.key], field: f, value: row[f], target: target.name });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return { checked: checked, ok: dangling.length === 0, dangling: dangling };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// ---------- 注册表级操作(任一实例都可作为入口) ----------
|
|
532
|
+
|
|
533
|
+
models() {
|
|
534
|
+
return Array.from(this._store.models.values()).map(function (m) {
|
|
535
|
+
return {
|
|
536
|
+
name: m.name, kind: m.kind, key: m.key, version: m.version,
|
|
537
|
+
readonly: m.readonly, constrained: m.constrained, strict: m.strict,
|
|
538
|
+
fields: Object.keys(m.schema)
|
|
539
|
+
};
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
collections() { return this.models(); }
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* 扫描模型目录:优先 *_model.json,有几个文件就创建几种集合。
|
|
546
|
+
* 集合名由文件名推导(role_model.json → role),目录里没有规范文件时兼容旧命名。
|
|
547
|
+
*/
|
|
548
|
+
loadModels(dir, options) {
|
|
549
|
+
options = options || {};
|
|
550
|
+
const target = dir || EXAMPLE_MODEL_DIR;
|
|
551
|
+
if (!fs.existsSync(target)) return [];
|
|
552
|
+
const all = fs.readdirSync(target).filter(function (f) { return /\.json$/i.test(f); }).sort();
|
|
553
|
+
const standard = all.filter(function (f) { return /_model\.json$/i.test(f); });
|
|
554
|
+
const files = standard.length ? standard : all;
|
|
555
|
+
const names = [];
|
|
556
|
+
for (let i = 0; i < files.length; i++) {
|
|
557
|
+
const def = JSON.parse(fs.readFileSync(path.join(target, files[i]), 'utf8'));
|
|
558
|
+
const name = path.basename(files[i], '.json').replace(/_model$/i, '') || def.name;
|
|
559
|
+
def.name = name; // 文件名即集合名,保证「文件数 == 集合数」
|
|
560
|
+
this._register(name, def, { replace: true, reset: !!options.reset, seed: options.seed !== false, raw: true });
|
|
561
|
+
names.push(name);
|
|
562
|
+
}
|
|
563
|
+
return names;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
stats() {
|
|
567
|
+
const out = [];
|
|
568
|
+
let total = 0;
|
|
569
|
+
for (const name of this._store.models.keys()) {
|
|
570
|
+
const m = this._store.models.get(name);
|
|
571
|
+
const n = this._store.getRows(name).length;
|
|
572
|
+
total += n;
|
|
573
|
+
out.push({ name: name, kind: m.kind, key: m.key, version: m.version, rows: n });
|
|
574
|
+
}
|
|
575
|
+
return { total: total, collections: out };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
drop() {
|
|
579
|
+
const pool = reg(this._namespace);
|
|
580
|
+
if (pool && typeof pool.del === 'function') pool.del(this.name);
|
|
581
|
+
this._store.clear(this.name);
|
|
582
|
+
this._store.models.delete(this.name);
|
|
583
|
+
this._store.seq.delete(this.name);
|
|
584
|
+
return { ok: true, dropped: this.name };
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
clear() {
|
|
588
|
+
this._store.clear(this.name);
|
|
589
|
+
this._store.seq.delete(this.name);
|
|
590
|
+
return { ok: true, cleared: this.name };
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// ---------- 外部访问层(mm_cache / mm_mongodb / mm_sql) ----------
|
|
594
|
+
|
|
595
|
+
_adapters() { return this._store.adapters || null; }
|
|
596
|
+
|
|
597
|
+
_cacheKey(kind, query, options) {
|
|
598
|
+
return this._namespace + ':' + this.name + ':' + kind + ':' +
|
|
599
|
+
JSON.stringify([query === undefined ? null : query, options || null]);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** 经 mm_cache 取一条:命中直接返回,未命中查内存工作集并回填 */
|
|
603
|
+
async cacheGet(query, options) {
|
|
604
|
+
const a = this._adapters();
|
|
605
|
+
if (!a) return this.get(query, options);
|
|
606
|
+
const key = this._cacheKey('get', query, options);
|
|
607
|
+
const hit = await a.cache.get(key);
|
|
608
|
+
if (hit !== null) return hit;
|
|
609
|
+
const value = this.get(query, options);
|
|
610
|
+
await a.cache.set(key, value);
|
|
611
|
+
return value;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** 经 mm_cache 取列表:同样命中直接返回 */
|
|
615
|
+
async cacheList(query, options) {
|
|
616
|
+
const a = this._adapters();
|
|
617
|
+
if (!a) return this.list(query, options);
|
|
618
|
+
const key = this._cacheKey('list', query, options);
|
|
619
|
+
const hit = await a.cache.get(key);
|
|
620
|
+
if (hit !== null) return hit;
|
|
621
|
+
const value = this.list(query, options);
|
|
622
|
+
await a.cache.set(key, value);
|
|
623
|
+
return value;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** 可选:直接用 mm_sql 查询数据源(未启用时返回 null) */
|
|
627
|
+
async sql(sqlText, params) {
|
|
628
|
+
const a = this._adapters();
|
|
629
|
+
return a ? a.sql.query(sqlText, params) : null;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/** 写入后主动失效,避免脏读 */
|
|
633
|
+
async invalidateCache() {
|
|
634
|
+
const a = this._adapters();
|
|
635
|
+
if (!a) return 0;
|
|
636
|
+
return a.cache.clearPrefix(this._namespace + ':' + this.name + ':');
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** 显式连接外部依赖(未安装 / 未启用 / 连不上都不抛错) */
|
|
640
|
+
async connect() {
|
|
641
|
+
return typeof this._store.connect === 'function'
|
|
642
|
+
? this._store.connect()
|
|
643
|
+
: { ok: false, reason: '当前为纯内存 store,请用 createPool(ns, { store:"hybrid", dir, models })' };
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** 把内存工作集推到外部层(静态逐文件、动态缓存 + 持久 + 可选 SQL) */
|
|
647
|
+
async flush() {
|
|
648
|
+
return typeof this._store.flush === 'function'
|
|
649
|
+
? this._store.flush()
|
|
650
|
+
: { ok: false, reason: '当前为纯内存 store,不支持外部后端' };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** 从 data 目录 / mm_mongodb / mm_sql 恢复 */
|
|
654
|
+
async restore(dir) {
|
|
655
|
+
return typeof this._store.restore === 'function'
|
|
656
|
+
? this._store.restore(dir)
|
|
657
|
+
: { ok: false, reason: '当前为纯内存 store,不支持外部后端' };
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** 后端与依赖可用性报告 */
|
|
661
|
+
backends() {
|
|
662
|
+
return typeof this._store.backends === 'function'
|
|
663
|
+
? this._store.backends()
|
|
664
|
+
: { backend: this._store.constructor.name, dependencies: require('./backend.js').probe() };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
save(dir) { return this._store.save(dir); }
|
|
668
|
+
|
|
669
|
+
/** 立即落盘当前池的脏数据(同步本地持久化) */
|
|
670
|
+
flushNow() {
|
|
671
|
+
return typeof this._store.saveNow === 'function'
|
|
672
|
+
? this._store.saveNow()
|
|
673
|
+
: { ok: true, skipped: true, reason: '当前 store 不支持 saveNow' };
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** 设置自动落盘间隔(毫秒),0 表示关闭定时落盘 */
|
|
677
|
+
startAutoFlush(interval) {
|
|
678
|
+
if (typeof this._store.startAutoFlush === 'function') this._store.startAutoFlush(interval);
|
|
679
|
+
return this;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** 停止自动落盘定时器 */
|
|
683
|
+
stopAutoFlush() {
|
|
684
|
+
if (typeof this._store.stopAutoFlush === 'function') this._store.stopAutoFlush();
|
|
685
|
+
return this;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/** 关闭数据集合:停止定时落盘并保存剩余数据 */
|
|
689
|
+
close() {
|
|
690
|
+
return typeof this._store.close === 'function' ? this._store.close() : this.flushNow();
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** 持久化策略与落盘统计 */
|
|
694
|
+
persistStatus() {
|
|
695
|
+
return typeof this._store.persistStatus === 'function'
|
|
696
|
+
? this._store.persistStatus()
|
|
697
|
+
: { backend: this._store.constructor.name, persist: false, dirty: false };
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
load(dir) {
|
|
701
|
+
const res = this._store.load(null, dir);
|
|
702
|
+
const names = res.table_names || [];
|
|
703
|
+
for (let i = 0; i < names.length; i++) {
|
|
704
|
+
if (!this._store.models.has(names[i])) this._register(names[i], {}, { seed: false });
|
|
705
|
+
}
|
|
706
|
+
this._store.seq.clear();
|
|
707
|
+
return res;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
dump() {
|
|
711
|
+
const out = {};
|
|
712
|
+
for (const name of this._store.models.keys()) out[name] = M.clone(this._store.getRows(name));
|
|
713
|
+
return out;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
module.exports = { DataManager: DataManager, EXAMPLE_MODEL_DIR: EXAMPLE_MODEL_DIR };
|