utils.js 16 KB

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