Skip to content

Instantly share code, notes, and snippets.

@chris-muller
Last active September 17, 2019 04:31
Show Gist options
  • Save chris-muller/85db7bdefe1b80c036e44df9e64b7d2c to your computer and use it in GitHub Desktop.
Save chris-muller/85db7bdefe1b80c036e44df9e64b7d2c to your computer and use it in GitHub Desktop.
Easy way to keep track of the $1, $2, $3, etc count inside an SQL query when working with loops, etc
import Bind from './sql-bind-incrementor.js'
const bind = new Bind()
const limit = 10
const queryValues = ['id_value', 'order_id_value']
const item_ids = ['aaa', 'bbb', 'ccc']
let sql = `
SELECT *
FROM aTable
WHERE id = ${bind}
AND order_id = ${bind}
`
queryValues.push(...item_ids)
const itemClause = item_ids.map(id => `${bind}`).join(', ')
sql += ` AND item_id IN (${itemClause})`
if(limit != null) {
queryValues.push(limit)
sql += ` LIMIT ${bind}`
}
console.log('SQL: ', sql)
// 'SQL: ' `
// SELECT *
// FROM aTable
// WHERE id = $1
// AND order_id = $2
// AND item_id IN ($3, $4, $5) LIMIT $6`
console.log('VALUES: ', queryValues)
// 'VALUES: ' [ 'id_value', 'order_id_value', 'aaa', 'bbb', 'ccc', 10 ]
export default class Bind {
constructor(startingIncrement) {
// Override the starting count for binding
if(startingIncrement != null) {
this.increment = startingIncrement
}
}
increment = 1
next = function() {
return `$${this.increment++}`
}
toString() {
return this.next()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment