Files
SupplierSystem/server/src/migrate.ts
T
Ubuntu 5fa2bbfd55
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
2026-10-19 16:16:51 +08:00

252 lines
9.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from 'fs';
import path from 'path';
import { pool } from './db';
import { setupDatabase, resolveAppRoleName, quotePgIdent } from './setup-db';
import { seedPermissions } from './seed-permissions';
import { seedDemoData } from './seed-demo-data';
import { seedMobileAccounts } from './seed-mobile-accounts';
import { seedDefaultPurchaser } from './seed-default-purchaser';
import { seedE2eRolePasswords } from './seed-e2e-role-passwords';
const AUTH_BOOTSTRAP = `
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE SCHEMA IF NOT EXISTS auth;
CREATE OR REPLACE FUNCTION auth.uid()
RETURNS uuid
LANGUAGE sql
STABLE
AS $$ SELECT NULL::uuid $$;
CREATE TABLE IF NOT EXISTS auth.users (
instance_id UUID,
id UUID PRIMARY KEY,
aud VARCHAR(255),
role VARCHAR(255),
email VARCHAR(255) UNIQUE,
encrypted_password VARCHAR(255),
email_confirmed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
confirmation_token TEXT DEFAULT '',
recovery_token TEXT DEFAULT '',
email_change_token_new TEXT DEFAULT '',
email_change TEXT DEFAULT '',
raw_app_meta_data JSONB DEFAULT '{}'::jsonb,
raw_user_meta_data JSONB DEFAULT '{}'::jsonb
);
CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ DEFAULT NOW()
);
`;
/** 生产库 user_roles.role 为 varchar,兼容旧迁移里的 app_role 枚举写法 */
function normalizeMigrationSql(sql: string) {
return sql
.replace(/'::app_role/g, "'")
.replace(/::public\.app_role/g, '')
.replace(/::app_role/g, '');
}
/**
* 只对**可证明幂等**的「对象已存在」SQLSTATE 容错(DATA-6,2026-10-19):
* 42710 duplicate_object / 42P07 duplicate_table / 42701 duplicate_column / 42723 duplicate_function。
*
* 硬规则:
* · 不再用 /already exists/i 文本判断(未知 code 的同一文本必须失败);
* · 白名单命中 ⇒ warning 后继续下一个文件,但**绝不**写 schema_migrations(下次仍会重跑);
* · 23505/23503/42P01 等及未知错误 ⇒ 失败并抛出,同样不登记。
*/
const IDEMPOTENT_OBJECT_EXISTS_SQLSTATES = new Set(['42710', '42P07', '42701', '42723']);
export async function applySqlFile(filePath: string) {
const filename = path.basename(filePath);
const exists = await pool.query('SELECT 1 FROM schema_migrations WHERE filename = $1', [filename]);
if (exists.rowCount) return;
const rawSql = fs.readFileSync(filePath, 'utf8');
const sql = normalizeMigrationSql(rawSql);
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(sql);
await client.query('INSERT INTO schema_migrations (filename) VALUES ($1)', [filename]);
await client.query('COMMIT');
console.log(`Applied ${filename}`);
} catch (error: any) {
await client.query('ROLLBACK').catch(() => undefined);
const code = String(error?.code || '');
const msg = String(error?.message || error);
const firstLine = msg.split('\n')[0];
if (IDEMPOTENT_OBJECT_EXISTS_SQLSTATES.has(code)) {
// 对象已存在:幂等重放可接受,但**不登记**(本次文件可能只执行到一半,下次重跑继续尝试)
console.warn(`[MIGRATION] ${filename} 命中可幂等 SQLSTATE ${code}(${firstLine}),未登记 schema_migrations,下次迁移将重跑该文件`);
return;
}
console.error(
`\n[MIGRATION FAILED] ${filename}: SQLSTATE=${code || 'unknown'}\n` +
` ${firstLine}\n` +
(code === '23503'
? ' 外键约束失败(依赖数据缺失)'
: code === '23505'
? ' 唯一约束冲突(数据重复)'
: ' 非幂等错误(或未知错误码,文本 "already exists" 不再作为放行依据)') +
`\n 该迁移未标记为已应用,请修复后重跑迁移。\n`
);
throw error;
} finally {
client.release();
}
}
/** 生产/远程库无需在本机创建应用角色与数据库 */
function shouldRunLocalDbSetup(): boolean {
if (process.env.SKIP_LOCAL_DB_SETUP === '1') return false;
if (process.env.NODE_ENV === 'production') return false;
const dbUrl = process.env.DATABASE_URL || '';
if (dbUrl && !/(localhost|127\.0\.0\.1)/i.test(dbUrl)) return false;
return true;
}
async function main() {
console.log('Running database migrations...');
if (shouldRunLocalDbSetup()) {
await setupDatabase();
} else {
console.log('Skipping local database setup (remote/production database).');
await pool.query('SELECT 1');
console.log('Application database connection OK');
}
await pool.query(AUTH_BOOTSTRAP);
const migrationsDir =
process.env.MIGRATIONS_DIR || path.join(__dirname, '..', '..', 'migrations');
const files = fs
.readdirSync(migrationsDir)
.filter((f) => f.endsWith('.sql'))
.sort();
for (const file of files) {
await applySqlFile(path.join(migrationsDir, file));
}
// 阶段 5:补齐 tenant_template / 各 tenant_* 缺失业务表(列级 ALTER 须手写迁移)
try {
const ensured = await pool.query(
`SELECT public.ensure_tenant_schemas_match_template() AS n`
);
const n = Number(ensured.rows[0]?.n || 0);
if (n > 0) {
console.log(`ensure_tenant_schemas_match_template: cloned ${n} missing table(s)`);
}
} catch (error: any) {
if (/ensure_tenant_schemas_match_template/i.test(String(error?.message || ''))) {
console.warn('ensure_tenant_schemas_match_template skipped (function not yet applied)');
} else {
throw error;
}
}
// 阶段 5.1:名单守卫——模板里的普通表必须全部列入 tenant_business_tables(),
// 否则新建分公司会静默缺表(BR004 曾少 3 张)。断言失败即中断迁移(部署脚本不会重启 API)。
// 见 docs/design/20260915-tenant-table-list-guard.md
try {
await pool.query(`SELECT public.assert_tenant_template_matches_business_tables()`);
} catch (error: any) {
const msg = String(error?.message || error);
if (
/does not exist/i.test(msg) &&
/assert_tenant_template_matches_business_tables/i.test(msg)
) {
console.warn('assert_tenant_template_matches_business_tables skipped (function not yet applied)');
} else {
throw error;
}
}
// 20260815 只跑一次;克隆出的新 tenant_* 须每次幂等补齐 RLS/FORCE
try {
const rls = await pool.query(`SELECT public.ensure_all_tenant_core_rls() AS n`);
const n = Number(rls.rows[0]?.n || 0);
if (n > 0) {
console.log(`ensure_all_tenant_core_rls: applied on ${n} tenant schema(s)`);
}
} catch (error: any) {
if (/ensure_all_tenant_core_rls/i.test(String(error?.message || ''))) {
console.warn('ensure_all_tenant_core_rls skipped (function not yet applied)');
} else {
throw error;
}
}
const skipDemoAndTestSeeds = process.env.SKIP_DEMO_SEED === '1' || process.env.SKIP_E2E_SEED === '1';
if (!skipDemoAndTestSeeds) {
await pool.query(`
INSERT INTO categories (branch_code, category_code, category_name, level, status) VALUES
('BR001', 'VEG001', '蔬菜', 1, 1),
('BR001', 'MEAT001', '肉类', 1, 1),
('BR001', 'FRUIT001', '水果', 1, 1)
ON CONFLICT (branch_code, category_code) DO NOTHING
`).catch(() => undefined);
}
// 部署只同步权限目录;线上已配置的角色/功能模块映射必须原样保留。
await seedPermissions(pool, { resetBuiltinRoleMappings: false });
if (!skipDemoAndTestSeeds) {
await seedDefaultPurchaser(pool).catch((err) => console.warn('Default purchaser seed skipped:', err?.message));
await seedE2eRolePasswords(pool).catch((err) => console.warn('E2E role password seed skipped:', err?.message));
await seedDemoData(pool);
await seedMobileAccounts(pool).catch((err) => console.warn('Mobile seed skipped:', err?.message));
} else {
console.log('SKIP_DEMO_SEED/SKIP_E2E_SEED=1, demo/test account seed skipped.');
}
const profiles = await pool.query('SELECT COUNT(*)::int AS count FROM profiles');
if (profiles.rows[0]?.count === 0) {
console.log('Seeding profiles for default auth users...');
await pool.query(`
INSERT INTO profiles (id, username, full_name, status)
SELECT id,
COALESCE(raw_user_meta_data->>'username', split_part(email, '@', 1)),
COALESCE(raw_user_meta_data->>'full_name', split_part(email, '@', 1)),
1
FROM auth.users
ON CONFLICT (id) DO NOTHING
`);
}
console.log('Migrations complete.');
if (shouldRunLocalDbSetup()) {
// 授权目标必须是 DATABASE_URL 里的应用角色(供应商系统为 supplier);
// 此处曾硬编码主系统角色 canteen,会把本系统库的权限授给主系统角色。
const appRole = quotePgIdent(resolveAppRoleName());
await pool.query(`
GRANT ALL ON SCHEMA public TO ${appRole};
GRANT ALL ON SCHEMA auth TO ${appRole};
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO ${appRole};
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO ${appRole};
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA auth TO ${appRole};
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA auth TO ${appRole};
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO ${appRole};
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO ${appRole};
`).catch(() => undefined);
}
await pool.end();
}
// T4 测试卫生(T9 顺手修):仅作为入口脚本执行时才跑 main 并 process.exit;
// 被测试 import(applySqlFile 单测)时不得触发真实迁移/退出进程。
if (require.main === module) {
main().catch((error) => {
console.error(error);
process.exit(1);
});
}