2018-08-10 02:55:16 +08:00
|
|
|
module.exports = function(attributeFilters) {
|
2018-03-24 11:08:29 +08:00
|
|
|
const joins = [];
|
|
|
|
const joinParams = [];
|
|
|
|
let where = '1';
|
|
|
|
const whereParams = [];
|
|
|
|
|
|
|
|
let i = 1;
|
|
|
|
|
2018-08-10 02:55:16 +08:00
|
|
|
for (const filter of attributeFilters) {
|
2018-08-13 17:06:17 +08:00
|
|
|
joins.push(`LEFT JOIN attributes AS attribute${i} ON attribute${i}.noteId = notes.noteId AND attribute${i}.name = ? AND attribute${i}.isDeleted = 0`);
|
2018-03-24 11:08:29 +08:00
|
|
|
joinParams.push(filter.name);
|
|
|
|
|
|
|
|
where += " " + filter.relation + " ";
|
|
|
|
|
|
|
|
if (filter.operator === 'exists') {
|
2018-08-10 02:55:16 +08:00
|
|
|
where += `attribute${i}.attributeId IS NOT NULL`;
|
2018-03-24 11:08:29 +08:00
|
|
|
}
|
|
|
|
else if (filter.operator === 'not-exists') {
|
2018-08-10 02:55:16 +08:00
|
|
|
where += `attribute${i}.attributeId IS NULL`;
|
2018-03-24 11:08:29 +08:00
|
|
|
}
|
|
|
|
else if (filter.operator === '=' || filter.operator === '!=') {
|
2018-08-10 02:55:16 +08:00
|
|
|
where += `attribute${i}.value ${filter.operator} ?`;
|
2018-03-24 11:08:29 +08:00
|
|
|
whereParams.push(filter.value);
|
|
|
|
}
|
|
|
|
else if ([">", ">=", "<", "<="].includes(filter.operator)) {
|
2018-12-31 05:09:14 +08:00
|
|
|
let floatParam;
|
2018-03-24 11:08:29 +08:00
|
|
|
|
2018-12-31 05:09:14 +08:00
|
|
|
// from https://stackoverflow.com/questions/12643009/regular-expression-for-floating-point-numbers
|
|
|
|
if (/^[+-]?([0-9]*[.])?[0-9]+$/.test(filter.value)) {
|
|
|
|
floatParam = parseFloat(filter.value);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (floatParam === undefined || isNaN(floatParam)) {
|
|
|
|
// if the value can't be parsed as float then we assume that string comparison should be used instead of numeric
|
2018-08-10 02:55:16 +08:00
|
|
|
where += `attribute${i}.value ${filter.operator} ?`;
|
2018-03-24 11:08:29 +08:00
|
|
|
whereParams.push(filter.value);
|
|
|
|
}
|
|
|
|
else {
|
2018-08-10 02:55:16 +08:00
|
|
|
where += `CAST(attribute${i}.value AS DECIMAL) ${filter.operator} ?`;
|
2018-03-24 11:08:29 +08:00
|
|
|
whereParams.push(floatParam);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
throw new Error("Unknown operator " + filter.operator);
|
|
|
|
}
|
|
|
|
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
|
|
|
|
let searchCondition = '';
|
|
|
|
const searchParams = [];
|
|
|
|
|
|
|
|
const query = `SELECT DISTINCT notes.noteId FROM notes
|
|
|
|
${joins.join('\r\n')}
|
|
|
|
WHERE
|
|
|
|
notes.isDeleted = 0
|
|
|
|
AND (${where})
|
|
|
|
${searchCondition}`;
|
|
|
|
|
|
|
|
const params = joinParams.concat(whereParams).concat(searchParams);
|
|
|
|
|
|
|
|
return { query, params };
|
|
|
|
};
|