'use strict'; /** * 迁移编排器(C3/A4):diff 两版定义 → 方言 SQL → 事务执行 → `__schemaMigration` 版本行 * * 七步编排(双端一致,执行文档 04 §4.2): * ① `oldDefs` 显式传入者优先(显式 > 探测);null → 经 `driver`(原生驱动实例,同 * syncSchema 惯例)introspect 拉当前物理结构(`schemaFromRows` 转 defn); * ② 逐 name `ddl.diffDefs(old, new)`; * ③ errors 非空 → 收集 skipped 并抛 `MigrationUnsupported`(附固定分步建议;不自动执行、不自动回滚); * ④ 白名单内 `generateMigration` 产方言 SQL 文本(不执行); * ⑤ 幂等闸:`__schemaMigration` 同 (tenant,env,backend,name) 最新行 hash 相同 → skipped 'unchanged'; * ⑥ 单表 SQL 与版本行在同一事务(runInTransaction)内执行/写入——失败整体回滚、无孤儿版本行; * ⑦ 汇总 `{applied, skipped}`。 * * 边界(执行文档 04 §5 步骤说明): * - 同批次多表不做跨表事务(每表独立事务 + 版本行);部分成功按 skipped/applied 对账重跑; * - 破坏性变更被拦后不提供自动回滚——`MigrationUnsupported` 只给分步建议; * - 版本表缺失时按 introspect 探测补建(DDL 由 core `ddl.generate` 产出,宿主不拼 SQL)。 * * D4-4 零语义拆分:纯逻辑(错误型与固定建议、hash 与版本行自然键、物理命名空间拷贝、 * 反推类型粒度对齐、段归一与版本号推导)下沉 ./migrate/plan,本文件保留编排与 IO; * 导出面(键名 / 键序 / 语义)与拆分前逐字一致。 */ const ddl = require('./ddl'); const { pname, ptable, builtinFieldNames, ownerField } = ddl; const introspect = require('./introspect'); const { core } = require('./schema'); const { MetaDefError, _runInternal, _MIGRATION } = require('./metadef'); const crud = require('./crud'); const { runInTransaction, executeRaw } = require('./datasource'); const { emit: emitFeedback } = require('./feedback-core'); const { _UNSUPPORTED_HINT, MigrationUnsupported, _hashOf, migrationId, _stripBuiltinFields, _physicalDefn, _alignTypes, _segOf, _versionOf, } = require('./migrate/plan'); /** 版本表存在性探测 SQL(表名为常量非用户输入,内联无注入面;宿主只读 SELECT, * 同 `introspect/.js` 既有惯例——introspect 需原生驱动实例,连接视图不暴露) */ const _PROBE_SQL = { sqlite: `SELECT name FROM sqlite_master WHERE type = 'table' AND name = '${_MIGRATION}'`, mysql: 'SELECT table_name AS name FROM information_schema.tables' + ` WHERE table_schema = DATABASE() AND table_name = '${_MIGRATION}'`, postgres: 'SELECT table_name AS name FROM information_schema.tables' + ` WHERE table_name = '${_MIGRATION}' AND table_schema = current_schema()`, }; async function _hasMigrationTable(backend, source) { const out = await executeRaw(source, _PROBE_SQL[backend], null, false); return (out.rows || []).length > 0; } /** * 迁移编排(A4)。 * * @param {object} o * @param {'sqlite'|'mysql'|'postgres'} o.backend 方言后端 * @param {string} o.source 数据源名(DDL 与版本表同源同事务) * @param {object} o.defs 目标定义 `{name: defn}`(与 persistDef 的 defn 同构) * @param {object|null} [o.oldDefs] 旧版定义 `{name: defn}`;null → introspect 探测(需 `driver`) * @param {object|null} [o.driver] 原生驱动实例(introspect 用;连接视图不暴露原生 handle, * 同 `syncSchema` 的 driver 惯例。oldDefs=null 时必填) * @param {string|null} [o.tenant] 租户段(null → 空串段,与 metadef 既有 null 处理一致) * @param {string|null} [o.env] 环境段(null → 空串段) * @returns {Promise<{applied: Array<{name, from, to, version}>, skipped: Array<{name, reason}>}>} */ /** 入参校验(defs 为 {name: defn} 对象)——拆出主编排保持单函数复杂度达标 */ function _assertArgs(backend, source, defs) { if (!backend || !source || !defs || typeof defs !== 'object' || Array.isArray(defs)) { throw new MetaDefError('migrate: backend/source/defs 必填(defs 为 {name: defn} 对象)'); } } /** * 版本表保障:有 driver 时一次完整 introspect(两用:版本表探测 + oldDefs=null 转 defn); * 无 driver 时退化为 executeRaw 只读探测。缺失才建(core 产 DDL;CREATE TABLE 非 IF NOT * EXISTS,幂等由探测保证)。ddl.generate 返回 `\n\n` 拼接语句串,executeRaw 单次单语句。 * 返回 probe(driver 模式的探测结果;无 driver 为 null)。 */ async function _ensureVersionTable({ backend, source, driver }) { let probe = null; let hasVersionTable = false; if (driver) { probe = await introspect.run(backend, driver, undefined); hasVersionTable = probe.tables.some((t) => t.name === _MIGRATION); } else { hasVersionTable = await _hasMigrationTable(backend, source); } if (!hasVersionTable) { const ensure = ddl.generate(backend, [_MIGRATION]); await runInTransaction(source, async () => { for (const sql of ensure.split('\n\n')) { if (sql.trim()) await executeRaw(source, sql, null, true); } }); } return probe; } /** * ① 旧版定义:oldDefs 显式传入者优先;null → 复用本次探测行转 defn(需 driver)。 * schemaFromRows 的 name 是物理表名(如 `notes`),与 defs 的 schema 名(如 `Note`) * 不同键——按 name 与 collection 双索引,查找时以 defs 侧 collection 兜底对齐 */ function _resolveOldDefs(oldDefs, probe, backend) { if (oldDefs !== null && oldDefs !== undefined) return oldDefs; if (!probe) { throw new MetaDefError( 'migrate: oldDefs 为 null 时需传 driver(introspect 需原生驱动实例,同 syncSchema 惯例);' + '或显式传入 oldDefs 跳过探测'); } const old = {}; for (const d of core.schemaFromRows(probe, backend)) { old[d.name] = d; if (d.collection && d.collection !== d.name) old[d.collection] = d; } return old; } /** * ⓪ 物理内建列完整性(仅 introspect 模式):camelCase 时代的老表缺 `__present` / * `created_by` / `created_at` 等内建列。先按当前 DDL 自动补列(老库照样迁得过去), * 同时发出可定位告警;**只有补列失败才中断**(保留真报错,不吞成静默通过)。 * ⓪b 归属键回填完整性:列已存在但值为 NULL ⇒ creator 行控下这些行对非 bypass 用户 * 不可见。迁移层不猜业务归属,放行但必须告警(no-error-masking:允许通过、禁止静默失守)。 */ async function _ensureBuiltinColumns({ backend, source, probe, name, defn, skipped }) { const table = ptable(backend, defn); if (!probe.tables.some((t) => t.name === table)) return; const have = new Set(probe.columns.filter((c) => c.table === table).map((c) => c.name)); const missing = [...new Set(builtinFieldNames(defn, backend).map((n) => pname(backend, n)))] .filter((n) => !have.has(n)); if (missing.length) { try { for (const stmt of ddl.implicitColumnDDL(backend, defn, have)) { await executeRaw(source, stmt, null, true); } } catch (e) { const reason = `物理表 ${table} 缺内建列 [${missing.join(', ')}],自动补列失败:${e.message};` + '请按当前 DDL 手工补列或重建表后重跑迁移'; skipped.push({ name, reason }); throw new MigrationUnsupported(`MIGRATION_UNSUPPORTED: ${reason}(${_UNSUPPORTED_HINT})`, skipped); } emitFeedback({ type: 'warning', code: 'migrationAutoAddBuiltinColumns', layer: 'migrate', message: `物理表 ${table} 缺内建列 [${missing.join(', ')}],已按当前 DDL 自动补列后继续迁移`, hint: '新补列的存量行为 NULL;归属键列需按业务回填后 creator 行控才可见', }); for (const n of missing) have.add(n); } const owner = ownerField(defn); if (owner) { const col = pname(backend, owner); const hit = await executeRaw( source, `SELECT 1 FROM ${table} WHERE ${col} IS NULL LIMIT 1`, null, false); if (hit.rows && hit.rows.length) { emitFeedback({ type: 'warning', code: 'migrationOwnerKeyNullRows', layer: 'migrate', message: `物理表 ${table} 的归属键 ${col} 存在 NULL 行:creator 行控下这些行对非 bypass 用户不可见`, hint: '请按业务回填归属键;迁移已继续,未静默拦截', }); } } } /** * ⓪c 归档表补齐(仅 introspect 模式):主表已存在时 addTable 分支不触发,老库常缺 * `_deleted` 附表(remove 报 no such table),或归档表由旧版 DDL 建出、缺 * 主表 timestamps 列(归档 INSERT 报 no column named created_at)。此处按当前 def 补建/补列。 */ function _ensureArchiveDDL(stmts, { backend, probe, defn }) { if (defn.archive === false) return; const mainTable = ptable(backend, defn); const archDefn = ddl.archiveDefnOf(defn); const archTable = ptable(backend, archDefn); const has = (n) => probe.tables.some((t) => t.name === n); if (!has(mainTable)) return; if (!has(archTable)) { stmts.unshift(...ddl.archiveDDL(backend, defn)); } else { // 内建列补齐(旧版归档表缺 created_at/updated_at/__present) const archHave = new Set(probe.columns.filter((c) => c.table === archTable).map((c) => c.name)); stmts.unshift(...ddl.implicitColumnDDL(backend, archDefn, archHave)); } } /** * ⑤ 幂等闸(先于 diff):同 (tenant,env,backend,name) 最新版本行 hash 相同 → unchanged, * 不 diff——introspect 反推类型粒度(如 SQLite INTEGER→number)与用户声明 * 粒度(int)不齐,重跑不应进 diff 被误报。latest 一并返回供版本号计算。 */ async function _migrationState({ source, seg, defn }) { const hash = _hashOf(defn); const rows = await crud.query( `${_MIGRATION}($condition:@c0, $sort:@s0){_id, version, hash}`, { c0: seg, s0: { version: -1 } }, { source }); return { unchanged: rows.length > 0 && rows[0].hash === hash, hash, latest: rows }; } /** 单个定义的迁移步骤(主循环体拆出;unchanged 返回 null,成功返回 applied 条目) */ async function _migrateOne({ backend, source, name, defn, old, probe, oldDefs, tenant, env, skipped }) { const oldDefn = _stripBuiltinFields(backend, old[name] || (defn.collection && old[defn.collection]) || null, defn); // ⓪/⓪b 内建列完整性与归属键回填告警(仅 introspect 模式) if (probe && oldDefs == null) { await _ensureBuiltinColumns({ backend, source, probe, name, defn, skipped }); } const seg = { tenant: _segOf(tenant), env: _segOf(env), backend, name }; const { unchanged, hash, latest } = await _migrationState({ source, seg, defn }); if (unchanged) { skipped.push({ name, reason: 'unchanged' }); return null; } // ②③ diff(物理命名空间):白名单外 → 收集 skipped 并抛 MigrationUnsupported(固定分步建议) const physNew = _alignTypes(backend, oldDefn, _physicalDefn(backend, defn)); const plan = ddl.diffDefs(oldDefn, physNew); if (plan.errors.length) { skipped.push({ name, reason: plan.errors }); throw new MigrationUnsupported( `MIGRATION_UNSUPPORTED: ${plan.errors.join(';')}(${_UNSUPPORTED_HINT})`, skipped); } // ④ 方言 SQL(纯文本) const stmts = ddl.generateMigration(backend, oldDefn, physNew); // ⓪c 归档表补齐(仅 introspect 模式) if (probe && oldDefs == null) { _ensureArchiveDDL(stmts, { backend, probe, defn }); } const { version, from } = _versionOf(latest); // ⑥ SQL 与版本行同事务:失败整体回滚、无孤儿版本行 await runInTransaction(source, async () => { for (const sql of stmts) await executeRaw(source, sql, null, true); await _runInternal(() => crud.insert(_MIGRATION, { _id: migrationId(tenant, env, backend, name, version), ...seg, hash, version, appliedAt: Date.now(), sqls: stmts, }, { source })); }); return { name, from, to: version, version }; } // 入参为宿主透传的开放形状(backend/source/defs + 可选驱动/租户/环境覆盖) async function migrate(/** @type {any} */ { backend, source, defs, oldDefs = null, driver = null, tenant = null, env = null } = {}) { _assertArgs(backend, source, defs); const probe = await _ensureVersionTable({ backend, source, driver }); const old = _resolveOldDefs(oldDefs, probe, backend); const applied = []; const skipped = []; for (const [name, defn] of Object.entries(defs)) { const entry = await _migrateOne({ backend, source, name, defn, old, probe, oldDefs, tenant, env, skipped }); if (entry) applied.push(entry); } // ⑦ 汇总 return { applied, skipped }; } // 单函数入口导出(辅助件挂函数属性;错误类另在 src/index.js 顶层直达) migrate.MigrationUnsupported = MigrationUnsupported; migrate.migrationId = migrationId; migrate.UNSUPPORTED_HINT = _UNSUPPORTED_HINT; module.exports = { migrate, MigrationUnsupported, migrationId, _UNSUPPORTED_HINT };