Files
SupplierSystem/server/scripts/compare-local-prod-db.ts
T
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

205 lines
6.6 KiB
TypeScript

/**
* Compare local vs production DB: schema_migrations + public tables + key grants.
* Usage (from server/): npx tsx --env-file=.env scripts/compare-local-prod-db.ts
* Prod snapshot file: ../tmp/prod-db-snapshot.json (written by SSH helper)
*/
import fs from 'fs';
import path from 'path';
import pg from 'pg';
type Snapshot = {
label: string;
migrations: string[];
tables: string[];
registryGrant?: string | null;
registryCount?: number | null;
tableCounts?: Record<string, number>;
};
type Snapshot = {
label: string;
migrations: string[];
tables: string[];
tenantSchemas?: string[];
registryRows?: string[];
registryGrant?: string | null;
registryCount?: number | null;
countSource?: string | null;
tableCounts?: Record<string, number>;
};
async function snapshotLocal(): Promise<Snapshot> {
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
try {
const mig = await pool.query(
`SELECT filename FROM schema_migrations ORDER BY filename`
);
const tables = await pool.query(
`SELECT tablename
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY tablename`
);
const schemas = await pool.query(
`SELECT nspname FROM pg_namespace WHERE nspname LIKE 'tenant_%' ORDER BY nspname`
);
let registryGrant: string | null = null;
let registryCount: number | null = null;
let registryRows: string[] = [];
try {
const g = await pool.query(
`SELECT COALESCE(
(SELECT string_agg(privilege_type, ',' ORDER BY privilege_type)
FROM information_schema.role_table_grants
WHERE table_schema='public'
AND table_name='tenant_schema_registry'
AND grantee='canteen_app_rls'),
'(no grants)'
) AS grants`
);
registryGrant = g.rows[0]?.grants || null;
} catch {
registryGrant = '(query failed)';
}
try {
const c = await pool.query(`SELECT count(*)::int AS n FROM public.tenant_schema_registry`);
registryCount = c.rows[0].n;
const rows = await pool.query(
`SELECT branch_code || ':' || schema_name || ':' || status AS row
FROM public.tenant_schema_registry ORDER BY branch_code`
);
registryRows = rows.rows.map((r) => r.row);
} catch {
registryCount = null;
}
const countTables = [
'orders',
'skus',
'customers',
'categories',
'cost_details',
'branches',
];
const tableCounts: Record<string, number> = {};
let countSource: string | null = null;
const publicOrders = await pool.query(`SELECT to_regclass('public.orders') AS reg`);
if (publicOrders.rows[0]?.reg) {
countSource = 'public';
} else {
const active = await pool.query(
`SELECT schema_name FROM public.tenant_schema_registry
WHERE status='active' ORDER BY branch_code LIMIT 1`
);
countSource = active.rows[0]?.schema_name || null;
}
for (const t of countTables) {
try {
if (!countSource) {
tableCounts[t] = -1;
continue;
}
const r2 = await pool.query(
`SELECT count(*)::int AS n FROM "${countSource.replace(/"/g, '')}"."${t.replace(/"/g, '')}"`
);
tableCounts[t] = r2.rows[0].n;
} catch {
tableCounts[t] = -1;
}
}
return {
label: 'local',
migrations: mig.rows.map((r) => r.filename),
tables: tables.rows.map((r) => r.tablename),
tenantSchemas: schemas.rows.map((r) => r.nspname),
registryRows,
registryGrant,
registryCount,
countSource,
tableCounts,
};
} finally {
await pool.end();
}
}
function diffLists(a: string[], b: string[]) {
const as = new Set(a);
const bs = new Set(b);
return {
onlyA: a.filter((x) => !bs.has(x)),
onlyB: b.filter((x) => !as.has(x)),
};
}
async function main() {
const local = await snapshotLocal();
const prodPath = path.resolve(process.cwd(), '../tmp/prod-db-snapshot.json');
if (!fs.existsSync(prodPath)) {
console.error('Missing prod snapshot:', prodPath);
console.error('Run the SSH snapshot step first.');
process.exit(1);
}
const raw = fs.readFileSync(prodPath, 'utf8').replace(/^\uFEFF/, '');
const prod = JSON.parse(raw) as Snapshot;
const migDiff = diffLists(local.migrations, prod.migrations);
const tableDiff = diffLists(local.tables, prod.tables);
console.log('=== Database comparison ===');
console.log(`Local migrations: ${local.migrations.length}`);
console.log(`Prod migrations: ${prod.migrations.length}`);
console.log(`Only local migrations (${migDiff.onlyA.length}):`);
for (const f of migDiff.onlyA) console.log(' +', f);
console.log(`Only prod migrations (${migDiff.onlyB.length}):`);
for (const f of migDiff.onlyB) console.log(' -', f);
console.log('');
console.log(`Local public tables: ${local.tables.length}`);
console.log(`Prod public tables: ${prod.tables.length}`);
console.log(`Only local tables (${tableDiff.onlyA.length}):`);
for (const t of tableDiff.onlyA) console.log(' +', t);
console.log(`Only prod tables (${tableDiff.onlyB.length}):`);
for (const t of tableDiff.onlyB) console.log(' -', t);
console.log('');
console.log('tenant schemas:');
console.log(' local:', (local.tenantSchemas || []).join(', ') || '(none)');
console.log(' prod :', (prod.tenantSchemas || []).join(', ') || '(none)');
console.log('registry rows:');
console.log(' local:', (local.registryRows || []).join(' | ') || '(none)');
console.log(' prod :', (prod.registryRows || []).join(' | ') || '(none)');
console.log('');
console.log('tenant_schema_registry:');
console.log(' local grants to canteen_app_rls:', local.registryGrant);
console.log(' prod grants to canteen_app_rls:', prod.registryGrant);
console.log(' local row count:', local.registryCount);
console.log(' prod row count:', prod.registryCount);
console.log(' local count source:', local.countSource);
console.log(' prod count source:', prod.countSource);
console.log('');
console.log('Row counts (public):');
const keys = new Set([
...Object.keys(local.tableCounts || {}),
...Object.keys(prod.tableCounts || {}),
]);
for (const k of [...keys].sort()) {
console.log(
` ${k}: local=${local.tableCounts?.[k] ?? '?'} prod=${prod.tableCounts?.[k] ?? '?'}`
);
}
if (local.migrations.length) {
console.log('');
console.log('Latest local migration:', local.migrations[local.migrations.length - 1]);
}
if (prod.migrations.length) {
console.log('Latest prod migration:', prod.migrations[prod.migrations.length - 1]);
}
}
void main();