metis-desk/modules/resources/src/api/infrastructure/persistence/resource-relational-sql.ts

39 lines
1.2 KiB
TypeScript
Raw Normal View History

2026-10-10 11:32:40 +00:00
import type { Sequelize, Transaction } from "sequelize";
import { QueryTypes } from "sequelize";
/** Identificadores internos; los valores externos siempre se parametrizan. */
export function sqlIdentifier(value: string) {
return `\`${value.replaceAll("`", "``")}\``;
}
export async function writeResourceRow(
database: Sequelize,
table: string,
row: Record<string, string | number | boolean | null>,
transaction: Transaction
) {
const columns = Object.keys(row);
await database.query(
`INSERT INTO ${sqlIdentifier(table)} (${columns.map(sqlIdentifier).join(",")}) VALUES (${columns.map((key) => `:${key}`).join(",")}) ON DUPLICATE KEY UPDATE ${columns.map((key) => `${sqlIdentifier(key)}=VALUES(${sqlIdentifier(key)})`).join(",")}`,
{ replacements: row, transaction }
);
}
export async function readResourceRows<T extends object>(
database: Sequelize,
table: string,
column: string,
ids: readonly string[],
transaction: Transaction
) {
if (!ids.length) {
return [];
}
return database.query<T>(
`SELECT * FROM ${sqlIdentifier(table)} WHERE ${sqlIdentifier(column)} IN (:ids)`,
{ replacements: { ids }, type: QueryTypes.SELECT, transaction }
);
}