Skip to content

Instantly share code, notes, and snippets.

@TehShrike
Created March 19, 2013 23:15
Show Gist options
  • Save TehShrike/5201022 to your computer and use it in GitHub Desktop.
Save TehShrike/5201022 to your computer and use it in GitHub Desktop.
A maybe marginally better way to build where clauses
var encloseifNecessary = function(value) {
if (typeof value === 'string') {
return "'" + escape(value) + "'"
} else {
// TODO: add further handling for arrays or whatever maybe
return value
}
}
var escape = function(value) {
return value.replace("'", "\\'")
}
var compare = function(column, value) {
return column + " = " + encloseifNecessary(value)
}
var Where = function() {
var comparisons = []
this.add = function(column, value) {
comparisons.push(compare(column, value))
}
this.getClause = function() {
return comparisons.length ? ("WHERE " + comparisons.join(" AND ")) : ""
}
}
module.exports = Where
/*
console.log(compare('butts', 13))
console.log(compare('lol', "Can't you see I'm laughing?"))
var my_where = new Where()
my_where.add('thing', 'Thing 1')
my_where.add('other_thing', "You're just using stupid names for things, aren't you")
console.log(my_where.getClause())
console.log((new Where()).getClause())
*/
@TehShrike
Copy link
Author

For the Real Library version of this, check out sql-concat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment