import pg from "pg"; const { Client } = pg; const MATCH_SQL = ` session_type = 'birth_time_rectification' and title ~ '^[0-9]{1,2}月[0-9]{1,2}日[[:space:]]*·[[:space:]]*生时校正([[:space:]]+[0-9]{2}:[0-9]{2})?$' and ( created_at is null or (substring(title from '^([0-9]{1,2})月'))::int is distinct from extract(month from created_at at time zone 'Asia/Shanghai')::int or (substring(title from '月([0-9]{1,2})日'))::int is distinct from extract(day from created_at at time zone 'Asia/Shanghai')::int ) `; const COUNT_SQL = `select count(*)::int as n from public.chat_sessions where ${MATCH_SQL}`; const APPLY_SQL = ` update public.chat_sessions set title = case when created_at is null then '生时校正' else to_char(created_at at time zone 'Asia/Shanghai', 'FMMM') || '月' || to_char(created_at at time zone 'Asia/Shanghai', 'FMDD') || '日 · 生时校正' end where ${MATCH_SQL} `; function connectionString() { const value = process.env.SCHEMA_DATABASE_URL?.trim(); if (!value) { throw new Error("SCHEMA_DATABASE_URL is required"); } if (!/^postgres(ql)?:\/\//.test(value)) { throw new Error("SCHEMA_DATABASE_URL must be a PostgreSQL URL"); } return value; } async function main() { const apply = process.argv.includes("--apply"); const client = new Client({ connectionString: connectionString() }); await client.connect(); try { const before = await client.query(COUNT_SQL); const n = before.rows[0]?.n ?? 0; console.log(`mismatched_dated_rectification_titles=${n}`); if (!apply) return; const updated = await client.query(APPLY_SQL); const after = await client.query(COUNT_SQL); console.log(`updated_rows=${updated.rowCount ?? 0}`); console.log(`mismatched_after=${after.rows[0]?.n ?? 0}`); } finally { await client.end(); } } main().catch((error) => { console.error(error instanceof Error ? error.message : error); process.exit(1); });