Merge pull request #105 from adhilton25/f/query-parameterization

Query Parameterization
This commit is contained in:
TimonKK
2022-03-31 00:29:12 +03:00
committed by GitHub
3 changed files with 64 additions and 1 deletions

View File

@@ -195,6 +195,20 @@ const ws = clickhouse.insert('INSERT INTO session_temp2').stream();
const result = await rs.pipe(tf).pipe(ws).exec(); const result = await rs.pipe(tf).pipe(ws).exec();
``` ```
***
Parameterized Values:
```javascript
const rows = await clickhouse.query(
'SELECT * AS count FROM temp_table WHERE version = {ver:UInt16}',
{
params: {
ver: 1
},
}
).toPromise();
```
For more information on encoding in the query, see [this section](https://clickhouse.com/docs/en/interfaces/http/#cli-queries-with-parameters) of the ClickHouse documentation.
*** ***

View File

@@ -487,7 +487,28 @@ class QueryCursor {
let data = me.data; let data = me.data;
let query = me.query; let query = me.query;
// check for any query params passed for interpolation
// https://clickhouse.com/docs/en/interfaces/http/#cli-queries-with-parameters
if (data && data.params) {
// each variable used in the query is expected to be prefixed with `param_`
// when passed in the request.
Object.keys(data.params).forEach(k => {
let value = data.params[k].toString();
if (Array.isArray(data.params[k])) {
value = '[' + value + ']'
};
url.searchParams.append(
`param_${k}`, value
);
});
}
if (typeof query === 'string') { if (typeof query === 'string') {
if (/with totals/i.test(query)) { if (/with totals/i.test(query)) {
me.useTotals = true; me.useTotals = true;

View File

@@ -275,6 +275,34 @@ describe('Select', () => {
}); });
}); });
}); });
it('parameterized ', callback => {
let params_sql = `SELECT
number,
toString(number * 2) AS str,
toDate(number + 1) AS date
FROM numbers(10)
WHERE number = {num:UInt64}
OR number IN {nums:Array(UInt64)}`;
let params_data = {
params: {
num: 0,
nums: [1,2]
}
}
clickhouse.query(params_sql, params_data).exec((err, rows) => {
expect(err).to.not.be.ok();
expect(rows).to.have.length(3);
expect(rows[0]).to.eql({ number: 0, str: '0', date: '1970-01-02' });
callback();
});
});
}); });
describe('session', () => { describe('session', () => {