2018-04-01 21:59:44 +08:00
|
|
|
module.exports = function(labelFilters, searchText) {
|
2018-03-24 11:08:29 +08:00
|
|
|
const joins = [];
|
|
|
|
const joinParams = [];
|
|
|
|
let where = '1';
|
|
|
|
const whereParams = [];
|
|
|
|
|
|
|
|
let i = 1;
|
|
|
|
|
2018-04-01 21:59:44 +08:00
|
|
|
for (const filter of labelFilters) {
|
|
|
|
joins.push(`LEFT JOIN labels AS label${i} ON label${i}.noteId = notes.noteId AND label${i}.name = ?`);
|
2018-03-24 11:08:29 +08:00
|
|
|
joinParams.push(filter.name);
|
|
|
|
|
|
|
|
where += " " + filter.relation + " ";
|
|
|
|
|
|
|
|
if (filter.operator === 'exists') {
|
2018-04-01 21:59:44 +08:00
|
|
|
where += `label${i}.labelId IS NOT NULL`;
|
2018-03-24 11:08:29 +08:00
|
|
|
}
|
|
|
|
else if (filter.operator === 'not-exists') {
|
2018-04-01 21:59:44 +08:00
|
|
|
where += `label${i}.labelId IS NULL`;
|
2018-03-24 11:08:29 +08:00
|
|
|
}
|
|
|
|
else if (filter.operator === '=' || filter.operator === '!=') {
|
2018-04-01 21:59:44 +08:00
|
|
|
where += `label${i}.value ${filter.operator} ?`;
|
2018-03-24 11:08:29 +08:00
|
|
|
whereParams.push(filter.value);
|
|
|
|
}
|
|
|
|
else if ([">", ">=", "<", "<="].includes(filter.operator)) {
|
|
|
|
const floatParam = parseFloat(filter.value);
|
|
|
|
|
|
|
|
if (isNaN(floatParam)) {
|
2018-04-01 21:59:44 +08:00
|
|
|
where += `label${i}.value ${filter.operator} ?`;
|
2018-03-24 11:08:29 +08:00
|
|
|
whereParams.push(filter.value);
|
|
|
|
}
|
|
|
|
else {
|
2018-04-01 21:59:44 +08:00
|
|
|
where += `CAST(label${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 = [];
|
|
|
|
|
|
|
|
if (searchText.trim() !== '') {
|
|
|
|
// searching in protected notes is pointless because of encryption
|
|
|
|
searchCondition = ' AND (notes.isProtected = 0 AND (notes.title LIKE ? OR notes.content LIKE ?))';
|
|
|
|
|
|
|
|
searchText = '%' + searchText.trim() + '%';
|
|
|
|
|
|
|
|
searchParams.push(searchText);
|
|
|
|
searchParams.push(searchText); // two occurences in searchCondition
|
|
|
|
}
|
|
|
|
|
|
|
|
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 };
|
|
|
|
};
|