UNPKG

@sqb/builder

Version:

Extensible multi-dialect SQL query builder written with TypeScript

90 lines (89 loc) 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CompOperator = void 0; const enums_js_1 = require("../../enums.js"); const serializable_js_1 = require("../../serializable.js"); const sqlobject_initializers_js_1 = require("../../sqlobject.initializers.js"); const field_expression_js_1 = require("../field-expression.js"); const operator_js_1 = require("../operator.js"); const param_expression_js_1 = require("../param-expression.js"); const EXPRESSION_PATTERN = /^([\w\\.$]+)(\[])?/; class CompOperator extends operator_js_1.Operator { _left; _right; _symbol; _isArray; constructor(left, right) { super(); if (typeof left === 'string') { const m = left.match(EXPRESSION_PATTERN); if (!m) throw new TypeError(`"${left}" is not a valid expression definition`); this._left = m[1]; this._isArray = !!m[2]; } else this._left = left; this._right = right; } get _type() { return enums_js_1.SerializationType.COMPARISON_EXPRESSION; } _serialize(ctx) { const left = this.__serializeItem(ctx, this._left); if (this._isArray) left.isArray = true; const right = this.__serializeItem(ctx, this._right, left); const o = { operatorType: this._operatorType, symbol: this._symbol, left, right, }; return this.__serialize(ctx, o); } __serializeItem(ctx, x, left) { const isRight = !!left; if (ctx.strictParams && !(x instanceof serializable_js_1.Serializable) && isRight) { ctx.strictParamGenId = ctx.strictParamGenId || 0; const name = 'P$_' + ++ctx.strictParamGenId; ctx.params = ctx.params || {}; ctx.params[name] = x; x = (0, sqlobject_initializers_js_1.Param)(name, left?.dataType, left?.isArray || Array.isArray(x)); } if (x instanceof serializable_js_1.Serializable) { const expression = ctx.anyToSQL(x); const result = { expression, }; if (x instanceof field_expression_js_1.FieldExpression) { result.dataType = x._dataType; result.isArray = x._isArray; } if (x instanceof param_expression_js_1.ParamExpression) { let value = ctx.params ? ctx.params[x._name] : undefined; if (x._isArray && value != null && !Array.isArray(value)) value = [value]; result.value = value; result.isArray = x._isArray || Array.isArray(value); result.isParam = true; } return result; } // noinspection SuspiciousTypeOfGuard const result = { expression: isRight || typeof x !== 'string' ? ctx.anyToSQL(x) : x, }; // noinspection SuspiciousTypeOfGuard if (isRight || typeof x !== 'string') result.isArray = Array.isArray(x); return result; } __serialize(ctx, o) { return ctx.serialize(this._type, o, (_ctx, _o) => this.__defaultSerialize(_ctx, _o)); } __defaultSerialize(ctx, o) { return o.left.expression + ' ' + o.symbol + ' ' + o.right.expression; } } exports.CompOperator = CompOperator;