Last active
June 7, 2019 09:20
-
-
Save renatoargh/5292e56d1eaf9560e78e9b162407e851 to your computer and use it in GitHub Desktop.
A small query builder to help not writing SQL insert by hand
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
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(', ') + ';' | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Will print: