utils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. 'use strict';
  2. const DataTypes = require('./data-types');
  3. const SqlString = require('./sql-string');
  4. const _ = require('lodash');
  5. const baseIsNative = require('lodash/_baseIsNative');
  6. const uuidv1 = require('uuid').v1;
  7. const uuidv4 = require('uuid').v4;
  8. const operators = require('./operators');
  9. const operatorsSet = new Set(Object.values(operators));
  10. let inflection = require('inflection');
  11. exports.classToInvokable = require('./utils/class-to-invokable').classToInvokable;
  12. exports.joinSQLFragments = require('./utils/join-sql-fragments').joinSQLFragments;
  13. function useInflection(_inflection) {
  14. inflection = _inflection;
  15. }
  16. exports.useInflection = useInflection;
  17. function camelizeIf(str, condition) {
  18. let result = str;
  19. if (condition) {
  20. result = camelize(str);
  21. }
  22. return result;
  23. }
  24. exports.camelizeIf = camelizeIf;
  25. function underscoredIf(str, condition) {
  26. let result = str;
  27. if (condition) {
  28. result = underscore(str);
  29. }
  30. return result;
  31. }
  32. exports.underscoredIf = underscoredIf;
  33. function isPrimitive(val) {
  34. const type = typeof val;
  35. return type === 'string' || type === 'number' || type === 'boolean';
  36. }
  37. exports.isPrimitive = isPrimitive;
  38. // Same concept as _.merge, but don't overwrite properties that have already been assigned
  39. function mergeDefaults(a, b) {
  40. return _.mergeWith(a, b, (objectValue, sourceValue) => {
  41. // If it's an object, let _ handle it this time, we will be called again for each property
  42. if (!_.isPlainObject(objectValue) && objectValue !== undefined) {
  43. // _.isNative includes a check for core-js and throws an error if present.
  44. // Depending on _baseIsNative bypasses the core-js check.
  45. if (_.isFunction(objectValue) && baseIsNative(objectValue)) {
  46. return sourceValue || objectValue;
  47. }
  48. return objectValue;
  49. }
  50. });
  51. }
  52. exports.mergeDefaults = mergeDefaults;
  53. // An alternative to _.merge, which doesn't clone its arguments
  54. // Cloning is a bad idea because options arguments may contain references to sequelize
  55. // models - which again reference database libs which don't like to be cloned (in particular pg-native)
  56. function merge() {
  57. const result = {};
  58. for (const obj of arguments) {
  59. _.forOwn(obj, (value, key) => {
  60. if (value !== undefined) {
  61. if (!result[key]) {
  62. result[key] = value;
  63. } else if (_.isPlainObject(value) && _.isPlainObject(result[key])) {
  64. result[key] = merge(result[key], value);
  65. } else if (Array.isArray(value) && Array.isArray(result[key])) {
  66. result[key] = value.concat(result[key]);
  67. } else {
  68. result[key] = value;
  69. }
  70. }
  71. });
  72. }
  73. return result;
  74. }
  75. exports.merge = merge;
  76. function spliceStr(str, index, count, add) {
  77. return str.slice(0, index) + add + str.slice(index + count);
  78. }
  79. exports.spliceStr = spliceStr;
  80. function camelize(str) {
  81. return str.trim().replace(/[-_\s]+(.)?/g, (match, c) => c.toUpperCase());
  82. }
  83. exports.camelize = camelize;
  84. function underscore(str) {
  85. return inflection.underscore(str);
  86. }
  87. exports.underscore = underscore;
  88. function singularize(str) {
  89. return inflection.singularize(str);
  90. }
  91. exports.singularize = singularize;
  92. function pluralize(str) {
  93. return inflection.pluralize(str);
  94. }
  95. exports.pluralize = pluralize;
  96. function format(arr, dialect) {
  97. const timeZone = null;
  98. // Make a clone of the array beacuse format modifies the passed args
  99. return SqlString.format(arr[0], arr.slice(1), timeZone, dialect);
  100. }
  101. exports.format = format;
  102. function formatNamedParameters(sql, parameters, dialect) {
  103. const timeZone = null;
  104. return SqlString.formatNamedParameters(sql, parameters, timeZone, dialect);
  105. }
  106. exports.formatNamedParameters = formatNamedParameters;
  107. function cloneDeep(obj, onlyPlain) {
  108. obj = obj || {};
  109. return _.cloneDeepWith(obj, elem => {
  110. // Do not try to customize cloning of arrays or POJOs
  111. if (Array.isArray(elem) || _.isPlainObject(elem)) {
  112. return undefined;
  113. }
  114. // If we specified to clone only plain objects & arrays, we ignore everyhing else
  115. // In any case, don't clone stuff that's an object, but not a plain one - fx example sequelize models and instances
  116. if (onlyPlain || typeof elem === 'object') {
  117. return elem;
  118. }
  119. // Preserve special data-types like `fn` across clones. _.get() is used for checking up the prototype chain
  120. if (elem && typeof elem.clone === 'function') {
  121. return elem.clone();
  122. }
  123. });
  124. }
  125. exports.cloneDeep = cloneDeep;
  126. /* Expand and normalize finder options */
  127. function mapFinderOptions(options, Model) {
  128. if (options.attributes && Array.isArray(options.attributes)) {
  129. options.attributes = Model._injectDependentVirtualAttributes(options.attributes);
  130. options.attributes = options.attributes.filter(v => !Model._virtualAttributes.has(v));
  131. }
  132. mapOptionFieldNames(options, Model);
  133. return options;
  134. }
  135. exports.mapFinderOptions = mapFinderOptions;
  136. /* Used to map field names in attributes and where conditions */
  137. function mapOptionFieldNames(options, Model) {
  138. if (Array.isArray(options.attributes)) {
  139. options.attributes = options.attributes.map(attr => {
  140. // Object lookups will force any variable to strings, we don't want that for special objects etc
  141. if (typeof attr !== 'string') return attr;
  142. // Map attributes to aliased syntax attributes
  143. if (Model.rawAttributes[attr] && attr !== Model.rawAttributes[attr].field) {
  144. return [Model.rawAttributes[attr].field, attr];
  145. }
  146. return attr;
  147. });
  148. }
  149. if (options.where && _.isPlainObject(options.where)) {
  150. options.where = mapWhereFieldNames(options.where, Model);
  151. }
  152. return options;
  153. }
  154. exports.mapOptionFieldNames = mapOptionFieldNames;
  155. function mapWhereFieldNames(attributes, Model) {
  156. if (attributes) {
  157. getComplexKeys(attributes).forEach(attribute => {
  158. const rawAttribute = Model.rawAttributes[attribute];
  159. if (rawAttribute && rawAttribute.field !== rawAttribute.fieldName) {
  160. attributes[rawAttribute.field] = attributes[attribute];
  161. delete attributes[attribute];
  162. }
  163. if (_.isPlainObject(attributes[attribute])
  164. && !(rawAttribute && (
  165. rawAttribute.type instanceof DataTypes.HSTORE
  166. || rawAttribute.type instanceof DataTypes.JSON))) { // Prevent renaming of HSTORE & JSON fields
  167. attributes[attribute] = mapOptionFieldNames({
  168. where: attributes[attribute]
  169. }, Model).where;
  170. }
  171. if (Array.isArray(attributes[attribute])) {
  172. attributes[attribute].forEach((where, index) => {
  173. if (_.isPlainObject(where)) {
  174. attributes[attribute][index] = mapWhereFieldNames(where, Model);
  175. }
  176. });
  177. }
  178. });
  179. }
  180. return attributes;
  181. }
  182. exports.mapWhereFieldNames = mapWhereFieldNames;
  183. /* Used to map field names in values */
  184. function mapValueFieldNames(dataValues, fields, Model) {
  185. const values = {};
  186. for (const attr of fields) {
  187. if (dataValues[attr] !== undefined && !Model._virtualAttributes.has(attr)) {
  188. // Field name mapping
  189. if (Model.rawAttributes[attr] && Model.rawAttributes[attr].field && Model.rawAttributes[attr].field !== attr) {
  190. values[Model.rawAttributes[attr].field] = dataValues[attr];
  191. } else {
  192. values[attr] = dataValues[attr];
  193. }
  194. }
  195. }
  196. return values;
  197. }
  198. exports.mapValueFieldNames = mapValueFieldNames;
  199. function isColString(value) {
  200. return typeof value === 'string' && value[0] === '$' && value[value.length - 1] === '$';
  201. }
  202. exports.isColString = isColString;
  203. function canTreatArrayAsAnd(arr) {
  204. return arr.some(arg => _.isPlainObject(arg) || arg instanceof Where);
  205. }
  206. exports.canTreatArrayAsAnd = canTreatArrayAsAnd;
  207. function combineTableNames(tableName1, tableName2) {
  208. return tableName1.toLowerCase() < tableName2.toLowerCase() ? tableName1 + tableName2 : tableName2 + tableName1;
  209. }
  210. exports.combineTableNames = combineTableNames;
  211. function toDefaultValue(value, dialect) {
  212. if (typeof value === 'function') {
  213. const tmp = value();
  214. if (tmp instanceof DataTypes.ABSTRACT) {
  215. return tmp.toSql();
  216. }
  217. return tmp;
  218. }
  219. if (value instanceof DataTypes.UUIDV1) {
  220. return uuidv1();
  221. }
  222. if (value instanceof DataTypes.UUIDV4) {
  223. return uuidv4();
  224. }
  225. if (value instanceof DataTypes.NOW) {
  226. return now(dialect);
  227. }
  228. if (Array.isArray(value)) {
  229. return value.slice();
  230. }
  231. if (_.isPlainObject(value)) {
  232. return { ...value };
  233. }
  234. return value;
  235. }
  236. exports.toDefaultValue = toDefaultValue;
  237. /**
  238. * Determine if the default value provided exists and can be described
  239. * in a db schema using the DEFAULT directive.
  240. *
  241. * @param {*} value Any default value.
  242. * @returns {boolean} yes / no.
  243. * @private
  244. */
  245. function defaultValueSchemable(value) {
  246. if (value === undefined) { return false; }
  247. // TODO this will be schemable when all supported db
  248. // have been normalized for this case
  249. if (value instanceof DataTypes.NOW) { return false; }
  250. if (value instanceof DataTypes.UUIDV1 || value instanceof DataTypes.UUIDV4) { return false; }
  251. return typeof value !== 'function';
  252. }
  253. exports.defaultValueSchemable = defaultValueSchemable;
  254. function removeNullValuesFromHash(hash, omitNull, options) {
  255. let result = hash;
  256. options = options || {};
  257. options.allowNull = options.allowNull || [];
  258. if (omitNull) {
  259. const _hash = {};
  260. _.forIn(hash, (val, key) => {
  261. if (options.allowNull.includes(key) || key.endsWith('Id') || val !== null && val !== undefined) {
  262. _hash[key] = val;
  263. }
  264. });
  265. result = _hash;
  266. }
  267. return result;
  268. }
  269. exports.removeNullValuesFromHash = removeNullValuesFromHash;
  270. const dialects = new Set(['mariadb', 'mysql', 'postgres', 'sqlite', 'mssql']);
  271. function now(dialect) {
  272. const d = new Date();
  273. if (!dialects.has(dialect)) {
  274. d.setMilliseconds(0);
  275. }
  276. return d;
  277. }
  278. exports.now = now;
  279. // Note: Use the `quoteIdentifier()` and `escape()` methods on the
  280. // `QueryInterface` instead for more portable code.
  281. const TICK_CHAR = '`';
  282. exports.TICK_CHAR = TICK_CHAR;
  283. function addTicks(s, tickChar) {
  284. tickChar = tickChar || TICK_CHAR;
  285. return tickChar + removeTicks(s, tickChar) + tickChar;
  286. }
  287. exports.addTicks = addTicks;
  288. function removeTicks(s, tickChar) {
  289. tickChar = tickChar || TICK_CHAR;
  290. return s.replace(new RegExp(tickChar, 'g'), '');
  291. }
  292. exports.removeTicks = removeTicks;
  293. /**
  294. * Receives a tree-like object and returns a plain object which depth is 1.
  295. *
  296. * - Input:
  297. *
  298. * {
  299. * name: 'John',
  300. * address: {
  301. * street: 'Fake St. 123',
  302. * coordinates: {
  303. * longitude: 55.6779627,
  304. * latitude: 12.5964313
  305. * }
  306. * }
  307. * }
  308. *
  309. * - Output:
  310. *
  311. * {
  312. * name: 'John',
  313. * address.street: 'Fake St. 123',
  314. * address.coordinates.latitude: 55.6779627,
  315. * address.coordinates.longitude: 12.5964313
  316. * }
  317. *
  318. * @param {object} value an Object
  319. * @returns {object} a flattened object
  320. * @private
  321. */
  322. function flattenObjectDeep(value) {
  323. if (!_.isPlainObject(value)) return value;
  324. const flattenedObj = {};
  325. function flattenObject(obj, subPath) {
  326. Object.keys(obj).forEach(key => {
  327. const pathToProperty = subPath ? `${subPath}.${key}` : key;
  328. if (typeof obj[key] === 'object' && obj[key] !== null) {
  329. flattenObject(obj[key], pathToProperty);
  330. } else {
  331. flattenedObj[pathToProperty] = _.get(obj, key);
  332. }
  333. });
  334. return flattenedObj;
  335. }
  336. return flattenObject(value, undefined);
  337. }
  338. exports.flattenObjectDeep = flattenObjectDeep;
  339. /**
  340. * Utility functions for representing SQL functions, and columns that should be escaped.
  341. * Please do not use these functions directly, use Sequelize.fn and Sequelize.col instead.
  342. *
  343. * @private
  344. */
  345. class SequelizeMethod {}
  346. exports.SequelizeMethod = SequelizeMethod;
  347. class Fn extends SequelizeMethod {
  348. constructor(fn, args) {
  349. super();
  350. this.fn = fn;
  351. this.args = args;
  352. }
  353. clone() {
  354. return new Fn(this.fn, this.args);
  355. }
  356. }
  357. exports.Fn = Fn;
  358. class Col extends SequelizeMethod {
  359. constructor(col, ...args) {
  360. super();
  361. if (args.length > 0) {
  362. col = args;
  363. }
  364. this.col = col;
  365. }
  366. }
  367. exports.Col = Col;
  368. class Cast extends SequelizeMethod {
  369. constructor(val, type, json) {
  370. super();
  371. this.val = val;
  372. this.type = (type || '').trim();
  373. this.json = json || false;
  374. }
  375. }
  376. exports.Cast = Cast;
  377. class Literal extends SequelizeMethod {
  378. constructor(val) {
  379. super();
  380. this.val = val;
  381. }
  382. }
  383. exports.Literal = Literal;
  384. class Json extends SequelizeMethod {
  385. constructor(conditionsOrPath, value) {
  386. super();
  387. if (_.isObject(conditionsOrPath)) {
  388. this.conditions = conditionsOrPath;
  389. } else {
  390. this.path = conditionsOrPath;
  391. if (value) {
  392. this.value = value;
  393. }
  394. }
  395. }
  396. }
  397. exports.Json = Json;
  398. class Where extends SequelizeMethod {
  399. constructor(attribute, comparator, logic) {
  400. super();
  401. if (logic === undefined) {
  402. logic = comparator;
  403. comparator = '=';
  404. }
  405. this.attribute = attribute;
  406. this.comparator = comparator;
  407. this.logic = logic;
  408. }
  409. }
  410. exports.Where = Where;
  411. //Collection of helper methods to make it easier to work with symbol operators
  412. /**
  413. * getOperators
  414. *
  415. * @param {object} obj
  416. * @returns {Array<symbol>} All operators properties of obj
  417. * @private
  418. */
  419. function getOperators(obj) {
  420. return Object.getOwnPropertySymbols(obj).filter(s => operatorsSet.has(s));
  421. }
  422. exports.getOperators = getOperators;
  423. /**
  424. * getComplexKeys
  425. *
  426. * @param {object} obj
  427. * @returns {Array<string|symbol>} All keys including operators
  428. * @private
  429. */
  430. function getComplexKeys(obj) {
  431. return getOperators(obj).concat(Object.keys(obj));
  432. }
  433. exports.getComplexKeys = getComplexKeys;
  434. /**
  435. * getComplexSize
  436. *
  437. * @param {object|Array} obj
  438. * @returns {number} Length of object properties including operators if obj is array returns its length
  439. * @private
  440. */
  441. function getComplexSize(obj) {
  442. return Array.isArray(obj) ? obj.length : getComplexKeys(obj).length;
  443. }
  444. exports.getComplexSize = getComplexSize;
  445. /**
  446. * Returns true if a where clause is empty, even with Symbols
  447. *
  448. * @param {object} obj
  449. * @returns {boolean}
  450. * @private
  451. */
  452. function isWhereEmpty(obj) {
  453. return !!obj && _.isEmpty(obj) && getOperators(obj).length === 0;
  454. }
  455. exports.isWhereEmpty = isWhereEmpty;
  456. /**
  457. * Returns ENUM name by joining table and column name
  458. *
  459. * @param {string} tableName
  460. * @param {string} columnName
  461. * @returns {string}
  462. * @private
  463. */
  464. function generateEnumName(tableName, columnName) {
  465. return `enum_${tableName}_${columnName}`;
  466. }
  467. exports.generateEnumName = generateEnumName;
  468. /**
  469. * Returns an new Object which keys are camelized
  470. *
  471. * @param {object} obj
  472. * @returns {string}
  473. * @private
  474. */
  475. function camelizeObjectKeys(obj) {
  476. const newObj = new Object();
  477. Object.keys(obj).forEach(key => {
  478. newObj[camelize(key)] = obj[key];
  479. });
  480. return newObj;
  481. }
  482. exports.camelizeObjectKeys = camelizeObjectKeys;
  483. /**
  484. * Assigns own and inherited enumerable string and symbol keyed properties of source
  485. * objects to the destination object.
  486. *
  487. * https://lodash.com/docs/4.17.4#defaults
  488. *
  489. * **Note:** This method mutates `object`.
  490. *
  491. * @param {object} object The destination object.
  492. * @param {...object} [sources] The source objects.
  493. * @returns {object} Returns `object`.
  494. * @private
  495. */
  496. function defaults(object, ...sources) {
  497. object = Object(object);
  498. sources.forEach(source => {
  499. if (source) {
  500. source = Object(source);
  501. getComplexKeys(source).forEach(key => {
  502. const value = object[key];
  503. if (
  504. value === undefined ||
  505. _.eq(value, Object.prototype[key]) &&
  506. !Object.prototype.hasOwnProperty.call(object, key)
  507. ) {
  508. object[key] = source[key];
  509. }
  510. });
  511. }
  512. });
  513. return object;
  514. }
  515. exports.defaults = defaults;
  516. /**
  517. *
  518. * @param {object} index
  519. * @param {Array} index.fields
  520. * @param {string} [index.name]
  521. * @param {string|object} tableName
  522. *
  523. * @returns {object}
  524. * @private
  525. */
  526. function nameIndex(index, tableName) {
  527. if (tableName.tableName) tableName = tableName.tableName;
  528. if (!Object.prototype.hasOwnProperty.call(index, 'name')) {
  529. const fields = index.fields.map(
  530. field => typeof field === 'string' ? field : field.name || field.attribute
  531. );
  532. index.name = underscore(`${tableName}_${fields.join('_')}`);
  533. }
  534. return index;
  535. }
  536. exports.nameIndex = nameIndex;
  537. /**
  538. * Checks if 2 arrays intersect.
  539. *
  540. * @param {Array} arr1
  541. * @param {Array} arr2
  542. * @private
  543. */
  544. function intersects(arr1, arr2) {
  545. return arr1.some(v => arr2.includes(v));
  546. }
  547. exports.intersects = intersects;