UNPKG

@sqb/builder

Version:

Extensible multi-dialect SQL query builder written with TypeScript

83 lines (82 loc) 2.66 kB
import { SerializationType } from '../enums.js'; import { printArray } from '../helpers.js'; import { OpAnd } from '../sql-objects/operators/op-and.js'; import { TableName } from '../sql-objects/table-name.js'; import { isRawStatement } from '../typeguards.js'; import { ReturningQuery } from './returning-query.js'; export class UpdateQuery extends ReturningQuery { _table; _input; _where; constructor(tableName, input) { super(); if (!tableName || !(typeof tableName === 'string' || isRawStatement(tableName))) { throw new TypeError('String or Raw instance required as first argument (tableName) for UpdateQuery'); } if (!input || !((typeof input === 'object' && !Array.isArray(input)) || input.isSelect)) { throw new TypeError('Object or Raw instance required as second argument (input) for UpdateQuery'); } this._table = typeof tableName === 'string' ? new TableName(tableName) : tableName; this._input = input; } get _type() { return SerializationType.UPDATE_QUERY; } /** * Defines "where" part of query */ where(...operator) { this._where = this._where || new OpAnd(); this._where.add(...operator); return this; } /** * Performs serialization */ _serialize(ctx) { const o = { table: this._table._serialize(ctx), values: this.__serializeValues(ctx), where: this.__serializeWhere(ctx), returning: this.__serializeReturning(ctx), }; let out = 'update ' + o.table + ' set \n\t' + o.values + '\b'; if (o.where) out += '\n' + o.where; if (o.returning) out += '\n' + o.returning; return out; } /** * */ __serializeValues(ctx) { const arr = []; const allValues = this._input; for (const n of Object.getOwnPropertyNames(allValues)) { const value = ctx.anyToSQL(allValues[n]); arr.push({ field: n, value, }); } return ctx.serialize(SerializationType.UPDATE_QUERY_VALUES, arr, () => { const a = arr.map(o => o.field + ' = ' + o.value); return printArray(a, ','); }); } /** * */ __serializeWhere(ctx) { if (!this._where) return ''; const s = this._where._serialize(ctx); return ctx.serialize(SerializationType.CONDITIONS_BLOCK, s, () => /* istanbul ignore next */ s ? 'where ' + s : ''); } }