mm_datas 5.3.0 → 5.3.2

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/lib/manager.js CHANGED
@@ -3,7 +3,7 @@
3
3
  /**
4
4
  * DataManager —— 管理数据类(mm_data 的唯一管理类)
5
5
  *
6
- * 由 mm_admin 实例池 reg('mm_data').get(name) 创建/缓存,一个实例 = 一个具名数据集合:
6
+ * 由 mm_admin 实例池 reg('mm_datas').get(name) 创建/缓存,一个实例 = 一个具名数据集合:
7
7
  * const role = dataAdmin('role'); // role.name === 'role',就是「角色数据集合」
8
8
  *
9
9
  * 所有实例通过 mm_admin 的 setServer 共享同一个 store(含 models / seq / tables),
@@ -13,73 +13,22 @@
13
13
  * 所有写入路径(add/addMany/set/patch/upsert/generate/seed)统一执行。
14
14
  * schema 是标准 JSON Schema(draft-07 子集),类型只允许 string/number/boolean/object/array/null,
15
15
  * 不使用 int / integer;规则判定全部委托 mm_validator。
16
+ *
17
+ * 本文件承载类核心:构造、模型注册、写入校验、面向使用者的集合 API;
18
+ * 内部引擎(带集合名的 _seed/_add 等)、注册表级操作与外部访问层在 manager_ext.js,
19
+ * 加载时合并挂载到 DataManager.prototype。
16
20
  */
17
- const fs = require('fs');
18
- const path = require('path');
21
+
19
22
  const M = require('./model.js');
20
23
  const S = require('./store.js');
21
24
  const R = require('./relation.js');
22
25
  const { raise } = require('./errors.js');
23
26
  const { reg } = require('mm_admin');
27
+ const helper = require('./manager_helper.js');
24
28
 
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
- }
29
+ const ext = require('./manager_ext.js');
30
+ const define_part = require('./manager_define.js');
31
+ const store_part = require('./manager_store.js');
83
32
 
