@sqb/builder
Version:
Extensible multi-dialect SQL query builder written with TypeScript
84 lines (83 loc) • 2.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UpdateQuery = void 0;
const enums_js_1 = require("../enums.js");
const helpers_js_1 = require("../helpers.js");
const op_and_js_1 = require("../sql-objects/operators/op-and.js");
const table_name_js_1 = require("../sql-objects/table-name.js");
const typeguards_js_1 = require("../typeguards.js");
const returning_query_js_1 = require("./returning-query.js");
class UpdateQuery extends returning_query_js_1.ReturningQuery {
constructor(tableName, input) {
super();
if (!tableName ||
!(typeof tableName === 'string' || (0, typeguards_js_1.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 table_name_js_1.TableName(tableName) : tableName;
this._input = input;
}
get _type() {
return enums_js_1.SerializationType.UPDATE_QUERY;
}
/**
* Defines "where" part of query
*/
where(...operator) {
this._where = this._where || new op_and_js_1.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(enums_js_1.SerializationType.UPDATE_QUERY_VALUES, arr, () => {
const a = arr.map(o => o.field + ' = ' + o.value);
return (0, helpers_js_1.printArray)(a, ',');
});
}
/**
*
*/
__serializeWhere(ctx) {
if (!this._where)
return '';
const s = this._where._serialize(ctx);
return ctx.serialize(enums_js_1.SerializationType.CONDITIONS_BLOCK, s, () =>
/* istanbul ignore next */
s ? 'where ' + s : '');
}
}
exports.UpdateQuery = UpdateQuery;