Skip to content

Instantly share code, notes, and snippets.

@jeffmcmahan
Created April 25, 2017 21:21
Show Gist options
  • Save jeffmcmahan/e9da088172583898678ebd45bf57c005 to your computer and use it in GitHub Desktop.
Save jeffmcmahan/e9da088172583898678ebd45bf57c005 to your computer and use it in GitHub Desktop.
SQL template tag
'use strict'
/**
* Maps the given value to a value expressible in SQL.
* @param {*} val
* @return {String}
*/
function sqlValue(val) {
if (val === null) return null
if (val === "'null'") return 'null'
if (val === 'null') return 'null'
if (typeof val === 'undefined') return 'null'
if (typeof val === 'number') return val
if (typeof val === 'string') return `'${val}'`
if (typeof val === 'object') return `'${JSON.stringify(val)}'`
return val.toString()
}
/**
* Template tag function for creating SQL statements.
* @param {String[]} strings
* @param {...*} values
* @return {String}
*/
module.exports = function(strings, ...values) {
let output = ''
strings.forEach((str, i) => {
if (i >= values.length) output += str
else output += str + sqlValue(values[i] || null)
})
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment