knex/src/util/parse-connection.js

65 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-05-09 13:58:18 -04:00
2015-06-01 07:55:04 -04:00
import url from 'url'
import { parse as parsePG } from 'pg-connection-string'
2015-05-09 13:58:18 -04:00
2015-06-01 07:55:04 -04:00
export default function parseConnectionString(str) {
const parsed = url.parse(str)
let { protocol } = parsed
2015-05-09 13:58:18 -04:00
if (protocol && protocol.indexOf('maria') === 0) {
protocol = 'maria'
}
if (protocol === null) {
return {
client: 'sqlite3',
connection: {
filename: str
}
}
2015-05-09 13:58:18 -04:00
}
if (protocol.slice(-1) === ':') {
protocol = protocol.slice(0, -1);
}
const isPG = ['postgresql', 'postgres'].includes(protocol);
2015-05-09 13:58:18 -04:00
return {
client: protocol,
connection: isPG ? parsePG(str) : connectionObject(parsed)
};
2015-05-09 13:58:18 -04:00
}
function connectionObject(parsed) {
const connection = {};
let db = parsed.pathname;
2015-05-09 13:58:18 -04:00
if (db[0] === '/') {
db = db.slice(1)
}
if (parsed.protocol.indexOf('maria') === 0) {
connection.db = db
} else {
connection.database = db
}
if (parsed.hostname) {
if (parsed.protocol.indexOf('mssql') === 0) {
connection.server = parsed.hostname;
} else {
connection.host = parsed.hostname;
}
2015-05-09 13:58:18 -04:00
}
if (parsed.port) {
connection.port = parsed.port;
}
if (parsed.auth) {
const idx = parsed.auth.indexOf(':');
2015-05-09 13:58:18 -04:00
if (idx !== -1) {
connection.user = parsed.auth.slice(0, idx);
if (idx < parsed.auth.length - 1) {
connection.password = parsed.auth.slice(idx + 1);
}
} else {
connection.user = parsed.auth;
2015-05-09 13:58:18 -04:00
}
}
return connection
}