utils.js 16 KB

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