UNPKG

mysql-all-in-one

Version:

A package that allows you to have a complete interaction with a MYSQL database, allowing to connect to the database, retrieve data and create queries.

53 lines (52 loc) 2.67 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const generate_query_from_prepared_statement_1 = require("../generate_query_from_prepared_statement"); const where_1 = __importDefault(require("../select/conditionals/where")); const order_1 = require("../select/order"); const types_1 = require("../types"); const utils_1 = require("../utils"); const types_2 = require("./types"); /** * * @param table Table to update * @param values New values, Object where keys are the columns to be updated * @param whereOpts Where object * @param opts Extra update options like `ignore`, `order`, `limit` * @returns UPDATE SQL Query * @example update('table', {name: "John", bornData: new Date(2020,8,30)}, {id: 1}) * >>> "UPDATE `table` SET `name` = 'John',`bornData` = '2020-09-30 00:00:00.000' WHERE (`table`.`id` = 1);" */ const update = (table, values, whereOpts, opts) => { if (!(0, types_2.isUpdateValues)(values)) throw 'Invalid argument values, expects object of SQL values.'; const { ignore, limit, returnPreparedStatement, order: orderOpts, } = Object.assign(Object.assign({}, types_2.defaultUpdateOptions), opts); const prepStatementValues = []; const tableRef = (0, utils_1.escapeNames)(table); const [_, alias] = (0, utils_1.extractTableAlias)(tableRef); const { statement: whereStatement, values: whereValues } = (0, where_1.default)(whereOpts, alias); const prepStatementQuery = `UPDATE ${ignore === true ? 'IGNORE ' : ''}${tableRef} SET ${Object.entries(values) .filter(([_, val]) => val !== undefined) .map(([key, val]) => { if ((0, types_1.isSqlExpressionPreparedStatement)(val)) { val = (0, utils_1.placeAliasInSqlExpression)(val, null); prepStatementValues.push(...val.values); return `${(0, utils_1.putBackticks)(key)} = ${(0, utils_1.putBrackets)(val.statement)}`; } prepStatementValues.push(val); return `${(0, utils_1.putBackticks)(key)} = ?`; }) .join(',')}${whereStatement}${(0, order_1.order)(orderOpts, alias)}${limit ? ` LIMIT ${limit}` : ''};`; prepStatementValues.push(...whereValues); const prepStatement = { statement: prepStatementQuery, values: prepStatementValues, __is_prep_statement: true, }; return returnPreparedStatement === true ? prepStatement : (0, generate_query_from_prepared_statement_1.generateQueryFromPreparedStatement)(prepStatement); }; exports.default = update;