UNPKG

@sqb/builder

Version:

Extensible multi-dialect SQL query builder written with TypeScript

85 lines (84 loc) 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InsertQuery = void 0; const enums_js_1 = require("../enums.js"); const helpers_js_1 = require("../helpers.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 InsertQuery 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 InsertQuery'); } if (!input || !((typeof input === 'object' && !Array.isArray(input)) || input.isSelect)) { throw new TypeError('Object or SelectQuery instance required as second argument (input) for InsertQuery'); } this._table = typeof tableName === 'string' ? new table_name_js_1.TableName(tableName) : tableName; this._input = input; } get _type() { return enums_js_1.SerializationType.INSERT_QUERY; } /** * Performs serialization */ _serialize(ctx) { const o = { table: this._table._serialize(ctx), columns: this.__serializeColumns(ctx), values: this.__serializeValues(ctx), returning: this.__serializeReturning(ctx), }; let out = 'insert into ' + o.table + '\n\t(' + o.columns + ')\n\bvalues\n\t(' + o.values + ')\b'; if (o.returning) out += '\n' + o.returning; return out; } /** * */ __serializeColumns(ctx) { let arr; if ((0, typeguards_js_1.isSelectQuery)(this._input)) { arr = []; const cols = this._input._columns; if (cols) { for (const col of cols) { if (col._alias) arr.push(col._alias); else if (col._field) arr.push(col._field); } } } else arr = Object.keys(this._input); return ctx.serialize(enums_js_1.SerializationType.INSERT_QUERY_COLUMNS, arr, () => (0, helpers_js_1.printArray)(arr)); } /** * */ __serializeValues(ctx) { if ((0, typeguards_js_1.isSerializable)(this._input)) return this._input._serialize(ctx); const arr = []; const allValues = this._input; for (const n of Object.keys(allValues)) { const s = ctx.anyToSQL(allValues[n]) || 'null'; arr.push(s); } return ctx.serialize(enums_js_1.SerializationType.INSERT_QUERY_VALUES, arr, () => (0, helpers_js_1.printArray)(arr)); } } exports.InsertQuery = InsertQuery;