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, ''); } 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'); const msg = String(error?.message || error); // 幂等重放容错:仅「对象已存在」类错误(42710 等)视为已应用; // 外键缺失(23503)/ 唯一冲突(23505)说明数据有问题,必须让迁移失败,不能标记已应用。 const isDuplicateObject = /already exists/i.test(msg) && error?.code !== '23505' && error?.code !== '23503'; if (isDuplicateObject || error?.code === '42710') { await pool.query('INSERT INTO schema_migrations (filename) VALUES ($1) ON CONFLICT DO NOTHING', [filename]); console.log(`Skipped ${filename} (${msg.split('\n')[0]})`); return; } if (error?.code === '23503' || error?.code === '23505') { console.error( `\n[MIGRATION FAILED] ${filename}: ${error.code === '23503' ? '外键约束失败(依赖数据缺失)' : '唯一约束冲突(数据重复)'}\n` + ` ${msg.split('\n')[0]}\n` + ` 该迁移未标记为已应用,请修复数据后重跑迁移。\n` ); throw error; } 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(); } main().catch((error) => { console.error(error); process.exit(1); });