'use strict'; const MANAGED_TYPES = Object.freeze({ CURRENT: 'current', HISTORY: 'history', DISPATCH: 'dispatch', OUTSOURCED: 'outsourced', }); /** * 自增水位修复时的安全余量。 * * 修复水位时会读取各分表 MAX(id) 作为基准,但读取与 SET 之间存在并发窗口: * 其他请求可能正在抢号分配更大的 id。若 SET 值刚好是 MAX(id)+1,并发插入 * 提交后表内 max 可能再次超过水位。预留余量(跳过若干 id)可避免该竞态, * BIGINT 空间下跳过几十个 id 无实际影响。 */ const AUTO_INCREMENT_SAFE_MARGIN = 50; const TABLE_PATTERNS = Object.freeze([ { type: MANAGED_TYPES.DISPATCH, pattern: /^wms_order_delivery_(\d+)_dispatch$/, }, { type: MANAGED_TYPES.HISTORY, pattern: /^wms_order_delivery_(\d+)_history$/, }, { type: MANAGED_TYPES.OUTSOURCED, pattern: /^wms_order_delivery_(\d+)_outsourced$/, }, { type: MANAGED_TYPES.CURRENT, pattern: /^wms_order_delivery_(\d+)$/, }, ]); /** * 规范化订单工厂管理的模型类型。 * @param {string} type 模型类型。 * @return {string} 规范化后的模型类型。 */ function normalizeManagedType(type) { return Object.values(MANAGED_TYPES).includes(type) ? type : MANAGED_TYPES.CURRENT; } /** * 判断是否为配送域类型。 * @param {string} type 模型类型。 * @return {boolean} 是否为配送域类型。 */ function isDispatchType(type) { return normalizeManagedType(type) === MANAGED_TYPES.DISPATCH; } /** * 判断是否为历史类型。 * @param {string} type 模型类型。 * @return {boolean} 是否为历史类型。 */ function isHistoryType(type) { return normalizeManagedType(type) === MANAGED_TYPES.HISTORY; } /** * 判断是否为 outsourced 类型。 * @param {string} type 模型类型。 * @return {boolean} 是否为 outsourced 类型。 */ function isOutsourcedType(type) { return normalizeManagedType(type) === MANAGED_TYPES.OUTSOURCED; } /** * 克隆模型属性定义,避免直接修改基础模型对象。 * @param {Object} attributes 原始属性定义。 * @return {Object} 克隆后的属性定义。 */ function cloneAttributes(attributes) { return Object.entries(attributes).reduce((result, [ name, attribute ]) => { result[name] = { ...attribute }; return result; }, {}); } /** * 规范化索引字段定义。 * @param {string|Object} field 字段定义。 * @return {{ attribute: string, length?: number }} 规范化后的字段定义。 */ function normalizeIndexField(field) { if (typeof field === 'string') { return { attribute: field }; } if (!field || typeof field !== 'object') { return { attribute: String(field) }; } const attribute = field.attribute || field.name || field.field || field.columnName || field.column_name; const normalizedField = { attribute: attribute ? String(attribute) : '', }; if (Object.prototype.hasOwnProperty.call(field, 'length') && field.length !== undefined && field.length !== null) { normalizedField.length = Number(field.length); } return normalizedField; } /** * 规范化索引定义。 * @param {Object} index 索引定义。 * @return {{ name: string, unique: boolean, fields: Array }} 规范化后的索引定义。 */ function normalizeIndexDefinition(index) { return { name: index.name || index.Key_name || index.key_name || '', unique: Boolean(index.unique || index.Unique || (typeof index.nonUnique === 'number' ? index.nonUnique === 0 : false)), fields: Array.isArray(index.fields) ? index.fields.map(normalizeIndexField) : [], }; } /** * 规范化 Sequelize 数值类型的 SQL 定义。 * @param {Object} attribute Sequelize 属性定义。 * @return {{ type: string, unsigned: boolean, min: string, max: string, precision?: number, scale?: number }|null} 数值约束信息。 */ function parseNumericConstraint(attribute) { let typeSql = ''; if (attribute && attribute.type && typeof attribute.type.toSql === 'function') { try { typeSql = attribute.type.toSql(); } catch (error) { return null; } } else { typeSql = String(attribute && attribute.type || ''); } const normalizedTypeSql = String(typeSql || '') .trim() .replace(/\s+/g, ' ') .toUpperCase(); if (!normalizedTypeSql) { return null; } const integerMatch = normalizedTypeSql.match(/^(TINYINT|SMALLINT|MEDIUMINT|INT|INTEGER|BIGINT)\s*(?:\(\s*\d+\s*\))?(?:\s+UNSIGNED)?$/i); if (integerMatch) { const integerBits = { TINYINT: 8, SMALLINT: 16, MEDIUMINT: 24, INT: 32, INTEGER: 32, BIGINT: 64, }[integerMatch[1].toUpperCase()]; const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql); const bigBits = BigInt(integerBits); const max = unsigned ? (2n ** bigBits) - 1n : (2n ** (bigBits - 1n)) - 1n; const min = unsigned ? 0n : -(2n ** (bigBits - 1n)); return { type: integerMatch[1].toUpperCase(), unsigned, min: min.toString(), max: max.toString(), }; } const decimalMatch = normalizedTypeSql.match(/^(DECIMAL|NUMERIC)\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)(?:\s+UNSIGNED)?$/i); if (decimalMatch) { const precision = Number(decimalMatch[2]); const scale = Number(decimalMatch[3]); const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql); const integerDigits = precision - scale; if (!Number.isInteger(precision) || !Number.isInteger(scale) || precision <= 0 || scale < 0 || integerDigits <= 0) { return null; } const integerPart = '9'.repeat(integerDigits); const decimalPart = scale > 0 ? `.${'9'.repeat(scale)}` : ''; return { type: decimalMatch[1].toUpperCase(), unsigned, precision, scale, min: `-${integerPart}${decimalPart}`, max: `${integerPart}${decimalPart}`, }; } return null; } /** * 生成默认值 SQL 片段。 * @param {*} defaultValue 默认值。 * @return {string} SQL 片段。 */ function formatDefaultValue(defaultValue) { if (defaultValue === null) { return 'NULL'; } if (defaultValue === undefined) { return ''; } if (defaultValue && typeof defaultValue.toSql === 'function') { const rawSql = String(defaultValue.toSql()); // Sequelize.NOW 的 toSql() 返回 'NOW',MySQL/MariaDB 的 DATETIME 列 // 默认值必须写成 CURRENT_TIMESTAMP,否则生成 DEFAULT NOW 非法语法 return rawSql.trim().toUpperCase() === 'NOW' ? 'CURRENT_TIMESTAMP' : rawSql; } if (typeof defaultValue === 'string') { const escaped = defaultValue.replace(/'/g, "''"); return `'${escaped}'`; } if (typeof defaultValue === 'number' || typeof defaultValue === 'bigint') { return String(defaultValue); } if (typeof defaultValue === 'boolean') { return defaultValue ? '1' : '0'; } return `'${String(defaultValue).replace(/'/g, "''")}'`; } /** * 生成属性的类型 SQL 片段。 * @param {Object} attribute Sequelize 属性定义。 * @return {string} 类型 SQL 片段。 */ function buildColumnTypeSql(attribute) { let typeSql; if (attribute.type && Array.isArray(attribute.type.values)) { // ENUM 类型:type.toSql() 内部调 this.sequelize.escape(),sequelize 引用可能未绑定 // 直接用安全转义构造,避免依赖 sequelize 实例 const escaped = attribute.type.values.map(v => `'${String(v).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`).join(', '); typeSql = `ENUM(${escaped})`; } else if (attribute.type && typeof attribute.type.toSql === 'function') { typeSql = attribute.type.toSql(); } else { typeSql = String(attribute.type || ''); } // 无 dialect 绑定时 DataTypes.DATE 序列化为 'DATE', // 但 MySQL 实际列类型是 DATETIME;DDL 若输出 DATE 会把时间部分截断 if (typeSql && String(typeSql).trim().toUpperCase() === 'DATE') { typeSql = 'DATETIME'; } return typeSql; } /** * 归一化列类型 SQL,用于模型定义与实际表结构的语义比对。 * * 消除不会影响语义的差异,避免比对恒真而反复执行 ALTER: * - INTEGER 与 INT 在 MySQL 中是同义词; * - 整型 display width(如 BIGINT(20)、INT(11))不影响语义, * 且 MySQL 8.0.19+ 的 information_schema 不再返回 display width; * - 大小写与空格差异。 * * @param {string} sql 类型 SQL。 * @return {string} 归一化后的类型 SQL。 */ function normalizeColumnTypeSql(sql) { let normalized = String(sql || '') .trim() .replace(/\s+/g, ' ') .toUpperCase(); normalized = normalized.replace(/^INTEGER\b/, 'INT'); normalized = normalized.replace(/^(TINYINT|SMALLINT|MEDIUMINT|INT|BIGINT)\s*\(\s*\d+\s*\)/, '$1'); // Sequelize 无 dialect 绑定时 DATE 序列化为 'DATE',而 MySQL 实际列类型为 DATETIME if (normalized === 'DATE') { normalized = 'DATETIME'; } // 删除逗号两侧空格(ENUM 值列表、DECIMAL(18, 2) 等) normalized = normalized.replace(/\s*,\s*/g, ','); return normalized; } /** * 判断列定义是否与模型期望存在语义差异。 * * 与 needsTableSchemaSync / alterManagedTableSchema 共用同一套比较规则, * 保证“判定需要同步”与“生成 ALTER 子句”不会漂移。 * * @param {string} columnName 列名。 * @param {Object} expectedAttribute 模型期望的属性定义。 * @param {Object} actualColumn describeTable 返回的实际列定义。 * @return {boolean} 是否存在语义差异。 */ function isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumn) { const expectedType = normalizeColumnTypeSql(buildColumnTypeSql(expectedAttribute)); const actualType = normalizeColumnTypeSql(actualColumn && (actualColumn.type || actualColumn.Type) || ''); if (expectedType && actualType && expectedType !== actualType) { return true; } // 主键/自增列在建表时由 Sequelize 自动补 NOT NULL, // 即使模型定义未显式声明 allowNull: false,实际列也是 NOT NULL const expectedAllowNull = expectedAttribute.primaryKey || expectedAttribute.autoIncrement ? false : expectedAttribute.allowNull !== false; const actualAllowNull = (actualColumn && actualColumn.allowNull) !== false; if (expectedAllowNull !== actualAllowNull) { return true; } const expectedDefault = Object.prototype.hasOwnProperty.call(expectedAttribute, 'defaultValue') ? expectedAttribute.defaultValue : undefined; const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn || {}, 'defaultValue') ? actualColumn.defaultValue : undefined; // Sequelize.literal(如 CURRENT_TIMESTAMP)提取其原始表达式参与比较; // Sequelize.NOW 的 val 为 'NOW',与表内实际 DEFAULT CURRENT_TIMESTAMP 归一 const extractDefaultValue = value => { if (value && typeof value === 'object' && typeof value.val === 'string') { return String(value.val).trim().toUpperCase() === 'NOW' ? 'CURRENT_TIMESTAMP' : value.val; } return value; }; const normalizedExpectedDefault = extractDefaultValue(expectedDefault) == null ? null : String(extractDefaultValue(expectedDefault)); const normalizedActualDefault = extractDefaultValue(actualDefault) == null ? null : String(extractDefaultValue(actualDefault)); if (normalizedExpectedDefault === normalizedActualDefault) { return false; } // 数字默认值允许不同文本表示(如 '0' 与 '0.00'),只要数值相等即视为一致 if (normalizedExpectedDefault !== null && normalizedActualDefault !== null) { const expectedNumber = Number(normalizedExpectedDefault); const actualNumber = Number(normalizedActualDefault); if (normalizedExpectedDefault !== '' && normalizedActualDefault !== '' && Number.isFinite(expectedNumber) && Number.isFinite(actualNumber) && expectedNumber === actualNumber) { return false; } } return true; } /** * 将 Sequelize 属性定义转换为 DDL 列片段。 * @param {string} columnName 列名。 * @param {Object} attribute Sequelize 属性定义。 * @return {string} DDL 列片段。 */ function buildColumnLine(columnName, attribute) { const typeSql = buildColumnTypeSql(attribute); const parts = [ `\`${columnName}\``, typeSql ]; if (attribute.allowNull === false) { parts.push('NOT NULL'); } if (attribute.autoIncrement) { parts.push('AUTO_INCREMENT'); } if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) { const defaultSql = formatDefaultValue(attribute.defaultValue); if (defaultSql) { parts.push(`DEFAULT ${defaultSql}`); } } if (attribute.comment) { parts.push(`COMMENT '${String(attribute.comment).replace(/'/g, "''")}'`); } return parts.join(' '); } /** * 构建模型属性定义。 * @param {Object} app Egg 应用实例。 * @param {string} type 模型类型。 * @return {Object} 属性定义。 */ function buildTableAttributes(app, type) { const modelType = normalizeManagedType(type); const attributes = cloneAttributes(app.model.OrderDelivery.rawAttributes); // 分表 id 统一由仓库序列表显式分配,分表自身不再携带自增序列。 // 保留两套发号序列(分表自增 + 序列表)会在降级等场景产生区间重叠的冲突 id, // 这里从模型层移除 autoIncrement:新建分表不再带 AUTO_INCREMENT; // 已有分表结构保持不变(不执行任何 id 列变更),显式 id 插入不受影响。 attributes.id = { ...attributes.id, autoIncrement: false }; if (isDispatchType(modelType)) { const { ENUM } = app.Sequelize; attributes.dispatch_lane = { type: ENUM('m4', 'm5'), field: 'dispatch_lane', allowNull: false, defaultValue: 'm4', comment: '配送工作台子域(M4正常/M5异常)', }; } if (isHistoryType(modelType)) { attributes.archive_time = { type: app.Sequelize.DATE, field: 'archive_time', allowNull: true, defaultValue: null, comment: '归档时间', }; } return attributes; } /** * 构建表名。 * @param {number|string} warehouseId 仓库ID。 * @param {string} type 模型类型。 * @return {string} 表名。 */ function buildTableName(warehouseId, type) { const modelType = normalizeManagedType(type); if (isDispatchType(modelType)) { return `wms_order_delivery_${warehouseId}_dispatch`; } if (isOutsourcedType(modelType)) { return `wms_order_delivery_${warehouseId}_outsourced`; } const suffix = isHistoryType(modelType) ? '_history' : ''; return `wms_order_delivery_${warehouseId}${suffix}`; } /** * 构建表注释。 * @param {number|string} warehouseId 仓库ID。 * @param {string} type 模型类型。 * @return {string} 表注释。 */ function buildTableComment(warehouseId, type) { const modelType = normalizeManagedType(type); if (isDispatchType(modelType)) { return `仓库${warehouseId}发货单配送域(M4/M5)影子表`; } if (isHistoryType(modelType)) { return `仓库${warehouseId}发货单历史表`; } if (isOutsourcedType(modelType)) { return `仓库${warehouseId}发货单外仓表`; } return `仓库${warehouseId}发货单常用表`; } /** * 构建模型选项。 * @param {Object} app Egg 应用实例。 * @param {number|string} warehouseId 仓库ID。 * @param {string} type 模型类型。 * @return {Object} Sequelize 模型选项。 */ function buildTableOptions(app, warehouseId, type) { const modelType = normalizeManagedType(type); const options = { tableName: buildTableName(warehouseId, modelType), timestamps: false, comment: buildTableComment(warehouseId, modelType), indexes: buildIndexOptions(warehouseId, modelType), }; if (isHistoryType(modelType)) { options.fields = Object.keys(buildTableAttributes(app, modelType)); } return options; } /** * 构建索引选项。 * @param {number|string} warehouseId 仓库ID。 * @param {string} type 模型类型。 * @return {Array} 索引选项。 */ function buildIndexOptions(warehouseId, type) { const modelType = normalizeManagedType(type); const prefix = `${warehouseId}_${modelType}`; if (isDispatchType(modelType)) { const baseIndexes = buildIndexOptions(warehouseId, MANAGED_TYPES.CURRENT); const dispatchLaneIndex = { name: `idx_dispatch_${warehouseId}_dispatch_lane`, fields: [ 'dispatch_lane', 'status' ], }; return [ baseIndexes[0], baseIndexes[1], baseIndexes[2], dispatchLaneIndex, ...baseIndexes.slice(3), ]; } const indexes = [ { name: `idx_${prefix}_store_id`, fields: [ 'store_id' ], }, { name: `idx_${prefix}_warehouse_id`, fields: [ 'warehouse_id' ], }, { name: `idx_${prefix}_delivery_code`, unique: true, fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ], }, { name: `idx_${prefix}_items`, fields: [{ attribute: 'items', length: 50 }], }, { name: `idx_${prefix}_items_hash`, fields: [ 'items_hash' ], }, { name: `idx_${prefix}_hash_crc`, fields: [ 'items_hash', 'items_crc', 'warehouse_id' ], }, // wave_id 前导索引仅 current 分表需要:dispatch 通过 baseIndexes 自动继承; // history/outsourced 分表未在迁移中加该索引,模型不得生成预期定义, // 否则运行时 drift 同步会向其自动补建索引,造成模型与实际库不一致。 ...(modelType === MANAGED_TYPES.CURRENT ? [ { name: `idx_${prefix}_wave_id`, fields: [ 'wave_id' ], }, ] : []), { name: `idx_${prefix}_wave`, fields: [ 'status', 'wave_id' ], }, { name: `idx_${prefix}_statuses`, fields: [ 'status', 'post_status', 'pick_status', 'pack_status', 'outbound_status', ], }, ]; if (isHistoryType(modelType)) { indexes.push({ name: `idx_${warehouseId}_history_archive_time`, fields: [ 'archive_time' ], }); } return indexes; } /** * 将索引选项转换为 DDL 片段。 * @param {Object} index 索引定义。 * @return {string} DDL 索引片段。 */ function buildIndexLine(index) { const fieldParts = index.fields.map(field => { const normalizedField = normalizeIndexField(field); const length = Object.prototype.hasOwnProperty.call(normalizedField, 'length') ? `(${normalizedField.length})` : ''; return `\`${normalizedField.attribute}\`${length}`; }); const prefix = index.unique ? 'UNIQUE KEY' : 'KEY'; return `${prefix} \`${index.name}\` (${fieldParts.join(',')})`; } /** * 构建表列定义行。 * @param {Object} app Egg 应用实例。 * @param {string} type 模型类型。 * @return {Array} 列定义行。 */ function buildColumnLines(app, type) { return Object.entries(buildTableAttributes(app, type)).map(([ columnName, attribute ]) => buildColumnLine(columnName, attribute)); } /** * 构建表索引定义行。 * @param {number|string} warehouseId 仓库ID。 * @param {string} type 模型类型。 * @return {Array} 索引定义行。 */ function buildIndexLines(warehouseId, type) { return buildIndexOptions(warehouseId, type).map(buildIndexLine); } /** * 解析订单工厂管理的表名。 * @param {string} tableName 表名。 * @return {{ type: string, warehouseId: string }|null} 解析结果。 */ function parseManagedTableName(tableName) { for (const item of TABLE_PATTERNS) { const match = item.pattern.exec(tableName); if (match) { return { type: item.type, warehouseId: match[1], }; } } return null; } module.exports = { MANAGED_TYPES, AUTO_INCREMENT_SAFE_MARGIN, normalizeManagedType, isDispatchType, isHistoryType, isOutsourcedType, normalizeIndexField, normalizeIndexDefinition, parseNumericConstraint, buildTableAttributes, buildTableName, buildTableComment, buildTableOptions, buildIndexOptions, buildColumnTypeSql, normalizeColumnTypeSql, isColumnDefinitionDifferent, buildColumnLine, buildColumnLines, buildIndexLines, parseManagedTableName, };