mm_datas 5.3.1 → 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/relation.js CHANGED
@@ -7,37 +7,55 @@
7
7
  const { clone, project } = require('./model.js');
8
8
  const { raise } = require('./errors.js');
9
9
 
10
+ /**
11
+ * 查找模型声明的指定关联
12
+ * @param {object} model - 模型定义
13
+ * @param {string} name - 关联名
14
+ * @returns {object|null} 关联定义,未声明时返回 null
15
+ */
10
16
  function findRelation(model, name) {
11
- const list = model.relations || [];
17
+ let list = model.relations || [];
12
18
  for (let i = 0; i < list.length; i++) if (list[i].name === name) return list[i];
13
19
  return null;
14
20
  }
15
21
 
22
+ /**
23
+ * 归一化 with 展开参数:字符串/对象两种写法统一为 { rel, as, select, mode }
24
+ * @param {object} model - 模型定义
25
+ * @param {string|object|Array} withSpec - 展开参数,可为关联名或含 as/select/mode 的对象
26
+ * @returns {Array<{rel: object, as: string, select: Array|null, mode: string}>} 归一化后的展开清单
27
+ * @throws {Error} 关联未声明时抛出(REF_UNKNOWN)
28
+ */
16
29
  function normalizeWith(model, withSpec) {
17
30
  if (!withSpec) return [];
18
- const arr = Array.isArray(withSpec) ? withSpec : [withSpec];
19
- const out = [];
31
+ let arr = Array.isArray(withSpec) ? withSpec : [withSpec];
32
+ let out = [];
20
33
  for (let i = 0; i < arr.length; i++) {
21
- const item = arr[i];
22
- const isStr = typeof item === 'string';
23
- const name = isStr ? item : (item.ref || item.name || item.as);
24
- const rel = findRelation(model, name);
34
+ let item = arr[i];
35
+ let is_str = typeof item === 'string';
36
+ let name = is_str ? item : (item.ref || item.name || item.as);
37
+ let rel = findRelation(model, name);
25
38
  if (!rel) raise('REF_UNKNOWN', '模型 ' + model.name + ' 未声明关联 ' + name);
26
39
  out.push({
27
40
  rel: rel,
28
- as: (!isStr && item.as) || rel.as || rel.name,
29
- select: (!isStr && item.select) || rel.select || null,
30
- mode: (!isStr && item.mode) || rel.mode || 'live'
41
+ as: (!is_str && item.as) || rel.as || rel.name,
42
+ select: (!is_str && item.select) || rel.select || null,
43
+ mode: (!is_str && item.mode) || rel.mode || 'live'
31
44
  });
32
45
  }
33
46
  return out;
34
47
  }
35
48
 
