UNPKG

@opengis/fastify-table

Version:

core-plugins

65 lines (64 loc) 2.21 kB
/* eslint-disable no-console */ import path from "node:path"; import { createHash } from "node:crypto"; import { existsSync, readFileSync } from "node:fs"; import config from "../../../config.js"; import pgClients from "../pg/pgClients.js"; import logger from "../logger/getLogger.js"; import getRedis from "../redis/funcs/getRedis.js"; const rclient = getRedis(); const debug = config.debug || config.local; export default async function execSql(filepath, pg = pgClients.client) { const start = Date.now(); if (!pg || !filepath) return null; const filename = path.basename(filepath); if (!existsSync(filepath)) { logger.file("migration/notfound", { filepath, result: "not found", }); console.log(filepath, "warn", "not found", Date.now() - start); return null; } const sql = readFileSync(filepath, "utf-8"); const hash = createHash("md5").update(sql).digest("hex"); const hashes = config.redis ? await rclient .hgetall(`${pg?.options?.database}:migration-hashes`) .then((obj) => Object.keys(obj)) : []; if (hashes.includes(hash) && !config.disableCache && !process.env.MIGRATE && debug) { console.log(filename, "skip equal hash", Date.now() - start); return null; } try { if (debug) console.log(filename, "start", Date.now() - start); await pg.query(sql); if (!config.disableCache && config.redis) await rclient.hset(`${pg?.options?.database}:migration-hashes`, hash, 1); if (debug) console.log(filename, "finish", Date.now() - start); logger.file("migration/success", { filepath, result: "success", time: Date.now() - start, }); return "ok"; } catch (err) { console.error(filename, "error", err.toString(), Date.now() - start); logger.file("migration/error", { filepath, result: "error", error: err.toString(), stack: err.stack, time: Date.now() - start, }); return err.toString(); } }