UNPKG

@js-ak/db-manager

Version:
88 lines (87 loc) 3.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setStreamExecutor = setStreamExecutor; const node_crypto_1 = require("node:crypto"); function isPool(conn) { return typeof conn === "object" && conn !== null && "getConnection" in conn; } function isPoolConnection(conn) { return typeof conn === "object" && conn !== null && "release" in conn && "connection" in conn; } function isRawConnection(conn) { return typeof conn === "object" && conn !== null && "query" in conn; } async function runStreamQuery(executor, query, values, config) { if (isPool(executor)) { const promiseConn = await executor.getConnection(); try { const rawConn = promiseConn.connection; const stream = rawConn.query(query, values).stream(); stream.once("end", () => promiseConn.release()); stream.once("error", () => promiseConn.release()); return stream; } catch (err) { promiseConn.release(); throw err; } } else if (isPoolConnection(executor)) { const rawConn = executor.connection; return rawConn.query(query, values).stream(config); } else if (isRawConnection(executor)) { return executor.query(query, values).stream(); } else { throw new Error("Invalid mysql executor"); } } async function streamQueryLogged(query, values, config) { const queryId = (0, node_crypto_1.randomUUID)(); const start = performance.now(); let stream; this.logger.info(`[${queryId}] Stream query started. QUERY: ${query} VALUES: ${JSON.stringify(values)}`); try { stream = await runStreamQuery(this.client, query, values, config); } catch (error) { const execTime = Math.round(performance.now() - start); this.logger.error(`[${queryId}] Stream query failed during start in ${execTime} ms. ERROR: ${error.message}`); throw error; } let ended = false; const finalize = (level, message) => { if (ended) return; ended = true; const execTime = Math.round(performance.now() - start); this.logger[level](`[${queryId}] ${message} in ${execTime} ms.`); }; stream.once("end", () => finalize("info", "Stream query finished")); stream.once("error", (err) => { finalize("error", `Stream query failed with error: ${err.message}`); if (!stream.destroyed) stream.destroy(err); }); return stream; } function setStreamExecutor(executor, options) { const { isLoggerEnabled, logger } = options || {}; if (isLoggerEnabled) { // eslint-disable-next-line no-console const resultLogger = logger || { error: console.error, info: console.log }; return { executeSqlStream: async (sql, config) => { return streamQueryLogged.bind({ client: executor, logger: resultLogger })(sql.query, sql.values, config); }, }; } else { return { executeSqlStream: async (sql, config) => { return runStreamQuery(executor, sql.query, sql.values, config); }, }; } }