Created
March 19, 2013 23:15
-
-
Save TehShrike/5201022 to your computer and use it in GitHub Desktop.
A maybe marginally better way to build where clauses
This file contains 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
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()) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the Real Library version of this, check out sql-concat