Skip to content

Instantly share code, notes, and snippets.

@andreypopp
Created February 24, 2023 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreypopp/8d53bfbc0815344b96c8c1759a22c24a to your computer and use it in GitHub Desktop.
Save andreypopp/8d53bfbc0815344b96c8c1759a22c24a to your computer and use it in GitHub Desktop.
'use strict'
let sqlstring = require('sqlstring');
class SQLUnsafe {
constructor(sql) {
this.sql = sql;
}
}
class SQLQuery {
constructor(strings, values) {
this.strings = strings
this.values = values
}
toQuery(values=[]) {
let text = this.strings[0];
for (let i = 0; i<this.strings.length-1; i++) {
let s = this.strings[i + 1];
let v = this.values[i];
if (v instanceof SQLUnsafe) {
text += v.sql;
} else if (v instanceof SQLQuery) {
let built = v.toQuery(values);
text += built.text;
} else {
values.push(v);
text += `?`;
}
text += s;
}
return {text, values};
}
toSql() {
let {text, values} = this.toQuery();
return sqlstring.format(text, values);
}
}
function q(strings) {
return new SQLQuery(
strings.slice(0),
Array.from(arguments).slice(1))
}
/** Escape identifier. */
function id(name) {
return UNSAFE(sqlstring.escapeId(name));
}
/** Inject UNSAFE SQL string. */
function UNSAFE(sql) {
return new SQLUnsafe(sql);
}
module.exports = {q, UNSAFE, id};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment