UNPKG

zs-core-db

Version:

Servicios generales de acceso a bases de datos

86 lines (68 loc) 1.93 kB
const oracle = require("oracledb"); oracle.fetchAsString = [oracle.CLOB]; process.platform === "win32" && oracle.initOracleClient({ libDir: process.platform && "c:\\oracle\\instantclient_21_13", }); const CONN = { __db: null, }; let pool; module.exports.connect = async (url) => { const user = url?.split("oracle://")[1].split(":")[0]; const password = url?.split("oracle://")[1].split(":")[1].split("@")[0]; const connectionString = url?.split("@")[1]; pool = pool ?? (await oracle.createPool({ user, password, connectionString, })); const connection = await pool.getConnection(); connection.query = this.query; const database = url.split("/").reverse()[0]; CONN[database] = connection; this.use(database); return this; }; module.exports.check = async (url) => { const db = CONN[url.split("/").reverse()[0]]; await db.query({ sql: "select 'true' checked from dual" }); }; module.exports.use = (database) => { CONN.__db = CONN[database]; return this; }; module.exports.query = async ({ sql = "", bind = {}, sort = {}, initial = 1, limit = 0, options, }) => { const minRow = `"__min_row_${new Date().getTime()}"`; const pagedSQL = `select mn.* from (\n` + `select mx.*, rownum ${minRow} from (\n${sql}) mx \n` + `where rownum <= ${limit <= 0 ? "rownum" : initial + limit - 1}` + `) mn \nwhere mn.${minRow} >= ${initial}`; const result = ( await CONN.__db.execute(pagedSQL, bind, { resultSet: true, outFormat: oracle.OUT_FORMAT_OBJECT, }) ).resultSet; let row; const rows = []; while ((row = await result.getRow())) { delete row[minRow.slice(1, -1)]; rows.push(row); } await result.close(); return rows; }; module.exports.execute = async (sql, bind) => (await CONN.__db.execute(sql, bind)).rowsAffected; module.exports.commit = async (sql, bind) => CONN.__db.commit();