Skip to content

Commit

Permalink
Merge pull request #593 from Trucc/master
Browse files Browse the repository at this point in the history
Add support for passing array to tagged template litteral
  • Loading branch information
willmorgan authored Oct 25, 2018
2 parents 831d84e + 624b09f commit 691456d
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -999,8 +999,21 @@ class Request extends EventEmitter {

for (let index = 0; index < values.length; index++) {
let value = values[index]
this.input(`param${index + 1}`, value)
command.push(`@param${index + 1}`, strings[index + 1])
// if value is an array, prepare each items as it's own comma separated parameter
if (Array.isArray(value)) {
for (let parameterIndex = 0; parameterIndex < value.length; parameterIndex++) {
this.input(`param${index + 1}_${parameterIndex}`, value[parameterIndex])
command.push(`@param${index + 1}_${parameterIndex}`)
if (parameterIndex < value.length - 1) {
command.push(', ')
} else {
command.push(strings[index + 1])
}
}
} else {
this.input(`param${index + 1}`, value)
command.push(`@param${index + 1}`, strings[index + 1])
}
}

if (method) {
Expand Down
9 changes: 9 additions & 0 deletions test/common/templatestring.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ module.exports = (sql, driver) => {

done()
}).catch(done)
},

'array params' (done) {
let values = [1, 2, 3]
sql.query`select 1 as col where 1 in (${values});`.then(result => {
assert.strictEqual(result.recordset[0].col, 1)

done()
})
}
}
}
19 changes: 19 additions & 0 deletions test/common/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,4 +211,23 @@ describe('Unit', () => {
command: 'select * from myTable where id = @param1'
})
})

it('tagged template arrays', () => {
function query () {
const values = Array.prototype.slice.call(arguments)
const strings = values.shift()
const input = []
return {
input: input,
command: sql.Request.prototype._template.call({
input () { input.push(Array.prototype.slice.call(arguments)) }
}, strings, values)
}
}

assert.deepEqual(query`select * from myTable where id in (${[1, 2, 3]})`, {
input: [['param1_0', 1], ['param1_1', 2], ['param1_2', 3]],
command: 'select * from myTable where id in (@param1_0, @param1_1, @param1_2)'
})
})
})
1 change: 1 addition & 0 deletions test/tedious/tedious.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ describe('tedious', () => {

it('query', done => TEMPLATE_STRING['query'](done))
it('batch', done => TEMPLATE_STRING['batch'](done))
it('array params', done => TEMPLATE_STRING['array params'](done))

after(done => sql.close(done))
})
Expand Down

0 comments on commit 691456d

Please sign in to comment.