@sqb/builder
Version:
Extensible multi-dialect SQL query builder written with TypeScript
88 lines (87 loc) • 2.4 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CaseStatement = void 0;
const enums_js_1 = require("../enums.js");
const serializable_js_1 = require("../serializable.js");
const op_and_js_1 = require("./operators/op-and.js");
class CaseStatement extends serializable_js_1.Serializable {
constructor() {
super();
this._expressions = [];
}
get _type() {
return enums_js_1.SerializationType.CASE_STATEMENT;
}
/**
* Defines "when" part of Case expression.
*/
when(...condition) {
if (condition.length)
this._condition = new op_and_js_1.OpAnd(...condition);
else
this._condition = undefined;
return this;
}
/**
* Defines "then" part of Case expression.
*/
then(value) {
if (this._condition) {
this._expressions.push({
condition: this._condition,
value,
});
}
return this;
}
/**
* Defines "else" part of Case expression.
*/
else(value) {
this._elseValue = value;
return this;
}
/**
* Sets alias to case expression.
*/
as(alias) {
this._alias = alias;
return this;
}
/**
* Performs serialization
*
* @param {Object} ctx
* @return {string}
* @override
*/
_serialize(ctx) {
if (!this._expressions.length)
return '';
const q = {
expressions: [],
elseValue: this._elseValue !== undefined
? ctx.anyToSQL(this._elseValue)
: undefined,
};
for (const x of this._expressions) {
const o = {
condition: x.condition._serialize(ctx),
value: ctx.anyToSQL(x.value),
};
q.expressions.push(o);
}
return ctx.serialize(this._type, q, () => this.__defaultSerialize(ctx, q));
}
__defaultSerialize(ctx, o) {
let out = 'case\n\t';
for (const x of o.expressions) {
out += 'when ' + x.condition + ' then ' + x.value + '\n';
}
if (o.elseValue !== undefined)
out += 'else ' + o.elseValue + '\n';
out += '\bend' + (this._alias ? ' ' + this._alias : '');
return out;
}
}
exports.CaseStatement = CaseStatement;