49
+ /**
50
+ * 数组去重并剔除 null/undefined,保持首次出现顺序
51
+ * @param {Array} vals - 原始数组
52
+ * @returns {Array} 去重后的数组
53
+ */
36
54
  function unique(vals) {
37
- const seen = new Set();
38
- const out = [];
55
+ let seen = new Set();
56
+ let out = [];
39
57
  for (let i = 0; i < vals.length; i++) {
40
- const v = vals[i];
58
+ let v = vals[i];
41
59
  if (v === undefined || v === null || seen.has(v)) continue;
42
60
  seen.add(v);
43
61
  out.push(v);
@@ -45,6 +63,14 @@ function unique(vals) {
45
63
  return out;
46
64
  }
47
65
 
66
+ /**
67
+ * 计算关联行在目标集合上的投影形态:无 select 时整行克隆,有 select 时按字段投影
68
+ * @param {object} world - 数据世界(池上下文)
69
+ * @param {object} target - 关联目标集合的模型定义
70
+ * @param {object} row - 目标行数据
71
+ * @param {Array|null} select - 投影字段列表,缺省时整行克隆
72
+ * @returns {object} 投影后的行数据
73
+ */
48
74
  function attachSelect(world, target, row, select) {
49
75
  if (!select) return clone(row);
50
76
  return project(row, select, target.key);
@@ -55,27 +81,27 @@ function attachSelect(world, target, row, select) {
55
81
  * 每个关联仅一次后端调用
56
82
  */
57
83
  function hydrate(world, model, rows, withSpec) {
58
- const specs = normalizeWith(model, withSpec);
84
+ let specs = normalizeWith(model, withSpec);
59
85
  if (!specs.length) return rows.map(function (r) { return clone(r); });
60
- const out = rows.map(function (r) { return clone(r); });
86
+ let out = rows.map(function (r) { return clone(r); });
61
87
 
62
88
  for (let i = 0; i < specs.length; i++) {
63
- const spec = specs[i];
64
- const rel = spec.rel;
65
- const target = world.model(rel.model);
89
+ let spec = specs[i];
90
+ let rel = spec.rel;
91
+ let target = world.model(rel.model);
66
92
  if (!target) raise('REF_UNKNOWN', '关联目标模型未注册: ' + rel.model);
67
93
 
68
94
  if (rel.type === 'one-to-many') {
69
- const via = rel.via || model.key;
70
- const keys = unique(out.map(function (r) { return r[rel.local || model.key]; }));
95
+ let via = rel.via || model.key;
96
+ let keys = unique(out.map(function (r) { return r[rel.local || model.key]; }));
71
97
  if (!keys.length) { for (let j = 0; j < out.length; j++) out[j][spec.as] = []; continue; }
72
- const q = {};
98
+ let q = {};
73
99
  q[via] = { $in: keys };
74
- const res = world._listBy(target.name, q, { limit: -1 });
75
- const groups = new Map();
100
+ let res = world._listBy(target.name, q, { limit: -1 });
101
+ let groups = new Map();
76
102
  for (let k = 0; k < res.list.length; k++) {
77
- const r = res.list[k];
78
- const g = r[via];
103
+ let r = res.list[k];
104
+ let g = r[via];
79
105
  if (!groups.has(g)) groups.set(g, []);
80
106
  groups.get(g).push(attachSelect(world, target, r, spec.select));
81
107
  }
@@ -83,16 +109,16 @@ function hydrate(world, model, rows, withSpec) {
83
109
  out[j][spec.as] = groups.get(out[j][rel.local || model.key]) || [];
84
110
  }
85
111
  } else {
86
- const foreign = rel.foreign || target.key;
87
- const keys = unique(out.map(function (r) { return r[rel.local]; }));
112
+ let foreign = rel.foreign || target.key;
113
+ let keys = unique(out.map(function (r) { return r[rel.local]; }));
88
114
  if (!keys.length) { for (let j = 0; j < out.length; j++) out[j][spec.as] = null; continue; }
89
- const q = {};
115
+ let q = {};
90
116
  q[foreign] = { $in: keys };
91
- const res = world._listBy(target.name, q, { limit: -1 });
92
- const map = new Map();
117
+ let res = world._listBy(target.name, q, { limit: -1 });
118
+ let map = new Map();
93
119
  for (let k = 0; k < res.list.length; k++) map.set(res.list[k][foreign], res.list[k]);
94
120
  for (let j = 0; j < out.length; j++) {
95
- const hit = map.get(out[j][rel.local]);
121
+ let hit = map.get(out[j][rel.local]);
96
122
  out[j][spec.as] = hit ? attachSelect(world, target, hit, spec.select) : null;
97
123
  }
98
124
  }
@@ -102,18 +128,18 @@ function hydrate(world, model, rows, withSpec) {
102
128
 
103
129
  /** 写时校验:所有 ref 字段指向的记录存在 */
104
130
  function validateRefs(world, model, body) {
105
- const errs = [];
106
- const schema = model.schema;
107
- for (const field in schema) {
108
- const ref = schema[field].ref;
131
+ let errs = [];
132
+ let schema = model.schema;
133
+ for (let field in schema) {
134
+ let ref = schema[field].ref;
109
135
  if (!ref) continue;
110
- const val = body[field];
136
+ let val = body[field];
111
137
  if (val === undefined || val === null) continue;
112
- if (ref.onMissing === 'keep' || ref.onMissing === 'null') continue;
138
+ if (ref.on_missing === 'keep' || ref.on_missing === 'null') continue;
113
139
  let target;
114
140
  try { target = world.model(ref.model); }
115
141
  catch (e) { errs.push(field + ' 关联模型未注册: ' + ref.model); continue; }
116
- const q = {};
142
+ let q = {};
117
143
  q[ref.key || target.key] = val;
118
144
  if (!world._existsBy(target.name, q)) {
119
145
  errs.push(field + '=' + val + ' 在 ' + target.name + ' 中不存在');
@@ -124,8 +150,8 @@ function validateRefs(world, model, body) {
124
150
 
125
151
  /** 找到指向某个模型的本表字段 */
126
152
  function localRefField(model, modelName) {
127
- for (const f in model.schema) {
128
- const ref = model.schema[f].ref;
153
+ for (let f in model.schema) {
154
+ let ref = model.schema[f].ref;
129
155
  if (ref && ref.model === modelName) return f;
130
156
  }
131
157
  return null;
@@ -133,23 +159,23 @@ function localRefField(model, modelName) {
133
159
 
134
160
  /** 写时快照:把静态表字段冗余进动态记录,并钉扎配置版本 */
135
161
  function snapshotFields(world, model, body) {
136
- const out = {};
162
+ let out = {};
137
163
  let pinned = null;
138
- for (const field in model.schema) {
139
- const spec = model.schema[field].snapshot;
164
+ for (let field in model.schema) {
165
+ let spec = model.schema[field].snapshot;
140
166
  if (!spec) continue;
141
- const parts = String(spec).split('.');
142
- const targetName = parts[0];
143
- const targetField = parts[1];
144
- const local = localRefField(model, targetName);
167
+ let parts = String(spec).split('.');
168
+ let target_name = parts[0];
169
+ let target_field = parts[1];
170
+ let local = localRefField(model, target_name);
145
171
  if (!local || body[local] === undefined) continue;
146
172
  let target;
147
- try { target = world.model(targetName); }
148
- catch (e) { continue; }
149
- const q = {};
173
+ try { target = world.model(target_name); }
174
+ catch (e) { raise('REF_UNKNOWN', '快照目标模型未注册: ' + target_name); }
175
+ let q = {};
150
176
  q[target.key] = body[local];
151
- const row = world._getBy(target.name, q);
152
- if (row && row[targetField] !== undefined) out[field] = clone(row[targetField]);
177
+ let row = world._getBy(target.name, q);
178
+ if (row && row[target_field] !== undefined) out[field] = clone(row[target_field]);
153
179
  if (target.readonly && target.version) pinned = target.version;
154
180
  }
155
181
  if (pinned && model.schema.cfg_ver) out.cfg_ver = pinned;
@@ -159,10 +185,10 @@ function snapshotFields(world, model, body) {
159
185
  /** 反查:从静态项查所有引用它的动态记录 */
160
186
  function reverse(world, opts) {
161
187
  opts = opts || {};
162
- const refModel = world.model(opts.ref);
163
- const q = {};
188
+ let ref_model = world.model(opts.ref);
189
+ let q = {};
164
190
  q[opts.via] = opts.key;
165
- return world._listBy(refModel.name, q, opts.options || { limit: 100 });
191
+ return world._listBy(ref_model.name, q, opts.options || { limit: 100 });
166
192
  }
167
193
 
168
194
  module.exports = {
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const { sqlAdmin } = require('mm_sql');
5
+ const { decode, encode, withTimeout } = require('./backend_codec.js');
6
+
7
+ /**
8
+ * mm_sql 适配器:可选的关系型 / JSON 数据源;集合以 (id, body) 两张通用列落地
9
+ */
10
+ class SqlAdapter {
11
+ /**
12
+ * 构造函数
13
+ * @param {object} [config] 适配器配置(scope/db_type/sqlite/enabled)
14
+ */
15
+ constructor(config) {
16
+ this.name = 'mm_sql';
17
+ this.config = Object.assign({
18
+ db_type: 'sqlite',
19
+ sqlite: { dir: path.join(process.cwd(), 'data', '_sql'), database: 'mm_datas' }
20
+ }, config || {});
21
+ this.enabled = !!(config && config.enabled);
22
+ this.connected = false;
23
+ this.reason = this.enabled ? '' : '未启用(可选数据源)';
24
+ this.client = null;
25
+ this.factory = 'sqlAdmin';
26
+ this.stats = { push: 0, pull: 0 };
27
+ }
28
+
29
+ /**
30
+ * 连接 sql 实例
31
+ * @returns {Promise<object>} 状态信息
32
+ */
33
+ async open() {
34
+ if (!this.enabled) return this.status();
35
+ this.client = sqlAdmin(this.config.scope, this.config);
36
+ this.connected = true;
37
+ return this.status();
38
+ }
39
+
40
+ /**
41
+ * 获取状态信息
42
+ * @returns {object} 状态信息
43
+ */
44
+ status() {
45
+ return {
46
+ name: this.name, enabled: this.enabled, factory: this.factory,
47
+ scope: this.config.scope, connected: this.connected,
48
+ way: this.config.way || this.config.db_type, db_type: this.config.db_type,
49
+ reason: this.reason, stats: this.stats
50
+ };
51
+ }
52
+
53
+ /** 未连接即报错 */
54
+ _client() {
55
+ if (!this.connected) throw new Error('mm_sql 未连接');
56
+ return this.client;
57
+ }
58
+
59
+ /**
60
+ * 取集合对应的物理表名
61
+ * @param {string} name 集合名
62
+ * @returns {string} 表名
63
+ * @private
64
+ */
65
+ _table(name) { return 'd_' + String(name).replace(/[^a-zA-Z0-9_]/g, '_'); }
66
+
67
+ /**
68
+ * 推送集合到关系表(先清表再整表写入)
69
+ * @param {string} name 集合名
70
+ * @param {string} key 主键字段名
71
+ * @param {Array} rows 记录列表
72
+ * @returns {Promise<object>} 推送结果
73
+ */
74
+ async push(name, key, rows) {
75
+ let client = this._client();
76
+ let table = this._table(name);
77
+ let job = (async function () {
78
+ await client.exec('CREATE TABLE IF NOT EXISTS ' + table + ' (id TEXT PRIMARY KEY, body TEXT)');
79
+ await client.exec('DELETE FROM ' + table);
80
+ for (let i = 0; i < rows.length; i++) {
81
+ let id = String(rows[i][key] === undefined ? i + 1 : rows[i][key]);
82
+ await client.exec('INSERT INTO ' + table + ' (id, body) VALUES (?, ?)',
83
+ [id, encode(rows[i])]);
84
+ }
85
+ return { ok: true, table: table, rows: rows.length };
86
+ })();
87
+ let out = await withTimeout(job, 8000, 'mm_sql 写入');
88
+ this.stats.push++;
89
+ return out;
90
+ }
91
+
92
+ /**
93
+ * 拉取集合记录
94
+ * @param {string} name 集合名
95
+ * @returns {Promise<Array|null>} 记录列表,无数据为 null
96
+ */
97
+ async pull(name) {
98
+ let rows = await withTimeout(
99
+ this._client().run('SELECT body FROM ' + this._table(name)), 8000, 'mm_sql 读取');
100
+ if (!Array.isArray(rows)) return null;
101
+ this.stats.pull++;
102
+ return rows.map(function (r) { return decode(r.body !== undefined ? r.body : r); });
103
+ }
104
+
105
+ /**
106
+ * 执行任意查询
107
+ * @param {string} sql SQL 语句
108
+ * @param {Array} [params] 参数列表
109
+ * @returns {Promise<object>} 查询结果
110
+ */
111
+ async query(sql, params) {
112
+ return withTimeout(this._client().run(sql, params || []), 8000, 'mm_sql 查询');
113
+ }
114
+ }
115
+
116
+ module.exports = SqlAdapter;