column-set.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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 {InnerState} = require('../inner-state');
  10. const {assert} = require('../assert');
  11. const {TableName} = require('./table-name');
  12. const {Column} = require('./column');
  13. const npm = {
  14. os: require('os'),
  15. utils: require('../utils'),
  16. formatting: require('../formatting')
  17. };
  18. /**
  19. * @class helpers.ColumnSet
  20. * @description
  21. * Performance-optimized, read-only structure with query-formatting columns.
  22. *
  23. * In order to avail from performance optimization provided by this class, it should be created
  24. * only once, statically, and then reused.
  25. *
  26. * @param {object|helpers.Column|array} columns
  27. * Columns information object, depending on the type:
  28. *
  29. * - When it is a simple object, its properties are enumerated to represent both column names and property names
  30. * within the source objects. See also option `inherit` that's applicable in this case.
  31. *
  32. * - When it is a single {@link helpers.Column Column} object, property {@link helpers.ColumnSet#columns columns} is initialized with
  33. * just a single column. It is not a unique situation when only a single column is required for an update operation.
  34. *
  35. * - When it is an array, each element is assumed to represent details for a column. If the element is already of type {@link helpers.Column Column},
  36. * it is used directly; otherwise the element is passed into {@link helpers.Column Column} constructor for initialization.
  37. * On any duplicate column name (case-sensitive) it will throw {@link external:Error Error} = `Duplicate column name "name".`
  38. *
  39. * - When it is none of the above, it will throw {@link external:TypeError TypeError} = `Invalid parameter 'columns' specified.`
  40. *
  41. * @param {object} [options]
  42. *
  43. * @param {helpers.TableName|string|{table,schema}} [options.table]
  44. * Table details.
  45. *
  46. * When it is a non-null value, and not a {@link helpers.TableName TableName} object, a new {@link helpers.TableName TableName} is constructed from the value.
  47. *
  48. * It can be used as the default for methods {@link helpers.insert insert} and {@link helpers.update update} when their parameter
  49. * `table` is omitted, and for logging purposes.
  50. *
  51. * @param {boolean} [options.inherit = false]
  52. * Use inherited properties in addition to the object's own properties.
  53. *
  54. * By default, only the object's own properties are enumerated for column names.
  55. *
  56. * @returns {helpers.ColumnSet}
  57. *
  58. * @see
  59. *
  60. * {@link helpers.ColumnSet#columns columns},
  61. * {@link helpers.ColumnSet#names names},
  62. * {@link helpers.ColumnSet#table table},
  63. * {@link helpers.ColumnSet#variables variables} |
  64. * {@link helpers.ColumnSet#assign assign},
  65. * {@link helpers.ColumnSet#assignColumns assignColumns},
  66. * {@link helpers.ColumnSet#extend extend},
  67. * {@link helpers.ColumnSet#merge merge},
  68. * {@link helpers.ColumnSet#prepare prepare}
  69. *
  70. * @example
  71. *
  72. * // A complex insert/update object scenario for table 'purchases' in schema 'fiscal'.
  73. * // For a good performance, you should declare such objects once and then reuse them.
  74. * //
  75. * // Column Requirements:
  76. * //
  77. * // 1. Property 'id' is only to be used for a WHERE condition in updates
  78. * // 2. Property 'list' needs to be formatted as a csv
  79. * // 3. Property 'code' is to be used as raw text, and to be defaulted to 0 when the
  80. * // property is missing in the source object
  81. * // 4. Property 'log' is a JSON object with 'log-entry' for the column name
  82. * // 5. Property 'data' requires SQL type casting '::int[]'
  83. * // 6. Property 'amount' needs to be set to 100, if it is 0
  84. * // 7. Property 'total' must be skipped during updates, if 'amount' was 0, plus its
  85. * // column name is 'total-val'
  86. *
  87. * const cs = new pgp.helpers.ColumnSet([
  88. * '?id', // ColumnConfig equivalent: {name: 'id', cnd: true}
  89. * 'list:csv', // ColumnConfig equivalent: {name: 'list', mod: ':csv'}
  90. * {
  91. * name: 'code',
  92. * mod: '^', // format as raw text
  93. * def: 0 // default to 0 when the property doesn't exist
  94. * },
  95. * {
  96. * name: 'log-entry',
  97. * prop: 'log',
  98. * mod: ':json' // format as JSON
  99. * },
  100. * {
  101. * name: 'data',
  102. * cast: 'int[]' // use SQL type casting '::int[]'
  103. * },
  104. * {
  105. * name: 'amount',
  106. * init(col) {
  107. * // set to 100, if the value is 0:
  108. * return col.value === 0 ? 100 : col.value;
  109. * }
  110. * },
  111. * {
  112. * name: 'total-val',
  113. * prop: 'total',
  114. * skip(col) {
  115. * // skip from updates, if 'amount' is 0:
  116. * return col.source.amount === 0;
  117. * }
  118. * }
  119. * ], {table: {table: 'purchases', schema: 'fiscal'}});
  120. *
  121. * // Alternatively, you could take the table declaration out:
  122. * // const table = new pgp.helpers.TableName('purchases', 'fiscal');
  123. *
  124. * console.log(cs); // console output for the object:
  125. * //=>
  126. * // ColumnSet {
  127. * // table: "fiscal"."purchases"
  128. * // columns: [
  129. * // Column {
  130. * // name: "id"
  131. * // cnd: true
  132. * // }
  133. * // Column {
  134. * // name: "list"
  135. * // mod: ":csv"
  136. * // }
  137. * // Column {
  138. * // name: "code"
  139. * // mod: "^"
  140. * // def: 0
  141. * // }
  142. * // Column {
  143. * // name: "log-entry"
  144. * // prop: "log"
  145. * // mod: ":json"
  146. * // }
  147. * // Column {
  148. * // name: "data"
  149. * // cast: "int[]"
  150. * // }
  151. * // Column {
  152. * // name: "amount"
  153. * // init: [Function]
  154. * // }
  155. * // Column {
  156. * // name: "total-val"
  157. * // prop: "total"
  158. * // skip: [Function]
  159. * // }
  160. * // ]
  161. * // }
  162. */
  163. class ColumnSet extends InnerState {
  164. constructor(columns, opt) {
  165. super();
  166. if (!columns || typeof columns !== 'object') {
  167. throw new TypeError('Invalid parameter \'columns\' specified.');
  168. }
  169. opt = assert(opt, ['table', 'inherit']);
  170. if (!npm.utils.isNull(opt.table)) {
  171. this.table = (opt.table instanceof TableName) ? opt.table : new TableName(opt.table);
  172. }
  173. /**
  174. * @name helpers.ColumnSet#table
  175. * @type {helpers.TableName}
  176. * @readonly
  177. * @description
  178. * Destination table. It can be specified for two purposes:
  179. *
  180. * - **primary:** to be used as the default table when it is omitted during a call into methods {@link helpers.insert insert} and {@link helpers.update update}
  181. * - **secondary:** to be automatically written into the console (for logging purposes).
  182. */
  183. /**
  184. * @name helpers.ColumnSet#columns
  185. * @type helpers.Column[]
  186. * @readonly
  187. * @description
  188. * Array of {@link helpers.Column Column} objects.
  189. */
  190. if (Array.isArray(columns)) {
  191. const colNames = {};
  192. this.columns = columns.map(c => {
  193. const col = (c instanceof Column) ? c : new Column(c);
  194. if (col.name in colNames) {
  195. throw new Error(`Duplicate column name "${col.name}".`);
  196. }
  197. colNames[col.name] = true;
  198. return col;
  199. });
  200. } else {
  201. if (columns instanceof Column) {
  202. this.columns = [columns];
  203. } else {
  204. this.columns = [];
  205. for (const name in columns) {
  206. if (opt.inherit || Object.prototype.hasOwnProperty.call(columns, name)) {
  207. this.columns.push(new Column(name));
  208. }
  209. }
  210. }
  211. }
  212. Object.freeze(this.columns);
  213. Object.freeze(this);
  214. this.extendState({
  215. names: undefined,
  216. variables: undefined,
  217. updates: undefined,
  218. isSimple: true
  219. });
  220. for (let i = 0; i < this.columns.length; i++) {
  221. const c = this.columns[i];
  222. // ColumnSet is simple when the source objects require no preparation,
  223. // and should be used directly:
  224. if (c.prop || c.init || 'def' in c) {
  225. this._inner.isSimple = false;
  226. break;
  227. }
  228. }
  229. }
  230. /**
  231. * @name helpers.ColumnSet#names
  232. * @type string
  233. * @readonly
  234. * @description
  235. * Returns a string - comma-separated list of all column names, properly escaped.
  236. *
  237. * @example
  238. * const cs = new ColumnSet(['id^', {name: 'cells', cast: 'int[]'}, 'doc:json']);
  239. * console.log(cs.names);
  240. * //=> "id","cells","doc"
  241. */
  242. get names() {
  243. const _i = this._inner;
  244. if (!_i.names) {
  245. _i.names = this.columns.map(c => c.escapedName).join();
  246. }
  247. return _i.names;
  248. }
  249. /**
  250. * @name helpers.ColumnSet#variables
  251. * @type string
  252. * @readonly
  253. * @description
  254. * Returns a string - formatting template for all column values.
  255. *
  256. * @see {@link helpers.ColumnSet#assign assign}
  257. *
  258. * @example
  259. * const cs = new ColumnSet(['id^', {name: 'cells', cast: 'int[]'}, 'doc:json']);
  260. * console.log(cs.variables);
  261. * //=> ${id^},${cells}::int[],${doc:json}
  262. */
  263. get variables() {
  264. const _i = this._inner;
  265. if (!_i.variables) {
  266. _i.variables = this.columns.map(c => c.variable + c.castText).join();
  267. }
  268. return _i.variables;
  269. }
  270. }
  271. /**
  272. * @method helpers.ColumnSet#assign
  273. * @description
  274. * Returns a formatting template of SET assignments, either generic or for a single object.
  275. *
  276. * The method is optimized to cache the output string when there are no columns that can be skipped dynamically.
  277. *
  278. * This method is primarily for internal use, that's why it does not validate the input.
  279. *
  280. * @param {object} [options]
  281. * Assignment/formatting options.
  282. *
  283. * @param {object} [options.source]
  284. * Source - a single object that contains values for columns.
  285. *
  286. * The object is only necessary to correctly apply the logic of skipping columns dynamically, based on the source data
  287. * and the rules defined in the {@link helpers.ColumnSet ColumnSet}. If, however, you do not care about that, then you do not need to specify any object.
  288. *
  289. * Note that even if you do not specify the object, the columns marked as conditional (`cnd: true`) will always be skipped.
  290. *
  291. * @param {string} [options.prefix]
  292. * In cases where needed, an alias prefix to be added before each column.
  293. *
  294. * @returns {string}
  295. * Comma-separated list of variable-to-column assignments.
  296. *
  297. * @see {@link helpers.ColumnSet#variables variables}
  298. *
  299. * @example
  300. *
  301. * const cs = new pgp.helpers.ColumnSet([
  302. * '?first', // = {name: 'first', cnd: true}
  303. * 'second:json',
  304. * {name: 'third', mod: ':raw', cast: 'text'}
  305. * ]);
  306. *
  307. * cs.assign();
  308. * //=> "second"=${second:json},"third"=${third:raw}::text
  309. *
  310. * cs.assign({prefix: 'a b c'});
  311. * //=> "a b c"."second"=${second:json},"a b c"."third"=${third:raw}::text
  312. */
  313. ColumnSet.prototype.assign = function (options) {
  314. const _i = this._inner;
  315. const hasPrefix = options && options.prefix && typeof options.prefix === 'string';
  316. if (_i.updates && !hasPrefix) {
  317. return _i.updates;
  318. }
  319. let dynamic = hasPrefix;
  320. const hasSource = options && options.source && typeof options.source === 'object';
  321. let list = this.columns.filter(c => {
  322. if (c.cnd) {
  323. return false;
  324. }
  325. if (c.skip) {
  326. dynamic = true;
  327. if (hasSource) {
  328. const a = colDesc(c, options.source);
  329. if (c.skip.call(options.source, a)) {
  330. return false;
  331. }
  332. }
  333. }
  334. return true;
  335. });
  336. const prefix = hasPrefix ? npm.formatting.as.alias(options.prefix) + '.' : '';
  337. list = list.map(c => prefix + c.escapedName + '=' + c.variable + c.castText).join();
  338. if (!dynamic) {
  339. _i.updates = list;
  340. }
  341. return list;
  342. };
  343. /**
  344. * @method helpers.ColumnSet#assignColumns
  345. * @description
  346. * Generates assignments for all columns in the set, with support for aliases and column-skipping logic.
  347. * Aliases are set by using method {@link formatting.alias as.alias}.
  348. *
  349. * @param {{}} [options]
  350. * Optional Parameters.
  351. *
  352. * @param {string} [options.from]
  353. * Alias for the source columns.
  354. *
  355. * @param {string} [options.to]
  356. * Alias for the destination columns.
  357. *
  358. * @param {string | Array<string> | function} [options.skip]
  359. * Name(s) of the column(s) to be skipped (case-sensitive). It can be either a single string or an array of strings.
  360. *
  361. * It can also be a function - iterator, to be called for every column, passing in {@link helpers.Column Column} as
  362. * `this` context, and plus as a single parameter. The function would return a truthy value for every column that needs to be skipped.
  363. *
  364. * @returns {string}
  365. * A string of comma-separated column assignments.
  366. *
  367. * @example
  368. *
  369. * const cs = new pgp.helpers.ColumnSet(['id', 'city', 'street']);
  370. *
  371. * cs.assignColumns({from: 'EXCLUDED', skip: 'id'})
  372. * //=> "city"=EXCLUDED."city","street"=EXCLUDED."street"
  373. *
  374. * @example
  375. *
  376. * const cs = new pgp.helpers.ColumnSet(['?id', 'city', 'street']);
  377. *
  378. * cs.assignColumns({from: 'source', to: 'target', skip: c => c.cnd})
  379. * //=> target."city"=source."city",target."street"=source."street"
  380. *
  381. */
  382. ColumnSet.prototype.assignColumns = function (options) {
  383. options = assert(options, ['from', 'to', 'skip']);
  384. const skip = (typeof options.skip === 'string' && [options.skip]) || ((Array.isArray(options.skip) || typeof options.skip === 'function') && options.skip);
  385. const from = (typeof options.from === 'string' && options.from && (npm.formatting.as.alias(options.from) + '.')) || '';
  386. const to = (typeof options.to === 'string' && options.to && (npm.formatting.as.alias(options.to) + '.')) || '';
  387. const iterator = typeof skip === 'function' ? c => !skip.call(c, c) : c => skip.indexOf(c.name) === -1;
  388. const cols = skip ? this.columns.filter(iterator) : this.columns;
  389. return cols.map(c => to + c.escapedName + '=' + from + c.escapedName).join();
  390. };
  391. /**
  392. * @method helpers.ColumnSet#extend
  393. * @description
  394. * Creates a new {@link helpers.ColumnSet ColumnSet}, by joining the two sets of columns.
  395. *
  396. * If the two sets contain a column with the same `name` (case-sensitive), an error is thrown.
  397. *
  398. * @param {helpers.Column|helpers.ColumnSet|array} columns
  399. * Columns to be appended, of the same type as parameter `columns` during {@link helpers.ColumnSet ColumnSet} construction, except:
  400. * - it can also be of type {@link helpers.ColumnSet ColumnSet}
  401. * - it cannot be a simple object (properties enumeration is not supported here)
  402. *
  403. * @returns {helpers.ColumnSet}
  404. * New {@link helpers.ColumnSet ColumnSet} object with the extended/concatenated list of columns.
  405. *
  406. * @see
  407. * {@link helpers.Column Column},
  408. * {@link helpers.ColumnSet#merge merge}
  409. *
  410. * @example
  411. *
  412. * const pgp = require('pg-promise')();
  413. *
  414. * const cs = new pgp.helpers.ColumnSet(['one', 'two'], {table: 'my-table'});
  415. * console.log(cs);
  416. * //=>
  417. * // ColumnSet {
  418. * // table: "my-table"
  419. * // columns: [
  420. * // Column {
  421. * // name: "one"
  422. * // }
  423. * // Column {
  424. * // name: "two"
  425. * // }
  426. * // ]
  427. * // }
  428. * const csExtended = cs.extend(['three']);
  429. * console.log(csExtended);
  430. * //=>
  431. * // ColumnSet {
  432. * // table: "my-table"
  433. * // columns: [
  434. * // Column {
  435. * // name: "one"
  436. * // }
  437. * // Column {
  438. * // name: "two"
  439. * // }
  440. * // Column {
  441. * // name: "three"
  442. * // }
  443. * // ]
  444. * // }
  445. */
  446. ColumnSet.prototype.extend = function (columns) {
  447. let cs = columns;
  448. if (!(cs instanceof ColumnSet)) {
  449. cs = new ColumnSet(columns);
  450. }
  451. // Any duplicate column will throw Error = 'Duplicate column name "name".',
  452. return new ColumnSet(this.columns.concat(cs.columns), {table: this.table});
  453. };
  454. /**
  455. * @method helpers.ColumnSet#merge
  456. * @description
  457. * Creates a new {@link helpers.ColumnSet ColumnSet}, by joining the two sets of columns.
  458. *
  459. * Items in `columns` with the same `name` (case-sensitive) override the original columns.
  460. *
  461. * @param {helpers.Column|helpers.ColumnSet|array} columns
  462. * Columns to be appended, of the same type as parameter `columns` during {@link helpers.ColumnSet ColumnSet} construction, except:
  463. * - it can also be of type {@link helpers.ColumnSet ColumnSet}
  464. * - it cannot be a simple object (properties enumeration is not supported here)
  465. *
  466. * @see
  467. * {@link helpers.Column Column},
  468. * {@link helpers.ColumnSet#extend extend}
  469. *
  470. * @returns {helpers.ColumnSet}
  471. * New {@link helpers.ColumnSet ColumnSet} object with the merged list of columns.
  472. *
  473. * @example
  474. *
  475. * const pgp = require('pg-promise')();
  476. *
  477. * const cs = new pgp.helpers.ColumnSet(['?one', 'two:json'], {table: 'my-table'});
  478. * console.log(cs);
  479. * //=>
  480. * // ColumnSet {
  481. * // table: "my-table"
  482. * // columns: [
  483. * // Column {
  484. * // name: "one"
  485. * // cnd: true
  486. * // }
  487. * // Column {
  488. * // name: "two"
  489. * // mod: ":json"
  490. * // }
  491. * // ]
  492. * // }
  493. * const csMerged = cs.merge(['two', 'three^']);
  494. * console.log(csMerged);
  495. * //=>
  496. * // ColumnSet {
  497. * // table: "my-table"
  498. * // columns: [
  499. * // Column {
  500. * // name: "one"
  501. * // cnd: true
  502. * // }
  503. * // Column {
  504. * // name: "two"
  505. * // }
  506. * // Column {
  507. * // name: "three"
  508. * // mod: "^"
  509. * // }
  510. * // ]
  511. * // }
  512. *
  513. */
  514. ColumnSet.prototype.merge = function (columns) {
  515. let cs = columns;
  516. if (!(cs instanceof ColumnSet)) {
  517. cs = new ColumnSet(columns);
  518. }
  519. const colNames = {}, cols = [];
  520. this.columns.forEach((c, idx) => {
  521. cols.push(c);
  522. colNames[c.name] = idx;
  523. });
  524. cs.columns.forEach(c => {
  525. if (c.name in colNames) {
  526. cols[colNames[c.name]] = c;
  527. } else {
  528. cols.push(c);
  529. }
  530. });
  531. return new ColumnSet(cols, {table: this.table});
  532. };
  533. /**
  534. * @method helpers.ColumnSet#prepare
  535. * @description
  536. * Prepares a source object to be formatted, by cloning it and applying the rules as set by the
  537. * columns configuration.
  538. *
  539. * This method is primarily for internal use, that's why it does not validate the input parameters.
  540. *
  541. * @param {object} source
  542. * The source object to be prepared, if required.
  543. *
  544. * It must be a non-`null` object, which the method does not validate, as it is
  545. * intended primarily for internal use by the library.
  546. *
  547. * @returns {object}
  548. * When the object needs to be prepared, the method returns a clone of the source object,
  549. * with all properties and values set according to the columns configuration.
  550. *
  551. * When the object does not need to be prepared, the original object is returned.
  552. */
  553. ColumnSet.prototype.prepare = function (source) {
  554. if (this._inner.isSimple) {
  555. return source; // a simple ColumnSet requires no object preparation;
  556. }
  557. const target = {};
  558. this.columns.forEach(c => {
  559. const a = colDesc(c, source);
  560. if (c.init) {
  561. target[a.name] = c.init.call(source, a);
  562. } else {
  563. if (a.exists || 'def' in c) {
  564. target[a.name] = a.value;
  565. }
  566. }
  567. });
  568. return target;
  569. };
  570. function colDesc(column, source) {
  571. const a = {
  572. source,
  573. name: column.prop || column.name
  574. };
  575. a.exists = a.name in source;
  576. if (a.exists) {
  577. a.value = source[a.name];
  578. } else {
  579. a.value = 'def' in column ? column.def : undefined;
  580. }
  581. return a;
  582. }
  583. /**
  584. * @method helpers.ColumnSet#toString
  585. * @description
  586. * Creates a well-formatted multi-line string that represents the object.
  587. *
  588. * It is called automatically when writing the object into the console.
  589. *
  590. * @param {number} [level=0]
  591. * Nested output level, to provide visual offset.
  592. *
  593. * @returns {string}
  594. */
  595. ColumnSet.prototype.toString = function (level) {
  596. level = level > 0 ? parseInt(level) : 0;
  597. const gap0 = npm.utils.messageGap(level),
  598. gap1 = npm.utils.messageGap(level + 1),
  599. lines = [
  600. 'ColumnSet {'
  601. ];
  602. if (this.table) {
  603. lines.push(gap1 + 'table: ' + this.table);
  604. }
  605. if (this.columns.length) {
  606. lines.push(gap1 + 'columns: [');
  607. this.columns.forEach(c => {
  608. lines.push(c.toString(2));
  609. });
  610. lines.push(gap1 + ']');
  611. } else {
  612. lines.push(gap1 + 'columns: []');
  613. }
  614. lines.push(gap0 + '}');
  615. return lines.join(npm.os.EOL);
  616. };
  617. npm.utils.addInspection(ColumnSet, function () {
  618. return this.toString();
  619. });
  620. module.exports = {ColumnSet};