我正在使用标记模板来构建带有参数的查询。
function query (strings, ...args) {
return {
sql: strings.join('?'),
params: args
}
}
const storeId = '417-123';
const id = 10;
const res = query`select * from trad.customers where store_id = ${ storeId } and customer_id = ${ id }`;
// res.sql: select * from trad.customers where store_id = ? and customer_id = ?;
// res.params: [ '417-123', 10 ];
有时我需要将一个不能作为 SQL 参数(例如,表名)传递给查询的变量。我被这个困住了...
const nim = '0850204';
const id = 143;
const res = query`select * from _${ nim }_ tickets where tick_id = ${ id }`;
// what I get:
// res.sql: select * from _?_ tickets where tick_id = ?;
// res.params: [ '0850204', 143 ];
// what I'd like
// res.sql: select * from _0850204_ tickets where tick_id = ?;
// res.params: [ 143 ];
我怎样才能解决这个问题?谢谢您的帮助 :)
编辑:我使用一个特殊的 char 作为标志来告诉何时直接替换变量......这样,当#
找到 char 时,我直接替换以下值。我很确定我们可以做得更好,但我不知道如何...
function query (strings, ...args) {
const del = [];
const replace = [];
let sql = strings
.map((data, index) => {
if (data.endsWith('#') === false) return data;
replace.push(args[index]);
del.push(index);
return data;
})
.join('?');
args = args.filter((d, index) => del.includes(index) === false);
let n = 0;
while (sql.includes('#?')) {
sql = sql.replace('#?', replace[n]);
}
return { sql, params: args };
}
const nim = '0850204';
const id = 143;
// Notice the '#'
const res = query`select * from _#${ nim }_ tickets where tick_id = ${ id }`;
// res.sql: select * from _0850204_ tickets where tick_id = ?;
// res.params: [ 143 ];