fix(编辑报价单): RLS 上下文改事务级 set_config(true) 且单出口 COMMIT——修「报价单不存在」500(会话级残留 '' 污染连接池)
This commit is contained in:
@@ -179,8 +179,13 @@ export async function resolveEditCustomerSplit(input: {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
// 与仓库既有写法一致:会话级设置租户上下文(RLS),用完复位
|
||||
await client.query(`SELECT set_config('app.branch_code', $1, false)`, [branchCode]);
|
||||
/**
|
||||
* **事务级**设置租户上下文(`true`):事务结束自动失效,绝不能用会话级 false——
|
||||
* 连接回池后若残留 `''`,同连接上的其它查询会因 RLS 返回 0 行(生产事故 2026-10-19:
|
||||
* 编辑报价单报「报价单不存在」)。
|
||||
*/
|
||||
await client.query('BEGIN');
|
||||
await client.query(`SELECT set_config('app.branch_code', $1, true)`, [branchCode]);
|
||||
const current = await client.query<{ customer_code: string }>(
|
||||
`SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1`,
|
||||
[code]
|
||||
@@ -188,20 +193,27 @@ export async function resolveEditCustomerSplit(input: {
|
||||
const ownCustomerCodes = current.rows.map((r) => String(r.customer_code));
|
||||
const ownSet = new Set(ownCustomerCodes);
|
||||
const extra = requested.filter((c) => !ownSet.has(c));
|
||||
if (!extra.length) return { ownCustomerCodes, customersToCreate: [], takenCustomerCodes: [] };
|
||||
const taken = await client.query<{ customer_code: string }>(
|
||||
`SELECT DISTINCT customer_code FROM customer_quote_sheet_customers WHERE customer_code = ANY($1::text[])`,
|
||||
[extra]
|
||||
);
|
||||
const takenCustomerCodes = taken.rows.map((r) => String(r.customer_code));
|
||||
const takenSet = new Set(takenCustomerCodes);
|
||||
return {
|
||||
ownCustomerCodes,
|
||||
customersToCreate: extra.filter((c) => !takenSet.has(c)),
|
||||
takenCustomerCodes,
|
||||
};
|
||||
// 单出口:先算结果,再 COMMIT,最后 return(早退会跳过 COMMIT,把脏事务留给连接池)
|
||||
let payload = { ownCustomerCodes, customersToCreate: [] as string[], takenCustomerCodes: [] as string[] };
|
||||
if (extra.length) {
|
||||
const taken = await client.query<{ customer_code: string }>(
|
||||
`SELECT DISTINCT customer_code FROM customer_quote_sheet_customers WHERE customer_code = ANY($1::text[])`,
|
||||
[extra]
|
||||
);
|
||||
const takenCustomerCodes = taken.rows.map((r) => String(r.customer_code));
|
||||
const takenSet = new Set(takenCustomerCodes);
|
||||
payload = {
|
||||
ownCustomerCodes,
|
||||
customersToCreate: extra.filter((c) => !takenSet.has(c)),
|
||||
takenCustomerCodes,
|
||||
};
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
return payload;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
await client.query(`SELECT set_config('app.branch_code', '', false)`).catch(() => undefined);
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user