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, 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( database: Sequelize, table: string, column: string, ids: readonly string[], transaction: Transaction ) { if (!ids.length) { return []; } return database.query( `SELECT * FROM ${sqlIdentifier(table)} WHERE ${sqlIdentifier(column)} IN (:ids)`, { replacements: { ids }, type: QueryTypes.SELECT, transaction } ); }