UNPKG

@sqb/builder

Version:

Extensible multi-dialect SQL query builder written with TypeScript

93 lines (92 loc) 3.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JoinStatement = void 0; const enums_js_1 = require("../enums.js"); const serializable_js_1 = require("../serializable.js"); const typeguards_js_1 = require("../typeguards.js"); const op_and_js_1 = require("./operators/op-and.js"); const table_name_js_1 = require("./table-name.js"); class JoinStatement extends serializable_js_1.Serializable { constructor(joinType, table) { super(); this._conditions = new op_and_js_1.OpAnd(); // noinspection SuspiciousTypeOfGuard if (!((0, typeguards_js_1.isSelectQuery)(table) || (0, typeguards_js_1.isRawStatement)(table) || (0, typeguards_js_1.isTableName)(table) || typeof table === 'string')) { throw new TypeError('Table name, select query or raw object required for Join'); } this._joinType = joinType; this._table = typeof table === 'string' ? new table_name_js_1.TableName(table) : table; } get _type() { return enums_js_1.SerializationType.JOIN; } on(...conditions) { this._conditions.add(...conditions); return this; } _serialize(ctx) { const o = { joinType: this._joinType, table: this._table._serialize(ctx), conditions: this.__serializeConditions(ctx, this), }; return ctx.serialize(this._type, o, () => { let out; switch (this._joinType) { case enums_js_1.JoinType.LEFT: out = 'left join'; break; case enums_js_1.JoinType.LEFT_OUTER: out = 'left outer join'; break; case enums_js_1.JoinType.RIGHT: out = 'right join'; break; case enums_js_1.JoinType.RIGHT_OUTER: out = 'right outer join'; break; case enums_js_1.JoinType.OUTER: out = 'outer join'; break; case enums_js_1.JoinType.FULL_OUTER: out = 'full outer join'; break; case enums_js_1.JoinType.CROSS: out = 'cross join'; break; default: out = 'inner join'; break; } const lf = o.table.length > 40; if ((0, typeguards_js_1.isSelectQuery)(this._table)) { const alias = this._table._alias; if (!alias) throw new Error('Alias required for sub-select in Join'); out += ' (' + (lf ? '\n\t' : '') + o.table + (lf ? '\n\b' : '') + ') ' + alias; } else out += ' ' + o.table; if (o.conditions) out += ' ' + o.conditions; return out + (lf ? '\b' : ''); }); } __serializeConditions(ctx, join) { if (join._conditions._items.length) { const s = join._conditions._serialize(ctx); return ctx.serialize(enums_js_1.SerializationType.JOIN_CONDITIONS, s, () => s ? 'on ' + s : ''); } return ''; } } exports.JoinStatement = JoinStatement;