UNPKG

@grandlinex/bundle-postgresql

Version:
75 lines (74 loc) 2.47 kB
import { isQInterfaceSearchAdvanced, isQInterfaceSearchAdvancedArr, } from '@grandlinex/core'; import { convertSpecialFields } from './converter.js'; class ParamCounter { constructor() { this.count = 1; } next() { return `$${this.count++}`; } } function aFilter(key, s, count) { switch (s.mode) { case 'equals': if (s.value === null) { return [`${key} IS NULL}`, true]; } return [`${key} = ${count.next()}`]; case 'not': if (s.value === null) { return [`${key} IS NOT NULL}`, true]; } return [`${key} != ${count.next()}`]; case 'like': return [`${key} like '%' || ${count.next()} || '%'`]; case 'smallerThan': return [`${key} < ${count.next()}`]; case 'greaterThan': return [`${key} > ${count.next()}`]; default: throw new Error(`Unknown mode: ${s.mode}`); } } export default function buildSearchQ(config, search, param, searchQ) { let temp = searchQ; const keys = Object.keys(search); if (keys.length > 0) { const filter = []; const count = new ParamCounter(); for (const key of keys) { const s = search[key]; const meta = config.meta.get(key); if (!meta) { throw new Error('Missing meta'); } if (isQInterfaceSearchAdvanced(s)) { const [f, skip] = aFilter(String(key), s, count); filter.push(f); if (!skip) { convertSpecialFields(meta, s.value, param); } } else if (isQInterfaceSearchAdvancedArr(s)) { filter.push(...s.map((e) => { const [f, skip] = aFilter(String(key), e, count); if (!skip) { convertSpecialFields(meta, e.value, param); } return f; })); } else if (search[key] === null) { filter.push(`${String(key)} IS NULL`); } else { filter.push(`${String(key)} = ${count.next()}`); convertSpecialFields(meta, search[key], param); } } if (filter.length > 0) { temp = ` WHERE ${filter.join(' AND ')}`; } } return temp; }