update.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /*
  2. * Copyright (c) 2015-present, Vitaly Tomilov
  3. *
  4. * See the LICENSE file at the top-level directory of this distribution
  5. * for licensing information.
  6. *
  7. * Removal or modification of this copyright notice is prohibited.
  8. */
  9. const {assert} = require('../../assert');
  10. const {TableName} = require('../table-name');
  11. const {ColumnSet} = require('../column-set');
  12. const npm = {
  13. formatting: require('../../formatting'),
  14. utils: require('../../utils')
  15. };
  16. /**
  17. * @method helpers.update
  18. * @description
  19. * Generates a simplified `UPDATE` query for either one object or an array of objects.
  20. *
  21. * The resulting query needs a `WHERE` clause to be appended to it, to specify the update logic.
  22. * This is to allow for update conditions of any complexity that are easy to add.
  23. *
  24. * @param {object|object[]} data
  25. * An update object with properties for update values, or an array of such objects.
  26. *
  27. * When `data` is not a non-null object and not an array, it will throw {@link external:TypeError TypeError} = `Invalid parameter 'data' specified.`
  28. *
  29. * When `data` is an empty array, it will throw {@link external:TypeError TypeError} = `Cannot generate an UPDATE from an empty array.`
  30. *
  31. * When `data` is an array that contains a non-object value, the method will throw {@link external:Error Error} =
  32. * `Invalid update object at index N.`
  33. *
  34. * @param {array|helpers.Column|helpers.ColumnSet} [columns]
  35. * Set of columns to be updated.
  36. *
  37. * It is optional when `data` is a single object, and required when `data` is an array of objects. If not specified for an array
  38. * of objects, the method will throw {@link external:TypeError TypeError} = `Parameter 'columns' is required when updating multiple records.`
  39. *
  40. * When `columns` is not a {@link helpers.ColumnSet ColumnSet} object, a temporary {@link helpers.ColumnSet ColumnSet}
  41. * is created - from the value of `columns` (if it was specified), or from the value of `data` (if it is not an array).
  42. *
  43. * When the final {@link helpers.ColumnSet ColumnSet} is empty (no columns in it), the method will throw
  44. * {@link external:Error Error} = `Cannot generate an UPDATE without any columns.`, unless option `emptyUpdate` was specified.
  45. *
  46. * @param {helpers.TableName|string|{table,schema}} [table]
  47. * Table to be updated.
  48. *
  49. * It is normally a required parameter. But when `columns` is passed in as a {@link helpers.ColumnSet ColumnSet} object
  50. * with `table` set in it, that will be used when this parameter isn't specified. When neither is available, the method
  51. * will throw {@link external:Error Error} = `Table name is unknown.`
  52. *
  53. * @param {{}} [options]
  54. * An object with formatting options for multi-row `UPDATE` queries.
  55. *
  56. * @param {string} [options.tableAlias=t]
  57. * Name of the SQL variable that represents the destination table.
  58. *
  59. * @param {string} [options.valueAlias=v]
  60. * Name of the SQL variable that represents the values.
  61. *
  62. * @param {*} [options.emptyUpdate]
  63. * This is a convenience option, to avoid throwing an error when generating a conditional update results in no columns.
  64. *
  65. * When present, regardless of the value, this option overrides the method's behavior when applying `skip` logic results in no columns,
  66. * i.e. when every column is being skipped.
  67. *
  68. * By default, in that situation the method throws {@link external:Error Error} = `Cannot generate an UPDATE without any columns.`
  69. * But when this option is present, the method will instead return whatever value the option was passed.
  70. *
  71. * @returns {*}
  72. * An `UPDATE` query string that needs a `WHERE` condition appended.
  73. *
  74. * If it results in an empty update, and option `emptyUpdate` was passed in, then the method returns the value
  75. * to which the option was set.
  76. *
  77. * @see
  78. * {@link helpers.Column Column},
  79. * {@link helpers.ColumnSet ColumnSet},
  80. * {@link helpers.TableName TableName}
  81. *
  82. * @example
  83. *
  84. * const pgp = require('pg-promise')({
  85. * capSQL: true // if you want all generated SQL capitalized
  86. * });
  87. *
  88. * const dataSingle = {id: 1, val: 123, msg: 'hello'};
  89. * const dataMulti = [{id: 1, val: 123, msg: 'hello'}, {id: 2, val: 456, msg: 'world!'}];
  90. *
  91. * // Although column details can be taken from the data object, it is not
  92. * // a likely scenario for an update, unless updating the whole table:
  93. *
  94. * pgp.helpers.update(dataSingle, null, 'my-table');
  95. * //=> UPDATE "my-table" SET "id"=1,"val"=123,"msg"='hello'
  96. *
  97. * @example
  98. *
  99. * // A typical single-object update:
  100. *
  101. * // Dynamic conditions must be escaped/formatted properly:
  102. * const condition = pgp.as.format(' WHERE id = ${id}', dataSingle);
  103. *
  104. * pgp.helpers.update(dataSingle, ['val', 'msg'], 'my-table') + condition;
  105. * //=> UPDATE "my-table" SET "val"=123,"msg"='hello' WHERE id = 1
  106. *
  107. * @example
  108. *
  109. * // Column details are required for a multi-row `UPDATE`;
  110. * // Adding '?' in front of a column name means it is only for a WHERE condition:
  111. *
  112. * pgp.helpers.update(dataMulti, ['?id', 'val', 'msg'], 'my-table') + ' WHERE v.id = t.id';
  113. * //=> UPDATE "my-table" AS t SET "val"=v."val","msg"=v."msg" FROM (VALUES(1,123,'hello'),(2,456,'world!'))
  114. * // AS v("id","val","msg") WHERE v.id = t.id
  115. *
  116. * @example
  117. *
  118. * // Column details from a reusable ColumnSet (recommended for performance):
  119. *
  120. * const cs = new pgp.helpers.ColumnSet(['?id', 'val', 'msg'], {table: 'my-table'});
  121. *
  122. * pgp.helpers.update(dataMulti, cs) + ' WHERE v.id = t.id';
  123. * //=> UPDATE "my-table" AS t SET "val"=v."val","msg"=v."msg" FROM (VALUES(1,123,'hello'),(2,456,'world!'))
  124. * // AS v("id","val","msg") WHERE v.id = t.id
  125. *
  126. * @example
  127. *
  128. * // Using parameter `options` to change the default alias names:
  129. *
  130. * pgp.helpers.update(dataMulti, cs, null, {tableAlias: 'X', valueAlias: 'Y'}) + ' WHERE Y.id = X.id';
  131. * //=> UPDATE "my-table" AS X SET "val"=Y."val","msg"=Y."msg" FROM (VALUES(1,123,'hello'),(2,456,'world!'))
  132. * // AS Y("id","val","msg") WHERE Y.id = X.id
  133. *
  134. * @example
  135. *
  136. * // Handling an empty update
  137. *
  138. * const cs = new pgp.helpers.ColumnSet(['?id', '?name'], {table: 'tt'}); // no actual update-able columns
  139. * const result = pgp.helpers.update(dataMulti, cs, null, {emptyUpdate: 123});
  140. * if(result === 123) {
  141. * // We know the update is empty, i.e. no columns that can be updated;
  142. * // And it didn't throw because we specified `emptyUpdate` option.
  143. * }
  144. */
  145. function update(data, columns, table, options, capSQL) {
  146. if (!data || typeof data !== 'object') {
  147. throw new TypeError('Invalid parameter \'data\' specified.');
  148. }
  149. const isArray = Array.isArray(data);
  150. if (isArray && !data.length) {
  151. throw new TypeError('Cannot generate an UPDATE from an empty array.');
  152. }
  153. if (columns instanceof ColumnSet) {
  154. if (npm.utils.isNull(table)) {
  155. table = columns.table;
  156. }
  157. } else {
  158. if (isArray && npm.utils.isNull(columns)) {
  159. throw new TypeError('Parameter \'columns\' is required when updating multiple records.');
  160. }
  161. columns = new ColumnSet(columns || data);
  162. }
  163. options = assert(options, ['tableAlias', 'valueAlias', 'emptyUpdate']);
  164. const format = npm.formatting.as.format,
  165. useEmptyUpdate = 'emptyUpdate' in options,
  166. fmOptions = {capSQL};
  167. if (isArray) {
  168. const tableAlias = npm.formatting.as.alias(npm.utils.isNull(options.tableAlias) ? 't' : options.tableAlias);
  169. const valueAlias = npm.formatting.as.alias(npm.utils.isNull(options.valueAlias) ? 'v' : options.valueAlias);
  170. const q = capSQL ? sql.multi.capCase : sql.multi.lowCase;
  171. const actualColumns = columns.columns.filter(c => !c.cnd);
  172. if (checkColumns(actualColumns)) {
  173. return options.emptyUpdate;
  174. }
  175. checkTable();
  176. const targetCols = actualColumns.map(c => c.escapedName + '=' + valueAlias + '.' + c.escapedName).join();
  177. const values = data.map((d, index) => {
  178. if (!d || typeof d !== 'object') {
  179. throw new Error(`Invalid update object at index ${index}.`);
  180. }
  181. return '(' + format(columns.variables, columns.prepare(d), fmOptions) + ')';
  182. }).join();
  183. return format(q, [table.name, tableAlias, targetCols, values, valueAlias, columns.names], fmOptions);
  184. }
  185. const updates = columns.assign({source: data});
  186. if (checkColumns(updates)) {
  187. return options.emptyUpdate;
  188. }
  189. checkTable();
  190. const query = capSQL ? sql.single.capCase : sql.single.lowCase;
  191. return format(query, table.name) + format(updates, columns.prepare(data), fmOptions);
  192. function checkTable() {
  193. if (table && !(table instanceof TableName)) {
  194. table = new TableName(table);
  195. }
  196. if (!table) {
  197. throw new Error('Table name is unknown.');
  198. }
  199. }
  200. function checkColumns(cols) {
  201. if (!cols.length) {
  202. if (useEmptyUpdate) {
  203. return true;
  204. }
  205. throw new Error('Cannot generate an UPDATE without any columns.');
  206. }
  207. }
  208. }
  209. const sql = {
  210. single: {
  211. lowCase: 'update $1^ set ',
  212. capCase: 'UPDATE $1^ SET '
  213. },
  214. multi: {
  215. lowCase: 'update $1^ as $2^ set $3^ from (values$4^) as $5^($6^)',
  216. capCase: 'UPDATE $1^ AS $2^ SET $3^ FROM (VALUES$4^) AS $5^($6^)'
  217. }
  218. };
  219. module.exports = {update};