来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
458 lines
15 KiB
TypeScript
458 lines
15 KiB
TypeScript
import { pool } from '../db';
|
|
import { validateTableWrite } from './writeValidators';
|
|
import { compileTrustedExpr } from './trustedExprFilters';
|
|
|
|
export interface FilterSpec {
|
|
/**
|
|
* 注意:'expr' 仅允许服务端内部白名单模板(tenantScope 注入),`$val` 参数化。
|
|
* 客户端入口(routes/data.ts)会拒绝任何包含 op:'expr' 的请求。
|
|
*/
|
|
op: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'ilike' | 'or' | 'is' | 'empty_or_null' | 'expr';
|
|
column?: string;
|
|
value?: unknown;
|
|
raw?: string;
|
|
}
|
|
|
|
export interface OrderSpec {
|
|
column: string;
|
|
ascending: boolean;
|
|
}
|
|
|
|
export interface QuerySpec {
|
|
table: string;
|
|
action: 'select' | 'insert' | 'update' | 'delete';
|
|
select?: string;
|
|
returning?: string;
|
|
count?: 'exact';
|
|
filters?: FilterSpec[];
|
|
orders?: OrderSpec[];
|
|
limit?: number;
|
|
offset?: number;
|
|
range?: { from: number; to: number };
|
|
single?: boolean;
|
|
insertData?: unknown;
|
|
updateData?: unknown;
|
|
}
|
|
|
|
interface EmbedSpec {
|
|
alias: string;
|
|
table: string;
|
|
localKey: string;
|
|
foreignKey: string;
|
|
columns: string[];
|
|
/** 主表与嵌入表同时按 branch_code 对齐,避免跨分公司同码串名 */
|
|
matchBranchCode?: boolean;
|
|
}
|
|
|
|
const TABLE_ALIASES: Record<string, string> = {
|
|
orders: 't0',
|
|
customers: 't1',
|
|
skus: 't2',
|
|
categories: 't3',
|
|
suppliers: 't4',
|
|
order_items: 't5',
|
|
permissions: 't6',
|
|
delivery_persons: 't7',
|
|
role_permissions: 't8',
|
|
};
|
|
|
|
/** skus 表含 image_data BYTEA,列表查询 select * 会严重拖慢加载 */
|
|
const SKUS_LIST_SELECT =
|
|
't2.sku_code, t2.sku_name, t2.category_code, t2.unit, t2.spec, t2.barcode, t2.image_url, t2.default_loss_threshold, t2.is_prepackaged, t2.stock_mode, t2.brand, t2.tax_code, t2.tax_rate, t2.origin, t2.unit_weight, t2.status, t2.created_at';
|
|
|
|
const EMBED_RULES: Record<string, Record<string, Omit<EmbedSpec, 'alias' | 'columns'>>> = {
|
|
orders: {
|
|
customers: { table: 'customers', localKey: 'customer_code', foreignKey: 'customer_code' },
|
|
'customers:customer_code': { table: 'customers', localKey: 'customer_code', foreignKey: 'customer_code' },
|
|
},
|
|
skus: {
|
|
categories: {
|
|
table: 'categories',
|
|
localKey: 'category_code',
|
|
foreignKey: 'category_code',
|
|
matchBranchCode: true,
|
|
},
|
|
'categories:category_code': {
|
|
table: 'categories',
|
|
localKey: 'category_code',
|
|
foreignKey: 'category_code',
|
|
matchBranchCode: true,
|
|
},
|
|
},
|
|
order_items: {
|
|
skus: { table: 'skus', localKey: 'sku_code', foreignKey: 'sku_code', matchBranchCode: true },
|
|
'skus:sku_code': { table: 'skus', localKey: 'sku_code', foreignKey: 'sku_code', matchBranchCode: true },
|
|
suppliers: {
|
|
table: 'suppliers',
|
|
localKey: 'supplier_code',
|
|
foreignKey: 'supplier_code',
|
|
matchBranchCode: true,
|
|
},
|
|
'suppliers:supplier_code': {
|
|
table: 'suppliers',
|
|
localKey: 'supplier_code',
|
|
foreignKey: 'supplier_code',
|
|
matchBranchCode: true,
|
|
},
|
|
},
|
|
supplier_users: {
|
|
suppliers: { table: 'suppliers', localKey: 'supplier_code', foreignKey: 'supplier_code' },
|
|
},
|
|
delivery_person_users: {
|
|
delivery_persons: { table: 'delivery_persons', localKey: 'person_code', foreignKey: 'person_code' },
|
|
},
|
|
role_permissions: {
|
|
'permissions:permission_id': { table: 'permissions', localKey: 'permission_id', foreignKey: 'id' },
|
|
},
|
|
profiles: {
|
|
branches: { table: 'branches', localKey: 'branch_code', foreignKey: 'branch_code' },
|
|
},
|
|
bid_prices: {
|
|
'skus:sku_code': { table: 'skus', localKey: 'sku_code', foreignKey: 'sku_code' },
|
|
},
|
|
inventory: {
|
|
'skus:sku_code': { table: 'skus', localKey: 'sku_code', foreignKey: 'sku_code', matchBranchCode: true },
|
|
},
|
|
};
|
|
|
|
function assertSafeIdentifier(name: string) {
|
|
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
|
|
throw new Error(`Invalid identifier: ${name}`);
|
|
}
|
|
}
|
|
|
|
function assertSafeTable(name: string) {
|
|
assertSafeIdentifier(name);
|
|
}
|
|
|
|
function splitSelectParts(select: string): string[] {
|
|
const parts: string[] = [];
|
|
let current = '';
|
|
let depth = 0;
|
|
|
|
for (const char of select.replace(/\n/g, ' ')) {
|
|
if (char === '(') depth++;
|
|
if (char === ')') depth--;
|
|
if (char === ',' && depth === 0) {
|
|
if (current.trim()) parts.push(current.trim());
|
|
current = '';
|
|
continue;
|
|
}
|
|
current += char;
|
|
}
|
|
|
|
if (current.trim()) parts.push(current.trim());
|
|
return parts;
|
|
}
|
|
|
|
function parseEmbeds(table: string, select?: string): { baseSelect: string; embeds: EmbedSpec[] } {
|
|
const tableAlias = TABLE_ALIASES[table] || 't0';
|
|
if (!select || select.trim() === '*') {
|
|
if (table === 'skus') {
|
|
return { baseSelect: SKUS_LIST_SELECT, embeds: [] };
|
|
}
|
|
return { baseSelect: `${tableAlias}.*`, embeds: [] };
|
|
}
|
|
|
|
const embeds: EmbedSpec[] = [];
|
|
const baseColumns: string[] = [];
|
|
|
|
const parts = splitSelectParts(select);
|
|
|
|
for (const part of parts) {
|
|
const embedMatch = part.match(/^(\w+)(?::(\w+))?\s*\(([^)]+)\)$/);
|
|
if (embedMatch) {
|
|
const alias = embedMatch[1];
|
|
const explicitKey = embedMatch[2];
|
|
const columns = embedMatch[3].split(',').map((c) => c.trim()).filter(Boolean);
|
|
for (const col of columns) {
|
|
if (col !== '*') assertSafeIdentifier(col);
|
|
}
|
|
const rules = EMBED_RULES[table] || {};
|
|
const ruleKey = explicitKey ? `${alias}:${explicitKey}` : alias;
|
|
const rule = rules[ruleKey] || rules[alias];
|
|
if (!rule) {
|
|
throw new Error(`Unsupported embed ${part} on table ${table}`);
|
|
}
|
|
embeds.push({
|
|
alias,
|
|
table: rule.table,
|
|
localKey: explicitKey || rule.localKey,
|
|
foreignKey: rule.foreignKey,
|
|
columns,
|
|
matchBranchCode: Boolean(rule.matchBranchCode),
|
|
});
|
|
continue;
|
|
}
|
|
|
|
if (part === '*') {
|
|
baseColumns.push(`${TABLE_ALIASES[table] || 't0'}.*`);
|
|
} else {
|
|
// A2: select 列与 embed 列统一标识符白名单,禁止注入
|
|
assertSafeIdentifier(part);
|
|
baseColumns.push(`${TABLE_ALIASES[table] || 't0'}.${part}`);
|
|
}
|
|
}
|
|
|
|
return {
|
|
baseSelect: baseColumns.length ? baseColumns.join(', ') : `${TABLE_ALIASES[table] || 't0'}.*`,
|
|
embeds,
|
|
};
|
|
}
|
|
|
|
export function buildWhere(tableAlias: string, filters: FilterSpec[] = [], startIndex = 1) {
|
|
const clauses: string[] = [];
|
|
const params: unknown[] = [];
|
|
let index = startIndex;
|
|
|
|
for (const filter of filters) {
|
|
if (filter.op === 'or' && filter.raw) {
|
|
const orParts = filter.raw.split(',').map((part) => part.trim()).filter(Boolean);
|
|
const orClauses: string[] = [];
|
|
for (const part of orParts) {
|
|
const isNullMatch = part.match(/^(\w+)\.is\.null$/i);
|
|
if (isNullMatch) {
|
|
assertSafeIdentifier(isNullMatch[1]);
|
|
orClauses.push(`${tableAlias}.${isNullMatch[1]} IS NULL`);
|
|
continue;
|
|
}
|
|
const isNotNullMatch = part.match(/^(\w+)\.is\.not\.null$/i);
|
|
if (isNotNullMatch) {
|
|
assertSafeIdentifier(isNotNullMatch[1]);
|
|
orClauses.push(`${tableAlias}.${isNotNullMatch[1]} IS NOT NULL`);
|
|
continue;
|
|
}
|
|
const ilikeMatch = part.match(/^(\w+)\.ilike\.(.+)$/i);
|
|
if (ilikeMatch) {
|
|
assertSafeIdentifier(ilikeMatch[1]);
|
|
orClauses.push(`${tableAlias}.${ilikeMatch[1]} ILIKE $${index++}`);
|
|
params.push(ilikeMatch[2]);
|
|
continue;
|
|
}
|
|
const eqMatch = part.match(/^(\w+)\.eq\.(.*)$/i);
|
|
if (eqMatch) {
|
|
assertSafeIdentifier(eqMatch[1]);
|
|
orClauses.push(`${tableAlias}.${eqMatch[1]} = $${index++}`);
|
|
params.push(eqMatch[2]);
|
|
continue;
|
|
}
|
|
}
|
|
if (orClauses.length) clauses.push(`(${orClauses.join(' OR ')})`);
|
|
continue;
|
|
}
|
|
|
|
// 服务端可信 expr:在 column 校验之前处理(租户注入通常无 column)
|
|
if (filter.op === 'expr') {
|
|
const compiled = compileTrustedExpr(String(filter.raw || ''), filter.value, index);
|
|
if (!compiled) {
|
|
throw new Error('Raw SQL expr filters are not allowed');
|
|
}
|
|
clauses.push(compiled.sql);
|
|
params.push(...compiled.params);
|
|
index = compiled.nextIndex;
|
|
continue;
|
|
}
|
|
|
|
if (!filter.column) continue;
|
|
assertSafeIdentifier(filter.column);
|
|
const col = `${tableAlias}.${filter.column}`;
|
|
|
|
switch (filter.op) {
|
|
case 'eq':
|
|
clauses.push(`${col} = $${index++}`);
|
|
params.push(filter.value);
|
|
break;
|
|
case 'neq':
|
|
clauses.push(`${col} <> $${index++}`);
|
|
params.push(filter.value);
|
|
break;
|
|
case 'gt':
|
|
clauses.push(`${col} > $${index++}`);
|
|
params.push(filter.value);
|
|
break;
|
|
case 'gte':
|
|
clauses.push(`${col} >= $${index++}`);
|
|
params.push(filter.value);
|
|
break;
|
|
case 'lt':
|
|
clauses.push(`${col} < $${index++}`);
|
|
params.push(filter.value);
|
|
break;
|
|
case 'lte':
|
|
clauses.push(`${col} <= $${index++}`);
|
|
params.push(filter.value);
|
|
break;
|
|
case 'in':
|
|
clauses.push(`${col} = ANY($${index++})`);
|
|
params.push(filter.value);
|
|
break;
|
|
case 'ilike':
|
|
clauses.push(`${col} ILIKE $${index++}`);
|
|
params.push(filter.value);
|
|
break;
|
|
case 'is':
|
|
if (filter.value === null) {
|
|
clauses.push(`${col} IS NULL`);
|
|
} else {
|
|
clauses.push(`${col} IS NOT NULL`);
|
|
}
|
|
break;
|
|
case 'empty_or_null':
|
|
// 未分类:NULL、空串、纯空白
|
|
clauses.push(`(NULLIF(BTRIM(COALESCE(${col}::text, '')), '') IS NULL)`);
|
|
break;
|
|
default:
|
|
// M2:未知 op 原先静默 break —— 该过滤条件被整体丢弃、查询退化成"不过滤",
|
|
// 客户端以为加了条件却拿到更大范围的数据(且无任何报错,排查成本极高)。
|
|
// 明确拒绝,交给 routes/data.ts 映射成 400(该分支已存在)。
|
|
throw Object.assign(
|
|
new Error(`不支持的过滤操作符: ${String((filter as { op?: unknown }).op)}`),
|
|
{ code: 'bad_request' }
|
|
);
|
|
}
|
|
}
|
|
|
|
return { whereSql: clauses.length ? `WHERE ${clauses.join(' AND ')}` : '', params, nextIndex: index };
|
|
}
|
|
|
|
function buildOrder(tableAlias: string, orders: OrderSpec[] = []) {
|
|
if (!orders.length) return '';
|
|
const parts = orders.map((order) => {
|
|
assertSafeIdentifier(order.column);
|
|
return `${tableAlias}.${order.column} ${order.ascending ? 'ASC' : 'DESC'}`;
|
|
});
|
|
return `ORDER BY ${parts.join(', ')}`;
|
|
}
|
|
|
|
function buildLimitOffset(spec: QuerySpec) {
|
|
if (spec.range) {
|
|
const limit = spec.range.to - spec.range.from + 1;
|
|
return { limit, offset: spec.range.from };
|
|
}
|
|
return { limit: spec.limit, offset: spec.offset || 0 };
|
|
}
|
|
|
|
function nestEmbeds(row: any, embeds: EmbedSpec[]) {
|
|
const result = { ...row };
|
|
for (const embed of embeds) {
|
|
const payload: Record<string, unknown> = {};
|
|
for (const column of embed.columns) {
|
|
const key = `${embed.alias}__${column}`;
|
|
if (key in result) {
|
|
payload[column] = result[key];
|
|
delete result[key];
|
|
}
|
|
}
|
|
result[embed.alias] = payload;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
function parseReturningColumns(returning?: string): string {
|
|
if (!returning || returning.trim() === '*') {
|
|
return '*';
|
|
}
|
|
return splitSelectParts(returning)
|
|
.map((column) => {
|
|
assertSafeIdentifier(column);
|
|
return column;
|
|
})
|
|
.join(', ');
|
|
}
|
|
|
|
export async function executeQuery(
|
|
spec: QuerySpec,
|
|
db: { query: (sql: string, params?: unknown[]) => Promise<any> } = pool
|
|
) {
|
|
assertSafeTable(spec.table);
|
|
const mainAlias = TABLE_ALIASES[spec.table] || 't0';
|
|
|
|
if (spec.action === 'insert') {
|
|
const rows = Array.isArray(spec.insertData) ? spec.insertData : [spec.insertData];
|
|
const inserted: any[] = [];
|
|
for (const row of rows) {
|
|
if (!row || typeof row !== 'object') continue;
|
|
const record = row as Record<string, unknown>;
|
|
const columns = Object.keys(record).filter((k) => record[k] !== undefined);
|
|
columns.forEach(assertSafeIdentifier);
|
|
const values = columns.map((c) => record[c]);
|
|
const placeholders = columns.map((_, i) => `$${i + 1}`).join(', ');
|
|
const returning = parseReturningColumns(spec.returning);
|
|
const sql = `INSERT INTO ${spec.table} (${columns.join(', ')}) VALUES (${placeholders}) RETURNING ${returning}`;
|
|
const result = await db.query(sql, values);
|
|
inserted.push(...result.rows);
|
|
}
|
|
const data = spec.single ? inserted[0] || null : inserted;
|
|
return { data, error: null, count: inserted.length };
|
|
}
|
|
|
|
if (spec.action === 'update') {
|
|
await validateTableWrite(spec);
|
|
const record = (spec.updateData || {}) as Record<string, unknown>;
|
|
const columns = Object.keys(record).filter((k) => record[k] !== undefined);
|
|
columns.forEach(assertSafeIdentifier);
|
|
const assignments = columns.map((c, i) => `${c} = $${i + 1}`);
|
|
const values = columns.map((c) => record[c]);
|
|
const filterStart = values.length + 1;
|
|
const { whereSql, params } = buildWhere(mainAlias, spec.filters, filterStart);
|
|
const sql = `UPDATE ${spec.table} AS ${mainAlias} SET ${assignments.join(', ')} ${whereSql} RETURNING ${mainAlias}.*`;
|
|
const result = await db.query(sql, [...values, ...params]);
|
|
const data = spec.single ? result.rows[0] || null : result.rows;
|
|
return { data, error: null, count: result.rowCount || 0 };
|
|
}
|
|
|
|
if (spec.action === 'delete') {
|
|
const { whereSql, params } = buildWhere(mainAlias, spec.filters);
|
|
const sql = `DELETE FROM ${spec.table} AS ${mainAlias} ${whereSql} RETURNING ${mainAlias}.*`;
|
|
const result = await db.query(sql, params);
|
|
const data = spec.single ? result.rows[0] || null : result.rows;
|
|
return { data, error: null, count: result.rowCount || 0 };
|
|
}
|
|
|
|
const { baseSelect, embeds } = parseEmbeds(spec.table, spec.select);
|
|
const selectParts = [baseSelect];
|
|
const joins: string[] = [];
|
|
embeds.forEach((embed, idx) => {
|
|
const joinAlias = `e${idx}`;
|
|
assertSafeTable(embed.table);
|
|
assertSafeIdentifier(embed.localKey);
|
|
assertSafeIdentifier(embed.foreignKey);
|
|
let onClause = `${mainAlias}.${embed.localKey} = ${joinAlias}.${embed.foreignKey}`;
|
|
if (embed.matchBranchCode) {
|
|
onClause += ` AND ${mainAlias}.branch_code IS NOT DISTINCT FROM ${joinAlias}.branch_code`;
|
|
}
|
|
joins.push(`LEFT JOIN ${embed.table} AS ${joinAlias} ON ${onClause}`);
|
|
for (const column of embed.columns) {
|
|
assertSafeIdentifier(column);
|
|
selectParts.push(`${joinAlias}.${column} AS ${embed.alias}__${column}`);
|
|
}
|
|
});
|
|
|
|
const { whereSql, params } = buildWhere(mainAlias, spec.filters);
|
|
const orderSql = buildOrder(mainAlias, spec.orders);
|
|
const { limit, offset } = buildLimitOffset(spec);
|
|
|
|
let sql = `SELECT ${selectParts.join(', ')} FROM ${spec.table} AS ${mainAlias} ${joins.join(' ')} ${whereSql} ${orderSql}`;
|
|
const queryParams = [...params];
|
|
if (typeof limit === 'number') {
|
|
sql += ` LIMIT $${queryParams.length + 1}`;
|
|
queryParams.push(limit);
|
|
}
|
|
if (typeof offset === 'number' && offset > 0) {
|
|
sql += ` OFFSET $${queryParams.length + 1}`;
|
|
queryParams.push(offset);
|
|
}
|
|
|
|
const result = await db.query(sql, queryParams);
|
|
let count: number | null = null;
|
|
if (spec.count === 'exact') {
|
|
const countSql = `SELECT COUNT(*)::int AS count FROM ${spec.table} AS ${mainAlias} ${joins.join(' ')} ${whereSql}`;
|
|
const countResult = await db.query(countSql, params);
|
|
count = countResult.rows[0]?.count ?? 0;
|
|
}
|
|
|
|
const rows = result.rows.map((row: any) => nestEmbeds(row, embeds));
|
|
const data = spec.single ? rows[0] || null : rows;
|
|
return { data, error: null, count };
|
|
}
|