I have a Node JS project with Typescript in which I am including database queries in BigQuery
.
The function is to generate a JSON object with the search fields and values to pass them to the query and return all the records that match those fields.
This is the object:
let dataObj = {
"host": "192.168,AS101",
"code": "001,025",
"country": "Colombia"
}
This is the query:
SELECT *
FROM TABLE_TEST
WHERE hostName in ('${dataObj.host}') and codeData in (${dataObj.code}) and countryName in ('${dataObj.country}')
My problem: all the fields of the object are optional, how can I add or remove fields inside the WHERE
?
EXAMPLE:
New JSON object:
let dataObj = {
"host": "192.168,AS101",
"country": "Colombia"
}
This is the query that would have to be performed:
SELECT *
FROM TABLE_TEST
WHERE hostName in ('${dataObj.host}') and countryName in ('${dataObj.country}')
Upgrade:
The fields of the JSON object are not named the same as the fields of the tables so I need to change their names, this is what I currently do:
function formatName(key: string) {
if (key == 'host') {
return 'hostName'
} else if (key == 'code') {
return 'codeData'
} else if (key == 'country') {
return 'countryName'
} else {
return false
}
}
let sql = " SELECT * FROM MYTABLE WHERE true ";
Object.entries(dataObj).map(
(entri) => (sql = `${sql} AND ${formatName(entri[0])} in ("${entri[1]}")`)
);
The data of each key when included in the where clause cannot go "192.168,AS101", but it would have to be "192.168","AS101" so that the query picks it up correctly. This is what I have done but the query does not catch it:
let newData = {
"host": dataObj.host.split(','),
"code": dataObj.code.split(','),
"country": dataObj.country.split(',')
}
let sql = " SELECT * FROM MYTABLE WHERE true ";
Object.entries(dataObj).map(
(entri) => (sql = `${sql} AND ${entri[0]} in ("${entri[1]}")`)
);
I'm using in this case the famous WHERE 1=1
trick
const dataObj = {
host: "192.168,AS101",
code: "001,025",
country: "Colombia",
};
let sql = " SELECT * FROM MYTABLE WHERE 1=1 ";
Object.entries(dataObj).map(
(entri) => (sql = `${sql} AND ${entri[0]} in (${entri[1]})`)
);
console.log(sql); <-- SELECT * FROM MYTABLE WHERE 1=1 AND host in (192.168,AS101) AND code in (001,025) AND country in (Colombia)
const dataObj = {
host: "192.168,AS101",
};
let sql = " SELECT * FROM MYTABLE WHERE 1=1 ";
Object.entries(dataObj).map(
(entri) => (sql = `${sql} AND ${entri[0]} in (${entri[1]})`)
);
console.log(sql); <-- SELECT * FROM MYTABLE WHERE 1=1 AND host in (192.168,AS101)