utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  6. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  7. var __spreadValues = (a, b) => {
  8. for (var prop in b || (b = {}))
  9. if (__hasOwnProp.call(b, prop))
  10. __defNormalProp(a, prop, b[prop]);
  11. if (__getOwnPropSymbols)
  12. for (var prop of __getOwnPropSymbols(b)) {
  13. if (__propIsEnum.call(b, prop))
  14. __defNormalProp(a, prop, b[prop]);
  15. }
  16. return a;
  17. };
  18. const DataTypes = require("./data-types");
  19. const SqlString = require("./sql-string");
  20. const _ = require("lodash");
  21. const baseIsNative = require("lodash/_baseIsNative");
  22. const uuidv1 = require("uuid").v1;
  23. const uuidv4 = require("uuid").v4;
  24. const operators = require("./operators");
  25. const operatorsSet = new Set(Object.values(operators));
  26. let inflection = require("inflection");
  27. exports.classToInvokable = require("./utils/class-to-invokable").classToInvokable;
  28. exports.joinSQLFragments = require("./utils/join-sql-fragments").joinSQLFragments;
  29. function useInflection(_inflection) {
  30. inflection = _inflection;
  31. }
  32. exports.useInflection = useInflection;
  33. function camelizeIf(str, condition) {
  34. let result = str;
  35. if (condition) {
  36. result = camelize(str);
  37. }
  38. return result;
  39. }
  40. exports.camelizeIf = camelizeIf;
  41. function underscoredIf(str, condition) {
  42. let result = str;
  43. if (condition) {
  44. result = underscore(str);
  45. }
  46. return result;
  47. }
  48. exports.underscoredIf = underscoredIf;
  49. function isPrimitive(val) {
  50. const type = typeof val;
  51. return ["string", "number", "boolean"].includes(type);
  52. }
  53. exports.isPrimitive = isPrimitive;
  54. function mergeDefaults(a, b) {
  55. return _.mergeWith(a, b, (objectValue, sourceValue) => {
  56. if (!_.isPlainObject(objectValue) && objectValue !== void 0) {
  57. if (_.isFunction(objectValue) && baseIsNative(objectValue)) {
  58. return sourceValue || objectValue;
  59. }
  60. return objectValue;
  61. }
  62. });
  63. }
  64. exports.mergeDefaults = mergeDefaults;
  65. function merge() {
  66. const result = {};
  67. for (const obj of arguments) {
  68. _.forOwn(obj, (value, key) => {
  69. if (value !== void 0) {
  70. if (!result[key]) {
  71. result[key] = value;
  72. } else if (_.isPlainObject(value) && _.isPlainObject(result[key])) {
  73. result[key] = merge(result[key], value);
  74. } else if (Array.isArray(value) && Array.isArray(result[key])) {
  75. result[key] = value.concat(result[key]);
  76. } else {
  77. result[key] = value;
  78. }
  79. }
  80. });
  81. }
  82. return result;
  83. }
  84. exports.merge = merge;
  85. function spliceStr(str, index, count, add) {
  86. return str.slice(0, index) + add + str.slice(index + count);
  87. }
  88. exports.spliceStr = spliceStr;
  89. function camelize(str) {
  90. return str.trim().replace(/[-_\s]+(.)?/g, (match, c) => c.toUpperCase());
  91. }
  92. exports.camelize = camelize;
  93. function underscore(str) {
  94. return inflection.underscore(str);
  95. }
  96. exports.underscore = underscore;
  97. function singularize(str) {
  98. return inflection.singularize(str);
  99. }
  100. exports.singularize = singularize;
  101. function pluralize(str) {
  102. return inflection.pluralize(str);
  103. }
  104. exports.pluralize = pluralize;
  105. function format(arr, dialect) {
  106. const timeZone = null;
  107. return SqlString.format(arr[0], arr.slice(1), timeZone, dialect);
  108. }
  109. exports.format = format;
  110. function formatNamedParameters(sql, parameters, dialect) {
  111. const timeZone = null;
  112. return SqlString.formatNamedParameters(sql, parameters, timeZone, dialect);
  113. }
  114. exports.formatNamedParameters = formatNamedParameters;
  115. function cloneDeep(obj, onlyPlain) {
  116. obj = obj || {};
  117. return _.cloneDeepWith(obj, (elem) => {
  118. if (Array.isArray(elem) || _.isPlainObject(elem)) {
  119. return void 0;
  120. }
  121. if (onlyPlain || typeof elem === "object") {
  122. return elem;
  123. }
  124. if (elem && typeof elem.clone === "function") {
  125. return elem.clone();
  126. }
  127. });
  128. }
  129. exports.cloneDeep = cloneDeep;
  130. function mapFinderOptions(options, Model) {
  131. if (options.attributes && Array.isArray(options.attributes)) {
  132. options.attributes = Model._injectDependentVirtualAttributes(options.attributes);
  133. options.attributes = options.attributes.filter((v) => !Model._virtualAttributes.has(v));
  134. }
  135. mapOptionFieldNames(options, Model);
  136. return options;
  137. }
  138. exports.mapFinderOptions = mapFinderOptions;
  139. function mapOptionFieldNames(options, Model) {
  140. if (Array.isArray(options.attributes)) {
  141. options.attributes = options.attributes.map((attr) => {
  142. if (typeof attr !== "string")
  143. return attr;
  144. if (Model.rawAttributes[attr] && attr !== Model.rawAttributes[attr].field) {
  145. return [Model.rawAttributes[attr].field, attr];
  146. }
  147. return attr;
  148. });
  149. }
  150. if (options.where && _.isPlainObject(options.where)) {
  151. options.where = mapWhereFieldNames(options.where, Model);
  152. }
  153. return options;
  154. }
  155. exports.mapOptionFieldNames = mapOptionFieldNames;
  156. function mapWhereFieldNames(attributes, Model) {
  157. if (attributes) {
  158. attributes = cloneDeep(attributes);
  159. getComplexKeys(attributes).forEach((attribute) => {
  160. const rawAttribute = Model.rawAttributes[attribute];
  161. if (rawAttribute && rawAttribute.field !== rawAttribute.fieldName) {
  162. attributes[rawAttribute.field] = attributes[attribute];
  163. delete attributes[attribute];
  164. }
  165. if (_.isPlainObject(attributes[attribute]) && !(rawAttribute && (rawAttribute.type instanceof DataTypes.HSTORE || rawAttribute.type instanceof DataTypes.JSON))) {
  166. attributes[attribute] = mapOptionFieldNames({
  167. where: attributes[attribute]
  168. }, Model).where;
  169. }
  170. if (Array.isArray(attributes[attribute])) {
  171. attributes[attribute].forEach((where, index) => {
  172. if (_.isPlainObject(where)) {
  173. attributes[attribute][index] = mapWhereFieldNames(where, Model);
  174. }
  175. });
  176. }
  177. });
  178. }
  179. return attributes;
  180. }
  181. exports.mapWhereFieldNames = mapWhereFieldNames;
  182. function mapValueFieldNames(dataValues, fields, Model) {
  183. const values = {};
  184. for (const attr of fields) {
  185. if (dataValues[attr] !== void 0 && !Model._virtualAttributes.has(attr)) {
  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 __spreadValues({}, value);
  230. }
  231. return value;
  232. }
  233. exports.toDefaultValue = toDefaultValue;
  234. function defaultValueSchemable(value) {
  235. if (value === void 0) {
  236. return false;
  237. }
  238. if (value instanceof DataTypes.NOW) {
  239. return false;
  240. }
  241. if (value instanceof DataTypes.UUIDV1 || value instanceof DataTypes.UUIDV4) {
  242. return false;
  243. }
  244. return typeof value !== "function";
  245. }
  246. exports.defaultValueSchemable = defaultValueSchemable;
  247. function removeNullValuesFromHash(hash, omitNull, options) {
  248. let result = hash;
  249. options = options || {};
  250. options.allowNull = options.allowNull || [];
  251. if (omitNull) {
  252. const _hash = {};
  253. _.forIn(hash, (val, key) => {
  254. if (options.allowNull.includes(key) || key.endsWith("Id") || val !== null && val !== void 0) {
  255. _hash[key] = val;
  256. }
  257. });
  258. result = _hash;
  259. }
  260. return result;
  261. }
  262. exports.removeNullValuesFromHash = removeNullValuesFromHash;
  263. const dialects = /* @__PURE__ */ new Set(["mariadb", "mysql", "postgres", "sqlite", "mssql", "db2"]);
  264. function now(dialect) {
  265. const d = new Date();
  266. if (!dialects.has(dialect)) {
  267. d.setMilliseconds(0);
  268. }
  269. return d;
  270. }
  271. exports.now = now;
  272. const TICK_CHAR = "`";
  273. exports.TICK_CHAR = TICK_CHAR;
  274. function addTicks(s, tickChar) {
  275. tickChar = tickChar || TICK_CHAR;
  276. return tickChar + removeTicks(s, tickChar) + tickChar;
  277. }
  278. exports.addTicks = addTicks;
  279. function removeTicks(s, tickChar) {
  280. tickChar = tickChar || TICK_CHAR;
  281. return s.replace(new RegExp(tickChar, "g"), "");
  282. }
  283. exports.removeTicks = removeTicks;
  284. function flattenObjectDeep(value) {
  285. if (!_.isPlainObject(value))
  286. return value;
  287. const flattenedObj = {};
  288. function flattenObject(obj, subPath) {
  289. Object.keys(obj).forEach((key) => {
  290. const pathToProperty = subPath ? `${subPath}.${key}` : key;
  291. if (typeof obj[key] === "object" && obj[key] !== null) {
  292. flattenObject(obj[key], pathToProperty);
  293. } else {
  294. flattenedObj[pathToProperty] = _.get(obj, key);
  295. }
  296. });
  297. return flattenedObj;
  298. }
  299. return flattenObject(value, void 0);
  300. }
  301. exports.flattenObjectDeep = flattenObjectDeep;
  302. class SequelizeMethod {
  303. }
  304. exports.SequelizeMethod = SequelizeMethod;
  305. class Fn extends SequelizeMethod {
  306. constructor(fn, args) {
  307. super();
  308. this.fn = fn;
  309. this.args = args;
  310. }
  311. clone() {
  312. return new Fn(this.fn, this.args);
  313. }
  314. }
  315. exports.Fn = Fn;
  316. class Col extends SequelizeMethod {
  317. constructor(col, ...args) {
  318. super();
  319. if (args.length > 0) {
  320. col = args;
  321. }
  322. this.col = col;
  323. }
  324. }
  325. exports.Col = Col;
  326. class Cast extends SequelizeMethod {
  327. constructor(val, type, json) {
  328. super();
  329. this.val = val;
  330. this.type = (type || "").trim();
  331. this.json = json || false;
  332. }
  333. }
  334. exports.Cast = Cast;
  335. class Literal extends SequelizeMethod {
  336. constructor(val) {
  337. super();
  338. this.val = val;
  339. }
  340. }
  341. exports.Literal = Literal;
  342. class Json extends SequelizeMethod {
  343. constructor(conditionsOrPath, value) {
  344. super();
  345. if (_.isObject(conditionsOrPath)) {
  346. this.conditions = conditionsOrPath;
  347. } else {
  348. this.path = conditionsOrPath;
  349. if (value) {
  350. this.value = value;
  351. }
  352. }
  353. }
  354. }
  355. exports.Json = Json;
  356. class Where extends SequelizeMethod {
  357. constructor(attribute, comparator, logic) {
  358. super();
  359. if (logic === void 0) {
  360. logic = comparator;
  361. comparator = "=";
  362. }
  363. this.attribute = attribute;
  364. this.comparator = comparator;
  365. this.logic = logic;
  366. }
  367. }
  368. exports.Where = Where;
  369. function getOperators(obj) {
  370. return Object.getOwnPropertySymbols(obj).filter((s) => operatorsSet.has(s));
  371. }
  372. exports.getOperators = getOperators;
  373. function getComplexKeys(obj) {
  374. return getOperators(obj).concat(Object.keys(obj));
  375. }
  376. exports.getComplexKeys = getComplexKeys;
  377. function getComplexSize(obj) {
  378. return Array.isArray(obj) ? obj.length : getComplexKeys(obj).length;
  379. }
  380. exports.getComplexSize = getComplexSize;
  381. function isWhereEmpty(obj) {
  382. return !!obj && _.isEmpty(obj) && getOperators(obj).length === 0;
  383. }
  384. exports.isWhereEmpty = isWhereEmpty;
  385. function generateEnumName(tableName, columnName) {
  386. return `enum_${tableName}_${columnName}`;
  387. }
  388. exports.generateEnumName = generateEnumName;
  389. function camelizeObjectKeys(obj) {
  390. const newObj = new Object();
  391. Object.keys(obj).forEach((key) => {
  392. newObj[camelize(key)] = obj[key];
  393. });
  394. return newObj;
  395. }
  396. exports.camelizeObjectKeys = camelizeObjectKeys;
  397. function defaults(object, ...sources) {
  398. object = Object(object);
  399. sources.forEach((source) => {
  400. if (source) {
  401. source = Object(source);
  402. getComplexKeys(source).forEach((key) => {
  403. const value = object[key];
  404. if (value === void 0 || _.eq(value, Object.prototype[key]) && !Object.prototype.hasOwnProperty.call(object, key)) {
  405. object[key] = source[key];
  406. }
  407. });
  408. }
  409. });
  410. return object;
  411. }
  412. exports.defaults = defaults;
  413. function nameIndex(index, tableName) {
  414. if (tableName.tableName)
  415. tableName = tableName.tableName;
  416. if (!Object.prototype.hasOwnProperty.call(index, "name")) {
  417. const fields = index.fields.map((field) => typeof field === "string" ? field : field.name || field.attribute);
  418. index.name = underscore(`${tableName}_${fields.join("_")}`);
  419. }
  420. return index;
  421. }
  422. exports.nameIndex = nameIndex;
  423. function intersects(arr1, arr2) {
  424. return arr1.some((v) => arr2.includes(v));
  425. }
  426. exports.intersects = intersects;
  427. function safeStringifyJson(value) {
  428. return JSON.stringify(value, (key, value2) => {
  429. if (typeof value2 === "bigint") {
  430. return String(value2);
  431. }
  432. return value2;
  433. });
  434. }
  435. exports.safeStringifyJson = safeStringifyJson;
  436. //# sourceMappingURL=utils.js.map