API Reference Source

lib/dialects/postgres/query-interface.js

  1. 'use strict';
  2.  
  3. const DataTypes = require('../../data-types');
  4. const Promise = require('../../promise');
  5. const QueryTypes = require('../../query-types');
  6. const _ = require('lodash');
  7.  
  8.  
  9. /**
  10. Returns an object that handles Postgres special needs to do certain queries.
  11.  
  12. @class QueryInterface
  13. @static
  14. @private
  15. */
  16.  
  17. /**
  18. * Ensure enum and their values.
  19. *
  20. * @param {QueryInterface} qi
  21. * @param {string} tableName Name of table to create
  22. * @param {Object} attributes Object representing a list of normalized table attributes
  23. * @param {Object} [options]
  24. * @param {Model} [model]
  25. *
  26. * @returns {Promise}
  27. * @private
  28. */
  29. function ensureEnums(qi, tableName, attributes, options, model) {
  30. const keys = Object.keys(attributes);
  31. const keyLen = keys.length;
  32.  
  33. let sql = '';
  34. let promises = [];
  35. let i = 0;
  36.  
  37. for (i = 0; i < keyLen; i++) {
  38. const attribute = attributes[keys[i]];
  39. const type = attribute.type;
  40.  
  41. if (
  42. type instanceof DataTypes.ENUM ||
  43. type instanceof DataTypes.ARRAY && type.type instanceof DataTypes.ENUM //ARRAY sub type is ENUM
  44. ) {
  45. sql = qi.QueryGenerator.pgListEnums(tableName, attribute.field || keys[i], options);
  46. promises.push(qi.sequelize.query(
  47. sql,
  48. Object.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
  49. ));
  50. }
  51. }
  52.  
  53. return Promise.all(promises).then(results => {
  54. promises = [];
  55. let enumIdx = 0;
  56.  
  57. // This little function allows us to re-use the same code that prepends or appends new value to enum array
  58. const addEnumValue = (field, value, relativeValue, position = 'before', spliceStart = promises.length) => {
  59. const valueOptions = _.clone(options);
  60. valueOptions.before = null;
  61. valueOptions.after = null;
  62.  
  63. switch (position) {
  64. case 'after':
  65. valueOptions.after = relativeValue;
  66. break;
  67. case 'before':
  68. default:
  69. valueOptions.before = relativeValue;
  70. break;
  71. }
  72.  
  73. promises.splice(spliceStart, 0, () => {
  74. return qi.sequelize.query(qi.QueryGenerator.pgEnumAdd(
  75. tableName, field, value, valueOptions
  76. ), valueOptions);
  77. });
  78. };
  79.  
  80. for (i = 0; i < keyLen; i++) {
  81. const attribute = attributes[keys[i]];
  82. const type = attribute.type;
  83. const enumType = type.type || type;
  84. const field = attribute.field || keys[i];
  85.  
  86. if (
  87. type instanceof DataTypes.ENUM ||
  88. type instanceof DataTypes.ARRAY && enumType instanceof DataTypes.ENUM //ARRAY sub type is ENUM
  89. ) {
  90. // If the enum type doesn't exist then create it
  91. if (!results[enumIdx]) {
  92. promises.push(() => {
  93. return qi.sequelize.query(qi.QueryGenerator.pgEnum(tableName, field, enumType, options), Object.assign({}, options, { raw: true }));
  94. });
  95. } else if (!!results[enumIdx] && !!model) {
  96. const enumVals = qi.QueryGenerator.fromArray(results[enumIdx].enum_value);
  97. const vals = enumType.values;
  98.  
  99. // Going through already existing values allows us to make queries that depend on those values
  100. // We will prepend all new values between the old ones, but keep in mind - we can't change order of already existing values
  101. // Then we append the rest of new values AFTER the latest already existing value
  102. // E.g.: [1,2] -> [0,2,1] ==> [1,0,2]
  103. // E.g.: [1,2,3] -> [2,1,3,4] ==> [1,2,3,4]
  104. // E.g.: [1] -> [0,2,3] ==> [1,0,2,3]
  105. let lastOldEnumValue;
  106. let rightestPosition = -1;
  107. for (let oldIndex = 0; oldIndex < enumVals.length; oldIndex++) {
  108. const enumVal = enumVals[oldIndex];
  109. const newIdx = vals.indexOf(enumVal);
  110. lastOldEnumValue = enumVal;
  111.  
  112. if (newIdx === -1) {
  113. continue;
  114. }
  115.  
  116. const newValuesBefore = vals.slice(0, newIdx);
  117. const promisesLength = promises.length;
  118. // we go in reverse order so we could stop when we meet old value
  119. for (let reverseIdx = newValuesBefore.length - 1; reverseIdx >= 0; reverseIdx--) {
  120. if (~enumVals.indexOf(newValuesBefore[reverseIdx])) {
  121. break;
  122. }
  123.  
  124. addEnumValue(field, newValuesBefore[reverseIdx], lastOldEnumValue, 'before', promisesLength);
  125. }
  126.  
  127. // we detect the most 'right' position of old value in new enum array so we can append new values to it
  128. if (newIdx > rightestPosition) {
  129. rightestPosition = newIdx;
  130. }
  131. }
  132.  
  133. if (lastOldEnumValue && rightestPosition < vals.length - 1) {
  134. const remainingEnumValues = vals.slice(rightestPosition + 1);
  135. for (let reverseIdx = remainingEnumValues.length - 1; reverseIdx >= 0; reverseIdx--) {
  136. addEnumValue(field, remainingEnumValues[reverseIdx], lastOldEnumValue, 'after');
  137. }
  138. }
  139.  
  140. enumIdx++;
  141. }
  142. }
  143. }
  144.  
  145. return promises
  146. .reduce((promise, asyncFunction) => promise.then(asyncFunction), Promise.resolve())
  147. .tap(() => {
  148. // If ENUM processed, then refresh OIDs
  149. if (promises.length) {
  150. return qi.sequelize.dialect.connectionManager._refreshDynamicOIDs();
  151. }
  152. });
  153. });
  154. }
  155.  
  156.  
  157. exports.ensureEnums = ensureEnums;