Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Last active June 7, 2019 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoargh/5292e56d1eaf9560e78e9b162407e851 to your computer and use it in GitHub Desktop.
Save renatoargh/5292e56d1eaf9560e78e9b162407e851 to your computer and use it in GitHub Desktop.
A small query builder to help not writing SQL insert by hand
const withQuotes = (value, quote = '\'') => {
if (typeof value === 'undefined') {
return 'null'
}
if (value === null) {
return 'null'
}
return `${quote}${value}${quote}`
}
const getInsert = (table, columns = []) => {
const columnsWithQuotes = columns.map((c) => withQuotes(c, '"'))
const insert = `INSERT INTO ${table} (${columnsWithQuotes}) VALUES `
const values = []
return {
withValues: (...data) => {
data = Object.assign(...data)
const value = columns.map((column) => {
return withQuotes(data[column])
}).join(', ')
values.push(`(${value})`)
},
sql: () => {
return insert + values.join(', ') + ';'
}
}
}
@renatoargh
Copy link
Author

renatoargh commented Jun 7, 2019

Example

const insert = getInsert('table', ['columnA', 'columnB'])

insert.withValues({columnA: 'hello', columnB: 'world'})
insert.withValues({columnA: 'answer is', columnB: '42'})

console.log(insert.sql())

Will print:

INSERT INTO table ("columnA", "columnB") VALUES ('hello', 'world'), ('answer is', '42');

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