UNPKG

@sqb/builder

Version:

Extensible multi-dialect SQL query builder written with TypeScript

87 lines (86 loc) 3.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LogicalOperator = exports.WrapOps = void 0; const tslib_1 = require("tslib"); const putil_isplainobject_1 = tslib_1.__importDefault(require("putil-isplainobject")); const enums_js_1 = require("../../enums.js"); const helpers_js_1 = require("../../helpers.js"); const typeguards_js_1 = require("../../typeguards.js"); const operator_js_1 = require("../operator.js"); exports.WrapOps = {}; // noinspection RegExpUnnecessaryNonCapturingGroup const COMPARE_LEFT_PATTERN = /^([\w\\.$]+(?:\[])?) *(.*)$/; class LogicalOperator extends operator_js_1.Operator { _items = []; constructor(...expressions) { super(); this.add(...expressions); } get _type() { return enums_js_1.SerializationType.LOGICAL_EXPRESSION; } /** * Adds operator(s) to item list */ add(...expressions) { for (const item of expressions) { if (!item) continue; if ((0, typeguards_js_1.isLogicalOperator)(item)) { this._items.push(item); } else if ((0, typeguards_js_1.isRawStatement)(item) || (0, typeguards_js_1.isCompOperator)(item) || (0, typeguards_js_1.isNotOperator)(item)) { this._items.push(item); } else if ((0, putil_isplainobject_1.default)(item)) { this.add(...this._wrapObject(item)); } else throw new TypeError('Operator or Raw type required'); } return this; } _serialize(ctx) { const arr = []; for (const t of this._items) { const s = ctx.anyToSQL(t); /* istanbul ignore else */ if (s) arr.push(s); } return ctx.serialize(enums_js_1.SerializationType.LOGICAL_EXPRESSION, arr, () => { const s = (0, helpers_js_1.printArray)(arr, ' ' + String(this._operatorType)); return s.indexOf('\n') > 0 ? s.replace('\n', '\n\t') + '\b' : s; }); } // noinspection JSMethodCanBeStatic _wrapObject(obj) { const result = []; for (const n of Object.getOwnPropertyNames(obj)) { let op; const v = obj[n]; if (['and', 'or'].includes(n.toLowerCase())) { op = exports.WrapOps[n.toLowerCase()]; if (!op) throw new Error(`Unknown operator "${n}"`); result.push(Array.isArray(v) ? op(...v) : op(v)); continue; } if (['exists', '!exists'].includes(n)) result.push(exports.WrapOps[n](obj[n])); else { const m = n.match(COMPARE_LEFT_PATTERN); if (!m) throw new TypeError(`"${n}" is not a valid expression definition`); op = exports.WrapOps[m[2] || 'eq']; if (!op) throw new Error(`Unknown operator "${m[2]}"`); result.push(op(m[1], obj[n])); } } return result; } } exports.LogicalOperator = LogicalOperator;