Files
SupplierSystem/server/scripts/repair-inspection-photo-db-paths.cjs
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

167 lines
5.2 KiB
JavaScript

/**
* 修复:桶已迁三层但库表仍指向旧二层(或旧键已删)时,按规则回写库表。
* 若新键不存在而旧键还在,则补复制。
*/
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
const { pool } = require('../dist/db');
const {
INSPECTION_PHOTO_BUCKETS,
INSPECTION_RESULT_FOLDERS,
buildInspectionResultObjectName,
mimeFromFilename,
parseProductSlugFromResultBasename,
} = require('../dist/services/storageBucketConfig');
const { getStorageProvider } = require('../dist/services/storageProvider');
function isResultFolder(name) {
return INSPECTION_RESULT_FOLDERS.includes(name);
}
function planDestKey(filename) {
const key = String(filename || '')
.replace(/\\/g, '/')
.replace(/^\/+/, '');
const parts = key.split('/').filter(Boolean);
if (parts.length !== 2) return null;
if (!isResultFolder(parts[0])) return null;
if (parts[1] === '.keep') return null;
const folder = parts[0];
const base = parts[1];
const slug = parseProductSlugFromResultBasename(base) || 'unknown';
let destBase = base;
if (slug !== 'unknown' && base.toLowerCase().startsWith(`${slug}-`)) {
destBase = base.slice(slug.length + 1);
}
if (!destBase || destBase.includes('/')) destBase = base;
const to = buildInspectionResultObjectName(folder, slug, destBase);
if (to === key) return null;
return { from: key, to };
}
function quoteIdent(name) {
return `"${String(name).replace(/"/g, '""')}"`;
}
async function listSchemas(table) {
const result = await pool.query(
`SELECT n.nspname AS schema
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r' AND c.relname = $1 AND n.nspname <> 'tenant_template'
ORDER BY n.nspname`,
[table]
);
return result.rows.map((r) => String(r.schema));
}
async function ensureObject(storage, bucket, from, to) {
if (await storage.exists(bucket, to)) return 'exists';
if (!(await storage.exists(bucket, from))) return 'missing';
const obj = await storage.getObject(bucket, from);
if (!obj?.buffer?.byteLength) return 'missing';
await storage.putObject(bucket, to, obj.buffer, obj.contentType || mimeFromFilename(to));
return 'copied';
}
async function rewriteTable(options) {
const { schema, table, column, bucket, storage, dryRun } = options;
const rows = await pool.query(
`SELECT id, ${column} AS photos
FROM ${quoteIdent(schema)}.${quoteIdent(table)}
WHERE ${column} IS NOT NULL AND cardinality(${column}) > 0`
);
let updated = 0;
let fixedObjects = 0;
let missing = 0;
for (const row of rows.rows) {
const photos = Array.isArray(row.photos) ? row.photos.map(String) : [];
let changed = false;
const next = [];
for (const photo of photos) {
const plan = planDestKey(photo);
if (!plan) {
next.push(photo);
continue;
}
const st = await ensureObject(storage, bucket, plan.from, plan.to);
if (st === 'copied') fixedObjects += 1;
if (st === 'missing' && !(await storage.exists(bucket, plan.to))) {
missing += 1;
console.warn(` MISSING ${bucket} ${plan.from} / ${plan.to} (${schema}.${table} ${row.id})`);
next.push(photo);
continue;
}
next.push(plan.to);
if (plan.to !== photo) changed = true;
}
if (!changed) continue;
updated += 1;
if (!dryRun) {
if (table === 'processing_tasks') {
await pool.query(
`UPDATE ${quoteIdent(schema)}.${quoteIdent(table)}
SET ${column} = $2, updated_at = NOW() WHERE id = $1`,
[row.id, next]
);
} else {
await pool.query(
`UPDATE ${quoteIdent(schema)}.${quoteIdent(table)}
SET ${column} = $2 WHERE id = $1`,
[row.id, next]
);
}
}
}
return { updated, fixedObjects, missing };
}
async function main() {
const dryRun = process.argv.includes('--dry-run');
// bypass FORCE RLS for maintenance
await pool.query('SET row_security = off');
const storage = getStorageProvider();
console.log(`模式: ${dryRun ? 'dry-run' : 'repair'}`);
let totals = { updated: 0, fixedObjects: 0, missing: 0 };
for (const schema of await listSchemas('inspections')) {
console.log(`\n[${schema}.inspections]`);
const r = await rewriteTable({
schema,
table: 'inspections',
column: 'inspection_photos',
bucket: 'inspection-photos',
storage,
dryRun,
});
console.log(r);
totals.updated += r.updated;
totals.fixedObjects += r.fixedObjects;
totals.missing += r.missing;
}
for (const schema of await listSchemas('processing_tasks')) {
console.log(`\n[${schema}.processing_tasks]`);
const r = await rewriteTable({
schema,
table: 'processing_tasks',
column: 'processing_inspection_photos',
bucket: 'processing-inspection-photos',
storage,
dryRun,
});
console.log(r);
totals.updated += r.updated;
totals.fixedObjects += r.fixedObjects;
totals.missing += r.missing;
}
console.log('\nTOTAL', totals);
await pool.end();
if (totals.missing > 0) process.exitCode = 1;
}
main().catch(async (e) => {
console.error(e);
await pool.end().catch(() => {});
process.exit(1);
});