@clickup/pg-microsharding
Version:
Microshards support for PostgreSQL
79 lines • 2.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sql = void 0;
exports.shellQuote = shellQuote;
exports.sql = sql;
exports.ident = ident;
exports.join = join;
/**
* Quotes the value to be used as a shell argument.
*/
function shellQuote(s) {
function quote(s) {
return "'" + s.replace(/'/g, "'\\''") + "'";
}
return s === ";"
? "\\;"
: s.match(/^[-a-z_0-9:/@.=,]+$/is)
? s
: s.match(/^((?:--)?[-a-z_0-9]+=)(.*)$/is)
? RegExp.$1 + quote(RegExp.$2)
: quote(s);
}
/**
* Builds a compound SQL statement from a typed template string literal. All SQL
* clauses built by this helper will have newlines removed.
*/
function sql(strings, ...values) {
const SEP = "\x00";
return new Sql(strings
.join(SEP)
.trim()
.replace(/[ \t\r\n]+/g, " ") // glue all lines in one
.trimEnd()
.split(SEP), values);
}
/**
* Builds a PG identifier from a string.
*/
function ident(name) {
return new Ident(name);
}
/**
* Joins multiple compound SQL statements.
*/
function join(sqls, sep) {
return new Sql([sqls.map((sql) => sql.toString()).join(sep)], []);
}
class Ident {
constructor(name) {
this.name = name;
}
toString() {
return this.name.match(/^[a-z_][a-z_0-9]*$/is)
? this.name
: '"' + this.name.replace(/"/g, '""') + '"';
}
}
class Sql {
constructor(strings, values) {
this.strings = strings;
this.values = values;
}
toString() {
return (this.values
.map((value, i) => this.strings[i] +
(value instanceof Sql || value instanceof Ident
? value.toString()
: value === null || value === undefined
? "NULL"
: // Postgres doesn't like ASCII NUL character (error message is "unterminated
// quoted string" or "invalid message format"), so we remove it too.
"'" +
("" + value).replace(/\0/g, "").replace(/'/g, "''") +
"'"))
.join("") + this.strings[this.values.length]);
}
}
exports.Sql = Sql;
//# sourceMappingURL=quote.js.map