dsh-workbench-danmaku 0.4.1 → 0.4.8
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/CHANGELOG.md +28 -0
- package/lib/backend/backup-core.js +521 -0
- package/lib/backend/lww.js +51 -0
- package/lib/backend/schema.js +287 -0
- package/lib/backend/tag-source.js +149 -0
- package/lib/backup.js +85 -0
- package/lib/client.js +200 -187
- package/lib/db/db.js +58 -62
- package/lib/index.js +13 -20
- package/package.json +5 -4
- package/lib/actions/schema.js +0 -34
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 跨插件共享的表结构声明与幂等补齐。
|
|
3
|
+
*
|
|
4
|
+
* 设计目标:每个业务的建表语句与「老库补列」共用同一份列声明,
|
|
5
|
+
* CREATE TABLE 与 ALTER TABLE 都由这里生成,避免两套事实来源漂移。
|
|
6
|
+
*
|
|
7
|
+
* 约定:
|
|
8
|
+
* - 只依赖调用方传入的 node:sqlite DatabaseSync,不 import 任何业务域;
|
|
9
|
+
* - 所有补齐操作可重复执行:已存在的列/索引一律跳过;
|
|
10
|
+
* - 结构操作失败直接抛错(附带表名、列名与原因),不吞异常;
|
|
11
|
+
* - 列声明形如 { name, type, notNull, default, defaultSql, primaryKey }。
|
|
12
|
+
*
|
|
13
|
+
* 注意:SQLite 的 ALTER TABLE ADD COLUMN 不支持在无默认值时新增 NOT NULL 列,
|
|
14
|
+
* 遇到这种声明会抛出明确错误,要求调用方补默认值或改走重建表的数据迁移。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
let savepointSeq = 0;
|
|
18
|
+
|
|
19
|
+
const IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
20
|
+
const TYPE_RE = /^[A-Za-z][A-Za-z0-9_ ()]*$/;
|
|
21
|
+
|
|
22
|
+
function fail(message, cause) {
|
|
23
|
+
const error = new Error(message);
|
|
24
|
+
if (cause) error.cause = cause;
|
|
25
|
+
return error;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function ident(value, what) {
|
|
29
|
+
const text = String(value === undefined || value === null ? "" : value);
|
|
30
|
+
if (!IDENT_RE.test(text)) throw fail(what + " 不是合法标识符:" + JSON.stringify(text));
|
|
31
|
+
return text;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 把 JavaScript 值转成 SQL 字面量(只接受字符串、数字、布尔)。 */
|
|
35
|
+
export function sqlLiteral(value) {
|
|
36
|
+
if (typeof value === "string") return "'" + value.replace(/'/g, "''") + "'";
|
|
37
|
+
if (typeof value === "number") {
|
|
38
|
+
if (!Number.isFinite(value)) throw fail("默认值不是有限数字:" + value);
|
|
39
|
+
return String(value);
|
|
40
|
+
}
|
|
41
|
+
if (typeof value === "boolean") return value ? "1" : "0";
|
|
42
|
+
throw fail("不支持的默认值类型:" + typeof value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function normalizeColumn(column) {
|
|
46
|
+
if (!column || typeof column !== "object") throw fail("列声明必须是对象");
|
|
47
|
+
const name = ident(column.name, "列名");
|
|
48
|
+
const type = column.type === undefined || column.type === null ? "" : String(column.type).trim().toUpperCase();
|
|
49
|
+
if (type && !TYPE_RE.test(type)) throw fail("列 " + name + " 的类型不合法:" + type);
|
|
50
|
+
const notNull = !!column.notNull;
|
|
51
|
+
const primaryKey = !!column.primaryKey;
|
|
52
|
+
const hasDefault = column.default !== undefined && column.default !== null;
|
|
53
|
+
const hasDefaultSql = column.defaultSql !== undefined && column.defaultSql !== null;
|
|
54
|
+
if (hasDefault && hasDefaultSql) throw fail("列 " + name + " 不能同时声明 default 与 defaultSql");
|
|
55
|
+
return {
|
|
56
|
+
name,
|
|
57
|
+
type,
|
|
58
|
+
notNull,
|
|
59
|
+
primaryKey,
|
|
60
|
+
default: hasDefault ? column.default : null,
|
|
61
|
+
defaultSql: hasDefaultSql ? String(column.defaultSql) : null,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 生成单列的 SQL 片段(端口由调用方决定加在 CREATE 还是 ALTER 里)。 */
|
|
66
|
+
export function columnSql(column) {
|
|
67
|
+
const spec = normalizeColumn(column);
|
|
68
|
+
let sql = ident(spec.name, "列名");
|
|
69
|
+
if (spec.type) sql += " " + spec.type;
|
|
70
|
+
if (spec.primaryKey) sql += " PRIMARY KEY";
|
|
71
|
+
if (spec.notNull) sql += " NOT NULL";
|
|
72
|
+
if (spec.defaultSql !== null) sql += " DEFAULT " + spec.defaultSql;
|
|
73
|
+
else if (spec.default !== null) sql += " DEFAULT " + sqlLiteral(spec.default);
|
|
74
|
+
return sql;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 定义一张表:列声明、表级约束与索引在同一个对象里。
|
|
79
|
+
* 返回冻结后的声明,后续 CREATE TABLE、ensureColumns、audit 都读它。
|
|
80
|
+
*/
|
|
81
|
+
export function defineTable(def) {
|
|
82
|
+
if (!def || typeof def !== "object") throw fail("表声明必须是对象");
|
|
83
|
+
const name = ident(def.name, "表名");
|
|
84
|
+
if (!Array.isArray(def.columns) || def.columns.length === 0) throw fail("表 " + name + " 没有列声明");
|
|
85
|
+
const columns = def.columns.map(normalizeColumn);
|
|
86
|
+
const seen = new Set();
|
|
87
|
+
for (const column of columns) {
|
|
88
|
+
if (seen.has(column.name)) throw fail("表 " + name + " 的列 " + column.name + " 重复声明");
|
|
89
|
+
seen.add(column.name);
|
|
90
|
+
}
|
|
91
|
+
const constraints = (def.constraints || []).map(function (item) {
|
|
92
|
+
const text = String(item).trim();
|
|
93
|
+
if (!text) throw fail("表 " + name + " 含空约束");
|
|
94
|
+
return text;
|
|
95
|
+
});
|
|
96
|
+
const indexes = (def.indexes || []).map(function (item) {
|
|
97
|
+
const text = String(item).trim();
|
|
98
|
+
if (!text) throw fail("表 " + name + " 含空索引声明");
|
|
99
|
+
if (!/^(CREATE|DROP)\s/i.test(text)) throw fail("表 " + name + " 的索引必须是完整 SQL:" + text);
|
|
100
|
+
return text;
|
|
101
|
+
});
|
|
102
|
+
return Object.freeze({ name, columns: Object.freeze(columns), constraints: Object.freeze(constraints), indexes: Object.freeze(indexes) });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 由表声明生成 CREATE TABLE IF NOT EXISTS 语句。 */
|
|
106
|
+
export function createTableSql(def) {
|
|
107
|
+
const table = def && Array.isArray(def.columns) ? def : defineTable(def);
|
|
108
|
+
const lines = table.columns.map(columnSql).concat(table.constraints);
|
|
109
|
+
return "CREATE TABLE IF NOT EXISTS " + ident(table.name, "表名") + " (\n " + lines.join(",\n ") + "\n)";
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 读取真实表的列描述;表不存在时返回空数组,不抛错(供形状探测使用)。 */
|
|
113
|
+
export function tableColumns(db, table) {
|
|
114
|
+
if (!db || typeof db.prepare !== "function") throw fail("tableColumns 需要 node:sqlite DatabaseSync");
|
|
115
|
+
const name = ident(table, "表名");
|
|
116
|
+
const exists = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(name);
|
|
117
|
+
if (!exists) return [];
|
|
118
|
+
const rows = db.prepare("PRAGMA table_info(" + name + ")").all();
|
|
119
|
+
return rows.map(function (row) {
|
|
120
|
+
return {
|
|
121
|
+
name: String(row.name),
|
|
122
|
+
type: String(row.type || "").toUpperCase(),
|
|
123
|
+
notNull: Number(row.notnull) === 1,
|
|
124
|
+
defaultValue: row.dflt_value === undefined ? null : row.dflt_value,
|
|
125
|
+
primaryKey: Number(row.pk) > 0,
|
|
126
|
+
};
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 实际表里是否存在某一列。 */
|
|
131
|
+
export function hasColumn(db, table, column) {
|
|
132
|
+
return tableColumns(db, table).some(function (item) {
|
|
133
|
+
return item.name === String(column);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 表是否存在。 */
|
|
138
|
+
export function tableExists(db, table) {
|
|
139
|
+
if (!db || typeof db.prepare !== "function") throw fail("tableExists 需要 node:sqlite DatabaseSync");
|
|
140
|
+
const name = ident(table, "表名");
|
|
141
|
+
return !!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(name);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 用唯一命名的 SAVEPOINT 包住结构变更,失败时回滚本次补齐,成功即提交。 */
|
|
145
|
+
function withSavepoint(db, fn) {
|
|
146
|
+
savepointSeq += 1;
|
|
147
|
+
const name = "wb_schema_" + savepointSeq;
|
|
148
|
+
db.exec("SAVEPOINT " + name);
|
|
149
|
+
try {
|
|
150
|
+
const result = fn();
|
|
151
|
+
db.exec("RELEASE " + name);
|
|
152
|
+
return result;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
try {
|
|
155
|
+
db.exec("ROLLBACK TO " + name);
|
|
156
|
+
} finally {
|
|
157
|
+
db.exec("RELEASE " + name);
|
|
158
|
+
}
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 建表并补齐缺列(不建索引)。
|
|
165
|
+
*
|
|
166
|
+
* @returns {{created:boolean, added:string[], existing:string[]}}
|
|
167
|
+
*/
|
|
168
|
+
export function createTable(db, def) {
|
|
169
|
+
const table = def && Array.isArray(def.columns) && Array.isArray(def.indexes) ? def : defineTable(def);
|
|
170
|
+
return withSavepoint(db, function () {
|
|
171
|
+
const created = !tableExists(db, table.name);
|
|
172
|
+
try {
|
|
173
|
+
db.exec(createTableSql(table));
|
|
174
|
+
} catch (error) {
|
|
175
|
+
throw fail("建表失败:" + table.name + ":" + error.message, error);
|
|
176
|
+
}
|
|
177
|
+
const result = addMissingColumns(db, table);
|
|
178
|
+
return { created, added: result.added, existing: result.existing };
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function addMissingColumns(db, table) {
|
|
183
|
+
const current = new Set(
|
|
184
|
+
tableColumns(db, table.name).map(function (item) {
|
|
185
|
+
return item.name;
|
|
186
|
+
}),
|
|
187
|
+
);
|
|
188
|
+
const added = [];
|
|
189
|
+
const existing = [];
|
|
190
|
+
for (const column of table.columns) {
|
|
191
|
+
if (current.has(column.name)) {
|
|
192
|
+
existing.push(column.name);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (column.notNull && column.default === null && column.defaultSql === null) {
|
|
196
|
+
throw fail('表 "' + table.name + '" 补列 "' + column.name + '" 声明了 NOT NULL 但没有默认值,老库无法安全回填');
|
|
197
|
+
}
|
|
198
|
+
const sql = "ALTER TABLE " + ident(table.name, "表名") + " ADD COLUMN " + columnSql(column);
|
|
199
|
+
try {
|
|
200
|
+
db.exec(sql);
|
|
201
|
+
} catch (error) {
|
|
202
|
+
throw fail("表 " + table.name + " 补列 " + column.name + " 失败:" + error.message, error);
|
|
203
|
+
}
|
|
204
|
+
added.push(column.name);
|
|
205
|
+
current.add(column.name);
|
|
206
|
+
}
|
|
207
|
+
return { added, existing };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 补齐缺列:只新增缺失列,已存在列保持原形状,多余列忽略。
|
|
212
|
+
*
|
|
213
|
+
* @param {object} db node:sqlite DatabaseSync
|
|
214
|
+
* @param {string} table 表名
|
|
215
|
+
* @param {Array<object>} spec 列声明数组
|
|
216
|
+
*/
|
|
217
|
+
export function ensureColumns(db, table, spec) {
|
|
218
|
+
const name = ident(table, "表名");
|
|
219
|
+
if (!Array.isArray(spec) || spec.length === 0) throw fail("表 " + name + " 的补列声明为空");
|
|
220
|
+
if (!tableExists(db, name)) throw fail("表 " + name + " 不存在,不能补列");
|
|
221
|
+
const columns = spec.map(normalizeColumn);
|
|
222
|
+
const seen = new Set();
|
|
223
|
+
for (const column of columns) {
|
|
224
|
+
if (seen.has(column.name)) throw fail("表 " + name + " 的列 " + column.name + " 重复声明");
|
|
225
|
+
seen.add(column.name);
|
|
226
|
+
}
|
|
227
|
+
return withSavepoint(db, function () {
|
|
228
|
+
return addMissingColumns(db, { name, columns });
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* 执行索引声明(完整 CREATE INDEX / DROP INDEX 语句),可重复执行。
|
|
234
|
+
* 失败直接抛错,调用方如需容错请在业务层显式处理。
|
|
235
|
+
*/
|
|
236
|
+
export function ensureIndexes(db, table, indexes) {
|
|
237
|
+
const name = ident(table, "表名");
|
|
238
|
+
if (!Array.isArray(indexes)) throw fail("表 " + name + " 的索引声明必须是数组");
|
|
239
|
+
let executed = 0;
|
|
240
|
+
for (const item of indexes) {
|
|
241
|
+
const sql = String(item || "").trim();
|
|
242
|
+
if (!sql) throw fail("表 " + name + " 含空索引声明");
|
|
243
|
+
if (!/^(CREATE|DROP)\s/i.test(sql)) throw fail("表 " + name + " 的索引必须是完整 SQL:" + sql);
|
|
244
|
+
try {
|
|
245
|
+
db.exec(sql);
|
|
246
|
+
executed += 1;
|
|
247
|
+
} catch (error) {
|
|
248
|
+
throw fail("表 " + name + " 建索引失败:" + sql + ":" + error.message, error);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return executed;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* 建表 → 补列 → 建索引 的完整入口。
|
|
256
|
+
*
|
|
257
|
+
* @param {object} options { skipIndexes?: boolean },skipIndexes 供「先建表、迁移数据、再建唯一索引」的旧库场景使用。
|
|
258
|
+
*/
|
|
259
|
+
export function ensureTable(db, def, options) {
|
|
260
|
+
const table = def && Array.isArray(def.columns) && Array.isArray(def.indexes) ? def : defineTable(def);
|
|
261
|
+
const skipIndexes = !!(options && options.skipIndexes);
|
|
262
|
+
return withSavepoint(db, function () {
|
|
263
|
+
const created = !tableExists(db, table.name);
|
|
264
|
+
try {
|
|
265
|
+
db.exec(createTableSql(table));
|
|
266
|
+
} catch (error) {
|
|
267
|
+
throw fail("建表失败:" + table.name + ":" + error.message, error);
|
|
268
|
+
}
|
|
269
|
+
const result = addMissingColumns(db, table);
|
|
270
|
+
const indexCount = skipIndexes ? 0 : ensureIndexes(db, table.name, table.indexes);
|
|
271
|
+
return { created, added: result.added, existing: result.existing, indexes: indexCount };
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 供结构审计使用:把一组表声明展开成 { table, columns, indexes }。 */
|
|
276
|
+
export function describeTables(tables) {
|
|
277
|
+
return tables.map(function (def) {
|
|
278
|
+
const table = def && Array.isArray(def.columns) && Array.isArray(def.indexes) ? def : defineTable(def);
|
|
279
|
+
return {
|
|
280
|
+
table: table.name,
|
|
281
|
+
columns: table.columns.map(function (column) {
|
|
282
|
+
return column.name;
|
|
283
|
+
}),
|
|
284
|
+
indexes: table.indexes.slice(),
|
|
285
|
+
};
|
|
286
|
+
});
|
|
287
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 标签来源写入的共享实现(`tag_mapping.item_type` 的业务侧适配)。
|
|
3
|
+
*
|
|
4
|
+
* 契约见 `docs/specs/25-标签域解耦审计与改造.md`「6. 来源注册与映射写入门禁」:
|
|
5
|
+
* - 标签域(`wb-addon-tags` ≥ 1.7.1)用 `tag_source` 登记「哪个插件在用哪个 item_type」,
|
|
6
|
+
* 并在 `tag_mapping` 上装触发器:来源未注册(0 条)或重复(≥2 条)时拒绝一切写入;
|
|
7
|
+
* - 业务域负责启动时幂等登记自己的来源,写入前先判、写入异常时翻成统一可读文案。
|
|
8
|
+
*
|
|
9
|
+
* 三份逐字重复的插件实现(tasks / sites / storage)收敛到这里,插件只声明差异:
|
|
10
|
+
* 来源标识、归属包名、展示名、以及「标签域未安装时怎么办」的策略。
|
|
11
|
+
*
|
|
12
|
+
* 降级策略 `onMissingDomain`:
|
|
13
|
+
* - `"skip"`(默认):标签域没建 `tag_source` 表时跳过门禁,写入照常进行——标签是这些域的可选
|
|
14
|
+
* 能力,不能让没装标签插件的用户用不了任务/站点/储物。启动登记同样不报错。
|
|
15
|
+
* - `"throw"`:写入时抛 `TAG_DOMAIN_MISSING`,错误文案可读;用于「标签是显式入参、静默丢弃
|
|
16
|
+
* 会让人误以为存上了」的域(站点侧)。启动登记仍然不抛,避免插件加载被依赖缺失打断。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** 缺标签域时的两种声明策略,导出给测试与文档引用。 */
|
|
20
|
+
export var MISSING_POLICIES = ["skip", "throw"];
|
|
21
|
+
|
|
22
|
+
function coded(code, message) {
|
|
23
|
+
return Object.assign(new Error(message), { code: code });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 生成某个业务的标签来源适配器。
|
|
28
|
+
*
|
|
29
|
+
* @param {object} config
|
|
30
|
+
* @param {string} config.source `tag_mapping.item_type` / `tag_source.source` 的取值
|
|
31
|
+
* @param {string} config.owner 归属包名,写进 `tag_source.owner`
|
|
32
|
+
* @param {string} config.title 展示名,写进 `tag_source.title`
|
|
33
|
+
* @param {"skip"|"throw"} [config.onMissingDomain] 标签域未安装时的策略,默认 `"skip"`
|
|
34
|
+
* @param {() => number} config.now 业务域的时间戳函数
|
|
35
|
+
* @param {() => string} config.newId 业务域的 id 生成函数
|
|
36
|
+
* @param {(db: object, table: string) => boolean} config.tableExists 业务域的表存在判定
|
|
37
|
+
*/
|
|
38
|
+
export function createTagSource(config) {
|
|
39
|
+
var cfg = config || {};
|
|
40
|
+
var source = String(cfg.source || "");
|
|
41
|
+
var owner = String(cfg.owner || "");
|
|
42
|
+
var title = String(cfg.title || "");
|
|
43
|
+
var onMissingDomain = cfg.onMissingDomain === "throw" ? "throw" : "skip";
|
|
44
|
+
var now = cfg.now;
|
|
45
|
+
var newId = cfg.newId;
|
|
46
|
+
var tableExists = cfg.tableExists;
|
|
47
|
+
|
|
48
|
+
if (!source || !owner) throw new Error("createTagSource 需要 source 与 owner");
|
|
49
|
+
if (typeof now !== "function" || typeof newId !== "function" || typeof tableExists !== "function") {
|
|
50
|
+
throw new Error("createTagSource 需要 now/newId/tableExists 三个业务域助手");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 该来源的活跃注册行;没有 `tag_source` 表时返回空数组。 */
|
|
54
|
+
function tagSourceRows(db, src) {
|
|
55
|
+
if (!tableExists(db, "tag_source")) return [];
|
|
56
|
+
return db
|
|
57
|
+
.prepare("SELECT * FROM tag_source WHERE source=? AND deleted_at IS NULL ORDER BY created_at ASC, id ASC")
|
|
58
|
+
.all(String(src));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 恰好 1 条活跃注册才算 ready;`missing` 表示标签域还没建 `tag_source`(老版本),此时不做门禁。 */
|
|
62
|
+
function tagSourceReady(db, src) {
|
|
63
|
+
if (!tableExists(db, "tag_source")) return { ok: false, missing: true, count: 0, owners: [] };
|
|
64
|
+
var rows = tagSourceRows(db, src);
|
|
65
|
+
return {
|
|
66
|
+
ok: rows.length === 1,
|
|
67
|
+
missing: false,
|
|
68
|
+
count: rows.length,
|
|
69
|
+
owners: rows.map(function (r) { return String(r.owner); }),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 幂等登记本域来源;`tag_source` 不存在时跳过(老标签插件不认识来源注册)。 */
|
|
74
|
+
function ensureTagSource(db, src, own, label) {
|
|
75
|
+
if (!tableExists(db, "tag_source")) return { ok: false, missing: true, created: false };
|
|
76
|
+
var key = String(src === undefined || src === null ? "" : src).trim();
|
|
77
|
+
var by = String(own === undefined || own === null ? "" : own).trim();
|
|
78
|
+
if (!key || !by) return { ok: false, created: false };
|
|
79
|
+
var hit = db.prepare("SELECT id FROM tag_source WHERE source=? AND owner=? AND deleted_at IS NULL").get(key, by);
|
|
80
|
+
if (hit) return { ok: true, created: false, id: String(hit.id) };
|
|
81
|
+
var ts = now();
|
|
82
|
+
var id = newId();
|
|
83
|
+
db.prepare(
|
|
84
|
+
"INSERT INTO tag_source(id,source,owner,title,created_at,updated_at,deleted_at,rev) VALUES(?,?,?,?,?,?,NULL,1)",
|
|
85
|
+
).run(id, key, by, String(label || ""), ts, ts);
|
|
86
|
+
return { ok: true, created: true, id: id };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 按当前注册状态给出统一错误:0 条 = 未注册,≥2 条 = 标识重复。 */
|
|
90
|
+
function tagSourceError(db, src) {
|
|
91
|
+
var state = tagSourceReady(db, src);
|
|
92
|
+
if (state.count === 0) {
|
|
93
|
+
return coded(
|
|
94
|
+
"TAG_SOURCE_UNREGISTERED",
|
|
95
|
+
"标签来源未注册,无法操作(来源:" + src + ");先调用 tags.registerSource 注册该来源",
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
return coded(
|
|
99
|
+
"TAG_SOURCE_DUPLICATED",
|
|
100
|
+
"标签来源标识重复,无法操作(来源:" + src + ";归属:" + state.owners.join("、") +
|
|
101
|
+
");请先清理 tag_source 中的重复注册",
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 写入 `tag_mapping` 的统一入口:先判门禁,执行中触发器的原始错误翻成统一文案。
|
|
107
|
+
* `src` 省略时用本域默认来源。注册由启动时的 `ensureXxxTagSource` 负责,这里不补登记——
|
|
108
|
+
* 否则「被人工注销」会被静默覆盖,门禁也就失效了。
|
|
109
|
+
*/
|
|
110
|
+
function withTagSource(db, src, fn) {
|
|
111
|
+
var key = String(src || source);
|
|
112
|
+
var state = tagSourceReady(db, key);
|
|
113
|
+
if (state.missing) {
|
|
114
|
+
// 标签域未安装:按本域声明的策略放行或抛错(启动登记永远不抛,见 ensureTagSource)。
|
|
115
|
+
if (onMissingDomain === "throw") {
|
|
116
|
+
throw coded(
|
|
117
|
+
"TAG_DOMAIN_MISSING",
|
|
118
|
+
"标签域未安装(缺少 tag_source 表),无法写入标签归属;请先安装 wb-addon-tags(≥ 1.7.1),或改用不带标签的入参",
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return fn();
|
|
122
|
+
}
|
|
123
|
+
if (!state.ok) throw tagSourceError(db, key);
|
|
124
|
+
try {
|
|
125
|
+
return fn();
|
|
126
|
+
} catch (e) {
|
|
127
|
+
var msg = String((e && e.message) || "");
|
|
128
|
+
if (msg.indexOf("标签来源") >= 0) {
|
|
129
|
+
// 只有「此刻门禁确实不通过」才翻译成统一文案:登记正常却被触发器拒绝,说明是别的写入
|
|
130
|
+
// 约束(或并发注销),原样抛出比误报成「重复注册」更有助于定位。
|
|
131
|
+
var latest = tagSourceReady(db, key);
|
|
132
|
+
if (!latest.ok && !latest.missing) throw tagSourceError(db, key);
|
|
133
|
+
}
|
|
134
|
+
throw e;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
TAG_SOURCE: source,
|
|
140
|
+
TAG_SOURCE_OWNER: owner,
|
|
141
|
+
TAG_SOURCE_TITLE: title,
|
|
142
|
+
ON_MISSING_DOMAIN: onMissingDomain,
|
|
143
|
+
tagSourceRows: tagSourceRows,
|
|
144
|
+
tagSourceReady: tagSourceReady,
|
|
145
|
+
ensureTagSource: ensureTagSource,
|
|
146
|
+
tagSourceError: tagSourceError,
|
|
147
|
+
withTagSource: withTagSource,
|
|
148
|
+
};
|
|
149
|
+
}
|
package/lib/backup.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// 弹幕库的备份导入导出:只搬 danmaku 一张表,行内字段与库表同形(含墓碑),
|
|
3
|
+
// 导入按 id 幂等 upsert,同一份备份重复导入不会多出一行。
|
|
4
|
+
|
|
5
|
+
const COLUMNS = [
|
|
6
|
+
"id", "body", "tone", "enabled", "card", "font_size", "speed", "opacity", "font_weight",
|
|
7
|
+
"font_family", "band", "prefix", "chance", "sort_order", "created_at", "updated_at", "deleted_at", "rev",
|
|
8
|
+
];
|
|
9
|
+
|
|
10
|
+
export function exportDanmakuData(db) {
|
|
11
|
+
const rows = db.prepare("SELECT * FROM danmaku ORDER BY sort_order ASC, created_at ASC, id ASC").all();
|
|
12
|
+
return {
|
|
13
|
+
formatVersion: 1,
|
|
14
|
+
danmaku: rows.map((row) => {
|
|
15
|
+
const out = {};
|
|
16
|
+
for (const key of COLUMNS) out[key] = row[key] === undefined ? null : row[key];
|
|
17
|
+
return out;
|
|
18
|
+
}),
|
|
19
|
+
note: "只含弹幕库本体;播放节奏与桌面层开关属于本机配置,不进备份。",
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function importDanmakuData(db, raw, policy) {
|
|
24
|
+
let payload = raw;
|
|
25
|
+
if (typeof raw === "string") {
|
|
26
|
+
try {
|
|
27
|
+
payload = JSON.parse(raw);
|
|
28
|
+
} catch {
|
|
29
|
+
return { ok: false, imported: 0, failed: 0, skipped: 0, message: "备份内容不是合法 JSON" };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const rows = Array.isArray(payload && payload.danmaku) ? payload.danmaku : [];
|
|
33
|
+
const select = db.prepare("SELECT id, updated_at, deleted_at FROM danmaku WHERE id=?");
|
|
34
|
+
const selectBody = db.prepare("SELECT id FROM danmaku WHERE body=? AND deleted_at IS NULL");
|
|
35
|
+
const upsert = db.prepare(
|
|
36
|
+
"INSERT INTO danmaku (" + COLUMNS.join(",") + ") VALUES (" + COLUMNS.map(() => "?").join(",") + ") " +
|
|
37
|
+
"ON CONFLICT(id) DO UPDATE SET " + COLUMNS.filter((c) => c !== "id").map((c) => c + "=excluded." + c).join(", "),
|
|
38
|
+
);
|
|
39
|
+
let imported = 0;
|
|
40
|
+
let skipped = 0;
|
|
41
|
+
let failed = 0;
|
|
42
|
+
for (const row of rows) {
|
|
43
|
+
const id = String(row && row.id ? row.id : "").trim();
|
|
44
|
+
if (!id) {
|
|
45
|
+
failed += 1;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
const local = select.get(id);
|
|
50
|
+
if (local && policy === "skip") {
|
|
51
|
+
skipped += 1;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
// 未删除的行按 updated_at 判新旧;墓碑(deleted_at 非空)只做落库,不做「更新」判断。
|
|
55
|
+
if (local && policy === "newest" && row.deleted_at === null) {
|
|
56
|
+
const localTs = Number(local.updated_at) || 0;
|
|
57
|
+
const remoteTs = Number(row.updated_at) || 0;
|
|
58
|
+
if (local.deleted_at === null && localTs > remoteTs) {
|
|
59
|
+
skipped += 1;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// body 上有「未删除时唯一」的索引:同一句话换了 id 再导入会被索引拦下,
|
|
64
|
+
// 按同一行处理(跳过),避免整包因为一条重复内容失败。
|
|
65
|
+
if (!local && row.deleted_at === null) {
|
|
66
|
+
const same = selectBody.get(String(row.body || ""));
|
|
67
|
+
if (same && String(same.id) !== id) {
|
|
68
|
+
skipped += 1;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
upsert.run(...COLUMNS.map((key) => (row[key] === undefined ? null : row[key])));
|
|
73
|
+
imported += 1;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
failed += 1;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
ok: failed === 0,
|
|
80
|
+
imported,
|
|
81
|
+
failed,
|
|
82
|
+
skipped,
|
|
83
|
+
message: "导入弹幕 " + imported + " 条" + (skipped ? ",跳过 " + skipped + " 条" : "") + (failed ? ",失败 " + failed + " 条" : ""),
|
|
84
|
+
};
|
|
85
|
+
}
|