Created
February 24, 2023 07:50
-
-
Save andreypopp/8d53bfbc0815344b96c8c1759a22c24a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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