/** 数字人 MySQL 访问与事务审计,所有账号数据查询显式包含所属账号。数字人表与现有账号表按服务器 UTC 解码。 */ import type { RowDataPacket, ResultSetHeader, PoolConnection, } from "mysql2/promise"; import { pool } from "../../db/pool"; /** JSON 列兼容 mysql2 返回对象或字符串的情况。 */ export function json(value: unknown): T { return (typeof value === "string" ? JSON.parse(value) : value) as T; } /** 参数化读取;调用方仅可传入固定 SQL。 */ export async function rows( sql: string, args: unknown[] = [], connection?: PoolConnection, ): Promise { const [result] = await (connection ?? pool).query( { sql, timezone: "Z" }, args, ); return result as T[]; } /** 参数化写入并返回影响行数,供乐观锁和租约判断使用。 */ export async function write( sql: string, args: unknown[] = [], connection?: PoolConnection, ) { const [result] = await (connection ?? pool).query( { sql, timezone: "Z" }, args, ); return result; } /** 审计与状态变更共用同一连接,避免有变更却无审计。 */ export async function transaction( fn: (c: PoolConnection) => Promise, ): Promise { const c = await pool.getConnection(); try { await c.beginTransaction(); const v = await fn(c); await c.commit(); return v; } catch (e) { await c.rollback(); throw e; } finally { c.release(); } } /** 审计不保存用户聊天、密钥或上游响应。 */ export async function audit( actor: string, action: string, target: string, detail: unknown, c?: PoolConnection, ) { await write( "INSERT INTO dh_audits(actor,action,target,detail) VALUES (?,?,?,?)", [actor, action, target, JSON.stringify(detail)], c, ); }