sets.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 {ColumnSet} = require('../column-set');
  10. const npm = {
  11. format: require('../../formatting').as.format,
  12. utils: require('../../utils')
  13. };
  14. /**
  15. * @method helpers.sets
  16. * @description
  17. * Generates a string of comma-separated value-set statements from a single object: `col1=val1, col2=val2, ...`,
  18. * to be used as part of a query.
  19. *
  20. * Since it is to be used as part of `UPDATE` queries, {@link helpers.Column Column} properties `cnd` and `skip` apply.
  21. *
  22. * @param {object} data
  23. * A simple, non-null and non-array source object.
  24. *
  25. * If it is anything else, the method will throw {@link external:TypeError TypeError} = `Invalid parameter 'data' specified.`
  26. *
  27. * @param {array|helpers.Column|helpers.ColumnSet} [columns]
  28. * Columns for which to set values.
  29. *
  30. * When not specified, properties of the `data` object are used.
  31. *
  32. * When no effective columns are found, an empty string is returned.
  33. *
  34. * @returns {string}
  35. * - comma-separated value-set statements for the `data` object
  36. * - an empty string, if no effective columns found
  37. *
  38. * @see
  39. * {@link helpers.Column Column},
  40. * {@link helpers.ColumnSet ColumnSet}
  41. *
  42. * @example
  43. *
  44. * const pgp = require('pg-promise')();
  45. *
  46. * const data = {id: 1, val: 123, msg: 'hello'};
  47. *
  48. * // Properties can be pulled automatically from the object:
  49. *
  50. * pgp.helpers.sets(data);
  51. * //=> "id"=1,"val"=123,"msg"='hello'
  52. *
  53. * @example
  54. *
  55. * // Column details from a reusable ColumnSet (recommended for performance);
  56. * // NOTE: Conditional columns (start with '?') are skipped:
  57. *
  58. * const cs = new pgp.helpers.ColumnSet(['?id','val', 'msg']);
  59. *
  60. * pgp.helpers.sets(data, cs);
  61. * //=> "val"=123,"msg"='hello'
  62. *
  63. */
  64. function sets(data, columns, capSQL) {
  65. if (!data || typeof data !== 'object' || Array.isArray(data)) {
  66. throw new TypeError('Invalid parameter \'data\' specified.');
  67. }
  68. if (!(columns instanceof ColumnSet)) {
  69. columns = new ColumnSet(columns || data);
  70. }
  71. return npm.format(columns.assign({source: data}), columns.prepare(data), {capSQL});
  72. }
  73. module.exports = {sets};