84
33
  class DataManager {
85
34
  /**
@@ -94,9 +43,9 @@ class DataManager {
94
43
  this._store = server || this.config.store || S.createStore('memory', {});
95
44
  if (!this._store.models) this._store.models = new Map();
96
45
  if (!this._store.seq) this._store.seq = new Map();
97
- this._namespace = this.config.namespace || 'mm_data';
46
+ this._namespace = this.config.namespace || 'mm_datas';
98
47
 
99
- const def = this.config.def;
48
+ let def = this.config.def;
100
49
  if (!this._store.models.has(this.name)) {
101
50
  this._register(this.name, def || {}, {});
102
51
  } else if (def && Object.keys(def).length) {
@@ -109,6 +58,12 @@ class DataManager {
109
58
  get store() { return this._store; }
110
59
  get pool() { return reg(this._namespace); }
111
60
 
61
+ /**
62
+ * 判断表是否已存在
63
+ * @param {string} name 表名
64
+ * @returns {boolean} 存在返回 true
65
+ * @private
66
+ */
112
67
  _hasTable(name) {
113
68
  if (typeof this._store.tableNames === 'function') {
114
69
  return this._store.tableNames().indexOf(name) !== -1;
@@ -118,7 +73,7 @@ class DataManager {
118
73
 
119
74
  /** 取模型定义;未注册的名字惰性建成自由集合 */
120
75
  model(name) {
121
- const n = name || this.name;
76
+ let n = name || this.name;
122
77
  let m = this._store.models.get(n);
123
78
  if (!m) {
124
79
  m = M.normalize(n, {});
@@ -128,13 +83,26 @@ class DataManager {
128
83
  return m;
129
84
  }
130
85
 
86
+ /**
87
+ * 判断模型是否已注册
88
+ * @param {string} [name] 模型名,缺省当前集合
89
+ * @returns {boolean} 已注册返回 true
90
+ */
131
91
  has(name) { return this._store.models.has(name || this.name); }
132
92
 
93
+ /**
94
+ * 注册模型定义
95
+ * @param {string} name 模型名
96
+ * @param {object} def 模型定义
97
+ * @param {object} [options] 选项(replace/reset/seed/raw)
98
+ * @returns {object} 模型定义
99
+ * @private
100
+ */
133
101
  _register(name, def, options) {
134
102
  options = options || {};
135
- const existed = this._store.models.has(name);
103
+ let existed = this._store.models.has(name);
136
104
  if (existed && !options.replace) return this._store.models.get(name);
137
- const model = M.normalize(name, def);
105
+ let model = M.normalize(name, def);
138
106
  this._store.models.set(name, model);
139
107
  if (!this._hasTable(name)) this._store.setTable(name, []);
140
108
  if (options.reset) {
@@ -147,36 +115,58 @@ class DataManager {
147
115
  return model;
148
116
  }
149
117
 
118
+ /**
119
+ * 取当前集合定义的原始形态(深拷贝)
120
+ * @returns {object} 原始定义
121
+ * @private
122
+ */
150
123
  _raw() {
151
- const src = this.model().raw || {};
152
- const out = Object.assign({}, src, { schema: M.clone(src.schema || {}) });
124
+ let src = this.model().raw || {};
125
+ let out = Object.assign({}, src, { schema: M.clone(src.schema || {}) });
153
126
  if (src.relations) out.relations = src.relations.map(function (r) { return Object.assign({}, r); });
154
127
  return out;
155
128
  }
156
129
 
130
+ /**
131
+ * 取下一个自增主键
132
+ * @param {object} model 模型定义
133
+ * @returns {number} 自增主键值
134
+ * @private
135
+ */
157
136
  _nextId(model) {
158
137
  if (!this._store.seq.has(model.name)) {
159
138
  let max = 0;
160
- const rows = this._store.getRows(model.name);
139
+ let rows = this._store.getRows(model.name);
161
140
  for (let i = 0; i < rows.length; i++) {
162
- const v = rows[i][model.key];
141
+ let v = rows[i][model.key];
163
142
  if (typeof v === 'number' && v > max) max = v;
164
143
  }
165
144
  this._store.seq.set(model.name, max);
166
145
  }
167
- const n = this._store.seq.get(model.name) + 1;
146
+ let n = this._store.seq.get(model.name) + 1;
168
147
  this._store.seq.set(model.name, n);
169
148
  return n;
170
149
  }
171
150
 
151
+ /**
152
+ * 触发自动落盘
153
+ * @private
154
+ */
172
155
  _autoSave() {
173
156
  if (this._store && typeof this._store.touch === 'function') {
174
157
  this._store.touch();
175
- } else if (this._store.autoSave) {
158
+ } else if (this._store.auto_save) {
176
159
  this._store.save();
177
160
  }
178
161
  }
179
162
 
163
+ /**
164
+ * 写入前检查集合是否可写
165
+ * @param {object} model 模型定义
166
+ * @param {object} [options] 选项(force 覆盖只读)
167
+ * @throws {Error} 只读集合未强制写入时抛出
168
+ * @private
169
+ */
180
170
  _checkWritable(model, options) {
181
171
  if (model.readonly && !(options && options.force)) {
182
172
  raise('READONLY', model.name + ' 是静态只读集合;写入请传 { force:true },或用 seed/reload 换版');
@@ -186,10 +176,10 @@ class DataManager {
186
176
  /** 唯一的写入校验入口:schema 严格约束 + 引用完整性 */
187
177
  _validateWrite(model, row, add, options) {
188
178
  options = options || {};
189
- const errs = M.validate(model, row, { add: !!add });
179
+ let errs = M.validate(model, row, { add: !!add });
190
180
  if (errs) raise('SCHEMA_VALIDATION', errs.join('; '));
191
181
  if (!options.skip_refs) {
192
- const refErrs = R.validateRefs(this, model, row);
182
+ let refErrs = R.validateRefs(this, model, row);
193
183
  if (refErrs.length) raise('REF_MISSING', refErrs.join('; '));
194
184
  }
195
185
  return true;
@@ -198,183 +188,17 @@ class DataManager {
198
188
  /** 更新前对所有受影响行的「最终形态」做完整校验,全部通过才落盘(原子性) */
199
189
  _safeUpdate(name, query, mutator, options) {
200
190
  options = options || {};
201
- const model = this.model(name);
191
+ let model = this.model(name);
202
192
  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); });
193
+ let hits = this._store.getRows(name).filter(function (r) { return S.match(r, query); });
204
194
  for (let i = 0; i < hits.length; i++) {
205
- const next = M.clone(hits[i]);
195
+ let next = M.clone(hits[i]);
206
196
  mutator(next);
207
197
  this._validateWrite(model, next, false);
208
198
  }
209
199
  return this._store.update(name, query, mutator);
210
200
  }
211
201
 
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
202
  // ---------- 面向使用者的集合 API(无需再传集合名) ----------
379
203
 
380
204
  get key() { return this.model().key; }
@@ -387,196 +211,186 @@ class DataManager {
387
211
  get size() { return this._store.count(this.name, {}); }
388
212
  get length() { return this.size; }
389
213
 
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
214
 
215
+ /**
216
+ * 新增一条记录
217
+ * @param {object} body 记录数据
218
+ * @param {object} [options] 选项
219
+ * @returns {object} 新增结果
220
+ */
454
221
  add(body, options) { return this._add(this.name, body, options); }
222
+
223
+ /**
224
+ * 批量新增
225
+ * @param {Array} rows 记录列表
226
+ * @param {object} [options] 选项
227
+ * @returns {object} 新增结果
228
+ */
455
229
  addMany(rows, options) { return this._addMany(this.name, rows, options); }
230
+
231
+ /**
232
+ * 取一条记录
233
+ * @param {*} query 查询条件或主键值
234
+ * @param {object} [options] 选项(with 关联装载)
235
+ * @returns {object|null} 记录
236
+ */
456
237
  get(query, options) { return this._get(this.name, query, options); }
238
+
239
+ /**
240
+ * 分页查询
241
+ * @param {*} query 查询条件或主键值
242
+ * @param {object} [options] 选项
243
+ * @returns {object} 分页结果
244
+ */
457
245
  list(query, options) { return this._listBy(this.name, query, options); }
246
+
247
+ /**
248
+ * 按条件计数
249
+ * @param {object} [query] 查询条件
250
+ * @returns {number} 匹配条数
251
+ */
458
252
  count(query) { return this._store.count(this.name, query || {}); }
253
+
254
+ /**
255
+ * 按条件整行更新
256
+ * @param {*} query 查询条件
257
+ * @param {object} body 更新内容
258
+ * @param {object} [options] 选项
259
+ * @returns {object} 更新结果
260
+ */
459
261
  set(query, body, options) { return this._set(this.name, query, body, options); }
262
+
263
+ /**
264
+ * 按条件增量更新
265
+ * @param {*} query 查询条件
266
+ * @param {object} ops 操作符表
267
+ * @param {object} [options] 选项
268
+ * @returns {object} 更新结果
269
+ */
460
270
  patch(query, ops, options) { return this._patch(this.name, query, ops, options); }
271
+
272
+ /**
273
+ * 存在则更新,不存在则新增
274
+ * @param {*} query 查询条件或主键值
275
+ * @param {object} body 写入内容
276
+ * @param {object} [options] 选项
277
+ * @returns {object} 操作结果
278
+ */
461
279
  upsert(query, body, options) { return this._upsert(this.name, query, body, options); }
280
+
281
+ /**
282
+ * 按条件删除
283
+ * @param {*} query 查询条件
284
+ * @param {object} [options] 选项
285
+ * @returns {object} 删除结果
286
+ */
462
287
  del(query, options) { return this._del(this.name, query, options); }
288
+
289
+ /**
290
+ * del 的别名(批量语义)
291
+ * @param {*} query 查询条件
292
+ * @param {object} [options] 选项
293
+ * @returns {object} 删除结果
294
+ */
463
295
  delMany(query, options) { return this.del(query, options); }
296
+
297
+ /**
298
+ * 按模板造数
299
+ * @param {number} [count] 生成条数
300
+ * @param {object} [template] 造数模板
301
+ * @param {object} [options] 选项
302
+ * @returns {object} 新增结果
303
+ */
464
304
  generate(count, template, options) { return this._generate(this.name, count, template, options); }
305
+
306
+ /**
307
+ * 整表换版(替换全部数据)
308
+ * @param {Array} [rows] 数据列表
309
+ * @param {object} [options] 选项
310
+ * @returns {object} seed 结果
311
+ */
465
312
  seed(rows, options) { return this._seed(this.name, rows, options); }
313
+
314
+ /**
315
+ * 换版装载:替换全部数据并可更新版本号
316
+ * @param {Array} [rows] 数据列表,缺省用模型 seed
317
+ * @param {object} [options] 选项(version 更新版本号)
318
+ * @returns {object} seed 结果
319
+ */
466
320
  reload(rows, options) {
467
321
  options = options || {};
468
322
  if (options.version) this.model().version = options.version;
469
323
  return this._seed(this.name, rows || this.model().seed || [], Object.assign({ raw: true }, options));
470
324
  }
471
325
 
326
+ /**
327
+ * 全量列表
328
+ * @param {object} [options] 选项
329
+ * @returns {Array} 记录列表
330
+ */
472
331
  all(options) { return this.list({}, Object.assign({ limit: -1 }, options || {})).list; }
332
+
333
+ /**
334
+ * 条件列表
335
+ * @param {object} [query] 查询条件
336
+ * @param {object} [options] 选项
337
+ * @returns {Array} 记录列表
338
+ */
473
339
  where(query, options) { return this.list(query || {}, options).list; }
340
+
341
+ /**
342
+ * 取第一条
343
+ * @param {object} [query] 查询条件
344
+ * @param {object} [options] 选项
345
+ * @returns {object|null} 记录
346
+ */
474
347
  first(query, options) { return this.list(query || {}, Object.assign({ limit: 1 }, options || {})).list[0] || null; }
348
+
349
+ /**
350
+ * all 的别名
351
+ * @returns {Array} 记录列表
352
+ */
475
353
  toArray() { return this.all(); }
354
+
355
+ /**
356
+ * all 的别名
357
+ * @returns {Array} 记录列表
358
+ */
476
359
  toJSON() { return this.all(); }
360
+
361
+ /**
362
+ * 迭代器
363
+ * @returns {Iterator} 记录迭代器
364
+ */
477
365
  [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; }
366
+
367
+ /**
368
+ * 遍历记录
369
+ * @param {Function} fn 回调 fn(row, index)
370
+ * @returns {DataManager} 自身
371
+ */
372
+ each(fn) { let rows = this.all(); for (let i = 0; i < rows.length; i++) fn(rows[i], i); return this; }
373
+
374
+ /**
375
+ * 映射记录
376
+ * @param {Function} fn 回调 fn(row)
377
+ * @returns {Array} 映射结果
378
+ */
479
379
  map(fn) { return this.all().map(fn); }
480
380
 
481
381
  /** 取同池的另一个集合(跨集合关联的显式入口) */
482
382
  collection(name, def) {
483
- const pool = reg(this._namespace);
383
+ let pool = reg(this._namespace);
484
384
  if (typeof pool.data === 'function') return pool.data(name, def);
485
385
  return pool.get(name, { namespace: this._namespace, def: def });
486
386
  }
487
387
 
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
388
  /**
545
- * 扫描模型目录:优先 *_model.json,有几个文件就创建几种集合。
546
- * 集合名由文件名推导(role_model.json → role),目录里没有规范文件时兼容旧命名。
389
+ * 从注册表移除本集合并清空数据
390
+ * @returns {object} 删除结果
547
391
  */
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
392
  drop() {
579
- const pool = reg(this._namespace);
393
+ let pool = reg(this._namespace);
580
394
  if (pool && typeof pool.del === 'function') pool.del(this.name);
581
395
  this._store.clear(this.name);
582
396
  this._store.models.delete(this.name);
@@ -584,122 +398,24 @@ class DataManager {
584
398
  return { ok: true, dropped: this.name };
585
399
  }
586
400
 
401
+ /**
402
+ * 清空当前集合数据
403
+ * @returns {object} 清空结果
404
+ */
587
405
  clear() {
588
406
  this._store.clear(this.name);
589
407
  this._store.seq.delete(this.name);
590
408
  return { ok: true, cleared: this.name };
591
409
  }
592
410
 
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
-
411
+ /**
412
+ * 从存储恢复并补注册缺失的模型
413
+ * @param {string} [dir] 数据目录
414
+ * @returns {object} 恢复结果
415
+ */
700
416
  load(dir) {
701
- const res = this._store.load(null, dir);
702
- const names = res.table_names || [];
417
+ let res = this._store.load(null, dir);
418
+ let names = res.table_names || [];
703
419
  for (let i = 0; i < names.length; i++) {
704
420
  if (!this._store.models.has(names[i])) this._register(names[i], {}, { seed: false });
705
421
  }
@@ -707,11 +423,22 @@ class DataManager {
707
423
  return res;
708
424
  }
709
425
 
426
+ /**
427
+ * 导出全部集合数据
428
+ * @returns {object} 集合名 → 行列表
429
+ */
710
430
  dump() {
711
- const out = {};
712
- for (const name of this._store.models.keys()) out[name] = M.clone(this._store.getRows(name));
431
+ let out = {};
432
+ for (let name of this._store.models.keys()) out[name] = M.clone(this._store.getRows(name));
713
433
  return out;
714
434
  }
715
435
  }
716
436
 
717
- module.exports = { DataManager: DataManager, EXAMPLE_MODEL_DIR: EXAMPLE_MODEL_DIR };
437
+ let parts = [ext, define_part, store_part];
438
+ for (let part of parts) {
439
+ for (let key of Object.keys(part)) {
440
+ DataManager.prototype[key] = part[key];
441
+ }
442
+ }
443
+
444
+ module.exports = DataManager;