@fxjs/db-driver
Version:
[](https://www.npmjs.org/package/@fxjs/db-driver) [](https://travis-ci.org/fxjs-modules/db-driver) [ • 6.7 kB
JavaScript
/// <reference types="@fibjs/types" />
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterPSQLSearchPath = exports.detectWindowsCodePoints = exports.logDebugSQL = exports.arraify = exports.mountPoolToDriver = exports.parsePoolConfig = exports.parseConnectionString = exports.ensureSuffix = exports.castQueryStringToBoolean = exports.forceInteger = exports.filterDriverType = exports.driverUUid = void 0;
const url = require("url");
const util = require("util");
const tty = require("tty");
const net = require("net");
const uuid = require("uuid");
const io = require("io");
const child_process = require("child_process");
const ParseQSDotKey = require("parse-querystring-dotkey");
const FibPool = require("fib-pool");
function driverUUid() {
return uuid.node().hex();
}
exports.driverUUid = driverUUid;
function filterDriverType(protocol) {
switch (protocol) {
case 'sqlite:':
return 'sqlite';
case 'mysql:':
return 'mysql';
case 'postgresql:':
case 'postgres:':
case 'pg:':
case 'psql:':
return 'psql';
case 'redis:':
return 'redis';
// case 'mongodb:':
// return 'mongodb';
default:
return 'unknown';
}
}
exports.filterDriverType = filterDriverType;
function forceInteger(input, fallback) {
try {
input = parseInt(input);
}
catch (error) {
input = null;
}
if (input === null || isNaN(input))
input = fallback;
return input;
}
exports.forceInteger = forceInteger;
function castQueryStringToBoolean(input) {
switch (input) {
case "1":
case "true":
case "y":
return true;
case "0":
case "false":
case "no":
case "n":
case "":
return false;
default:
return !!input;
}
}
exports.castQueryStringToBoolean = castQueryStringToBoolean;
function unPrefix(str = '', prefix = '/') {
if (!str || typeof str !== 'string')
return '';
if (str.slice(0, prefix.length) === prefix)
str = str.slice(prefix.length);
return str;
}
function ensureSuffix(str = '', suffix = '//') {
if (!str || typeof str !== 'string')
return '';
const lidx = str.lastIndexOf(suffix);
if (str.slice(lidx) !== suffix)
str += suffix;
return str;
}
exports.ensureSuffix = ensureSuffix;
function parseConnectionString(input) {
input = input || {};
let urlObj = input instanceof net.Url ? input : null;
if (typeof input === 'string') {
urlObj = url.parse(input);
input = {
protocol: urlObj.protocol || null,
slashes: urlObj.slashes || false,
query: urlObj.query || null,
username: urlObj.username || null,
password: urlObj.password || null,
host: urlObj.host || null,
hostname: urlObj.hostname || null,
port: urlObj.port || null,
href: urlObj.href || null,
database: unPrefix(urlObj.pathname, '/') || null,
pathname: urlObj.pathname || null,
// timezone: urlObj.query.timezone || null,
};
}
else if (typeof input !== 'object') {
input = {};
}
if (input.user && !input.username)
input.username = input.user;
delete input.user;
if (typeof input.query === 'string')
input.query = ParseQSDotKey(input.query);
input.query = Object.assign({}, input.query);
input = Object.assign({}, input);
input = util.pick(input, [
'protocol',
'slashes',
'query',
'database',
'username',
'password',
'host',
'hostname',
'port',
'href',
'pathname',
]);
Object.defineProperty(input, 'database', {
set(v) {
this.pathname = '/' + v;
},
get() {
return unPrefix(this.pathname, '/');
},
});
input.slashes = !!input.slashes;
input.port = forceInteger(input.port, null);
return input;
}
exports.parseConnectionString = parseConnectionString;
function parsePoolConfig(input) {
if (!input || input === true)
return {};
if (typeof input !== 'object')
return {};
const { maxsize = undefined, timeout = undefined, retry = undefined } = (input || {});
return {
maxsize,
timeout,
retry
};
}
exports.parsePoolConfig = parsePoolConfig;
function mountPoolToDriver(driver, poolSetting = driver.config.pool) {
if (!driver.pool && poolSetting)
driver.pool = FibPool(Object.assign({ create: () => {
return driver.getConnection();
}, destroy: (conn) => {
return conn.close();
} }, parsePoolConfig(poolSetting)));
}
exports.mountPoolToDriver = mountPoolToDriver;
function arraify(item) {
return Array.isArray(item) ? item : [item];
}
exports.arraify = arraify;
function logDebugSQL(dbtype, sql, is_sync = true) {
let fmt;
if (tty.isatty(process.stdout.fd)) {
fmt = "\033[32;1m(orm/%s) \033[34m%s\033[0m\n";
sql = sql.replace(/`(.+?)`/g, function (m) { return "\033[31m" + m + "\033[34m"; });
}
else {
fmt = "[SQL/%s] %s\n";
}
const text = util.format(fmt, dbtype, sql);
if (is_sync) {
console.log(text);
}
else {
process.stdout.write(text);
}
}
exports.logDebugSQL = logDebugSQL;
;
function detectWindowsCodePoints() {
let codepoints = '';
const isWindows = process.platform === 'win32';
if (isWindows) {
try {
const p = child_process.spawn('cmd', "/c chcp".split(' '));
const stdout = new io.BufferedStream(p.stdout);
const output = stdout.readLines().join(' ');
const matches = output.match(/\d+/g);
codepoints = matches === null || matches === void 0 ? void 0 : matches[0];
}
catch (error) {
}
}
return {
isWindows,
codepoints
};
}
exports.detectWindowsCodePoints = detectWindowsCodePoints;
function filterPSQLSearchPath(input_sp) {
input_sp = Array.isArray(input_sp) ? input_sp.join(', ') : `${input_sp}`;
const filtered_sp = input_sp === null || input_sp === void 0 ? void 0 : input_sp.replace(/[^a-zA-Z0-9_"$,]/g, '');
return filtered_sp || '';
}
exports.filterPSQLSearchPath = filterPSQLSearchPath;