@opengis/fastify-table
Version:
core-plugins
65 lines (51 loc) • 2.04 kB
JavaScript
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();
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) {
console.log(filename, 'skip equal hash', Date.now() - start);
return null;
}
try {
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);
console.log(filename, 'finish', Date.now() - start);
logger.file('migration/success', {
filepath,
result: 'success',
time: Date.now() - start,
});
return 'ok';
}
catch (err) {
console.log(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();
}
}