Guest User

Dirty Fix Typeorm Circular Dependency Vite 0.3.9

a guest
Sep 11th, 2022
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 267.89 KB | Source Code | 0 0
  1. diff --git a/node_modules/typeorm/browser/platform/BrowserPlatformTools.js b/node_modules/typeorm/browser/platform/BrowserPlatformTools.js
  2. index 59dea25..387781a 100644
  3. --- a/node_modules/typeorm/browser/platform/BrowserPlatformTools.js
  4. +++ b/node_modules/typeorm/browser/platform/BrowserPlatformTools.js
  5. @@ -1,3 +1,5 @@
  6. +import { Buffer } from 'buffer';
  7. +
  8. /**
  9. * Browser's implementation of the platform-specific tools.
  10. *
  11. @@ -131,7 +133,7 @@ export class Readable {
  12. export class Writable {
  13. }
  14. if (typeof window !== "undefined") {
  15. - window.Buffer = require("buffer/").Buffer;
  16. + window.Buffer = Buffer;
  17. }
  18. // NativeScript uses global, not window
  19. if (typeof global !== "undefined") {
  20. diff --git a/node_modules/typeorm/browser/query-builder/DeleteQueryBuilder.js b/node_modules/typeorm/browser/query-builder/DeleteQueryBuilder.js
  21. index a8c9d3f..01c6e43 100644
  22. --- a/node_modules/typeorm/browser/query-builder/DeleteQueryBuilder.js
  23. +++ b/node_modules/typeorm/browser/query-builder/DeleteQueryBuilder.js
  24. @@ -1,11 +1,11 @@
  25. -import { QueryBuilder } from "./QueryBuilder";
  26. import { DeleteResult } from "./result/DeleteResult";
  27. import { ReturningStatementNotSupportedError } from "../error/ReturningStatementNotSupportedError";
  28. import { InstanceChecker } from "../util/InstanceChecker";
  29. +import { DeleteQueryBuilderBase } from "./DeleteQueryBuilderBase";
  30. /**
  31. * Allows to build complex sql queries in a fashion way and execute those queries.
  32. */
  33. -export class DeleteQueryBuilder extends QueryBuilder {
  34. +export class DeleteQueryBuilder extends DeleteQueryBuilderBase {
  35. // -------------------------------------------------------------------------
  36. // Constructor
  37. // -------------------------------------------------------------------------
  38. diff --git a/node_modules/typeorm/browser/query-builder/DeleteQueryBuilderBase.js b/node_modules/typeorm/browser/query-builder/DeleteQueryBuilderBase.js
  39. new file mode 100644
  40. index 0000000..65aee13
  41. --- /dev/null
  42. +++ b/node_modules/typeorm/browser/query-builder/DeleteQueryBuilderBase.js
  43. @@ -0,0 +1,1133 @@
  44. +import { QueryExpressionMap } from './QueryExpressionMap';
  45. +import { Brackets } from './Brackets';
  46. +import { FindOperator } from '../find-options/FindOperator';
  47. +import { In } from '../find-options/operator/In';
  48. +import { TypeORMError } from '../error';
  49. +import { EntityPropertyNotFoundError } from '../error/EntityPropertyNotFoundError';
  50. +import { InstanceChecker } from '../util/InstanceChecker';
  51. +import { escapeRegExp } from '../util/escapeRegExp';
  52. +// todo: completely cover query builder with tests
  53. +// todo: entityOrProperty can be target name. implement proper behaviour if it is.
  54. +// todo: check in persistment if id exist on object and throw exception (can be in partial selection?)
  55. +// todo: fix problem with long aliases eg getMaxIdentifierLength
  56. +// todo: fix replacing in .select("COUNT(post.id) AS cnt") statement
  57. +// todo: implement joinAlways in relations and relationId
  58. +// todo: finish partial selection
  59. +// todo: sugar methods like: .addCount and .selectCount, selectCountAndMap, selectSum, selectSumAndMap, ...
  60. +// todo: implement @Select decorator
  61. +// todo: add select and map functions
  62. +// todo: implement relation/entity loading and setting them into properties within a separate query
  63. +// .loadAndMap("post.categories", "post.categories", qb => ...)
  64. +// .loadAndMap("post.categories", Category, qb => ...)
  65. +/**
  66. + * Allows to build complex sql queries in a fashion way and execute those queries.
  67. + */
  68. +export class DeleteQueryBuilderBase {
  69. + /**
  70. + * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
  71. + */
  72. + constructor(connectionOrQueryBuilder, queryRunner) {
  73. + this['@instanceof'] = Symbol.for('QueryBuilder');
  74. + /**
  75. + * Memo to help keep place of current parameter index for `createParameter`
  76. + */
  77. + this.parameterIndex = 0;
  78. + if (InstanceChecker.isQueryBuilder(connectionOrQueryBuilder)) {
  79. + this.connection = connectionOrQueryBuilder.connection;
  80. + this.queryRunner = connectionOrQueryBuilder.queryRunner;
  81. + this.expressionMap = connectionOrQueryBuilder.expressionMap.clone();
  82. + } else {
  83. + this.connection = connectionOrQueryBuilder;
  84. + this.queryRunner = queryRunner;
  85. + this.expressionMap = new QueryExpressionMap(this.connection);
  86. + }
  87. + }
  88. + // -------------------------------------------------------------------------
  89. + // Accessors
  90. + // -------------------------------------------------------------------------
  91. + /**
  92. + * Gets the main alias string used in this query builder.
  93. + */
  94. + get alias() {
  95. + if (!this.expressionMap.mainAlias)
  96. + throw new TypeORMError(`Main alias is not set`); // todo: better exception
  97. + return this.expressionMap.mainAlias.name;
  98. + }
  99. + /**
  100. + * Creates SELECT query and selects given data.
  101. + * Replaces all previous selections if they exist.
  102. + */
  103. + select(selection, selectionAliasName) {
  104. + this.expressionMap.queryType = 'select';
  105. + if (Array.isArray(selection)) {
  106. + this.expressionMap.selects = selection.map((selection) => ({
  107. + selection: selection,
  108. + }));
  109. + } else if (selection) {
  110. + this.expressionMap.selects = [
  111. + { selection: selection, aliasName: selectionAliasName },
  112. + ];
  113. + }
  114. + // loading it dynamically because of circular issue
  115. + const SelectQueryBuilderCls =
  116. + require('typeorm/browser/query-builder/SelectQueryBuilder').SelectQueryBuilder;
  117. + if (InstanceChecker.isSelectQueryBuilder(this)) return this;
  118. + return new SelectQueryBuilderCls(this);
  119. + }
  120. + /**
  121. + * Creates INSERT query.
  122. + */
  123. + insert() {
  124. + this.expressionMap.queryType = 'insert';
  125. + // loading it dynamically because of circular issue
  126. + const InsertQueryBuilderCls =
  127. + require('typeorm/browser/query-builder/InsertQueryBuilder').InsertQueryBuilder;
  128. + if (InstanceChecker.isInsertQueryBuilder(this)) return this;
  129. + return new InsertQueryBuilderCls(this);
  130. + }
  131. + /**
  132. + * Creates UPDATE query and applies given update values.
  133. + */
  134. + update(entityOrTableNameUpdateSet, maybeUpdateSet) {
  135. + const updateSet = maybeUpdateSet
  136. + ? maybeUpdateSet
  137. + : entityOrTableNameUpdateSet;
  138. + entityOrTableNameUpdateSet = InstanceChecker.isEntitySchema(
  139. + entityOrTableNameUpdateSet
  140. + )
  141. + ? entityOrTableNameUpdateSet.options.name
  142. + : entityOrTableNameUpdateSet;
  143. + if (
  144. + typeof entityOrTableNameUpdateSet === 'function' ||
  145. + typeof entityOrTableNameUpdateSet === 'string'
  146. + ) {
  147. + const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet);
  148. + this.expressionMap.setMainAlias(mainAlias);
  149. + }
  150. + this.expressionMap.queryType = 'update';
  151. + this.expressionMap.valuesSet = updateSet;
  152. + // loading it dynamically because of circular issue
  153. + const UpdateQueryBuilderCls =
  154. + require('typeorm/browser/query-builder/UpdateQueryBuilder').UpdateQueryBuilder;
  155. + if (InstanceChecker.isUpdateQueryBuilder(this)) return this;
  156. + return new UpdateQueryBuilderCls(this);
  157. + }
  158. + /**
  159. + * Creates DELETE query.
  160. + */
  161. + delete() {
  162. + this.expressionMap.queryType = 'delete';
  163. + // loading it dynamically because of circular issue
  164. + const DeleteQueryBuilderCls =
  165. + require('typeorm/browser/query-builder/DeleteQueryBuilder').DeleteQueryBuilder;
  166. + if (InstanceChecker.isDeleteQueryBuilder(this)) return this;
  167. + return new DeleteQueryBuilderCls(this);
  168. + }
  169. + softDelete() {
  170. + this.expressionMap.queryType = 'soft-delete';
  171. + // loading it dynamically because of circular issue
  172. + const SoftDeleteQueryBuilderCls =
  173. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  174. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  175. + return new SoftDeleteQueryBuilderCls(this);
  176. + }
  177. + restore() {
  178. + this.expressionMap.queryType = 'restore';
  179. + // loading it dynamically because of circular issue
  180. + const SoftDeleteQueryBuilderCls =
  181. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  182. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  183. + return new SoftDeleteQueryBuilderCls(this);
  184. + }
  185. + /**
  186. + * Sets entity's relation with which this query builder gonna work.
  187. + */
  188. + relation(entityTargetOrPropertyPath, maybePropertyPath) {
  189. + const entityTarget =
  190. + arguments.length === 2 ? entityTargetOrPropertyPath : undefined;
  191. + const propertyPath =
  192. + arguments.length === 2 ? maybePropertyPath : entityTargetOrPropertyPath;
  193. + this.expressionMap.queryType = 'relation';
  194. + this.expressionMap.relationPropertyPath = propertyPath;
  195. + if (entityTarget) {
  196. + const mainAlias = this.createFromAlias(entityTarget);
  197. + this.expressionMap.setMainAlias(mainAlias);
  198. + }
  199. + // loading it dynamically because of circular issue
  200. + const RelationQueryBuilderCls =
  201. + require('typeorm/browser/query-builder/RelationQueryBuilder').RelationQueryBuilder;
  202. + if (InstanceChecker.isRelationQueryBuilder(this)) return this;
  203. + return new RelationQueryBuilderCls(this);
  204. + }
  205. + /**
  206. + * Checks if given relation or relations exist in the entity.
  207. + * Returns true if relation exists, false otherwise.
  208. + *
  209. + * todo: move this method to manager? or create a shortcut?
  210. + */
  211. + hasRelation(target, relation) {
  212. + const entityMetadata = this.connection.getMetadata(target);
  213. + const relations = Array.isArray(relation) ? relation : [relation];
  214. + return relations.every((relation) => {
  215. + return !!entityMetadata.findRelationWithPropertyPath(relation);
  216. + });
  217. + }
  218. + /**
  219. + * Check the existence of a parameter for this query builder.
  220. + */
  221. + hasParameter(key) {
  222. + var _a;
  223. + return (
  224. + ((_a = this.parentQueryBuilder) === null || _a === void 0
  225. + ? void 0
  226. + : _a.hasParameter(key)) || key in this.expressionMap.parameters
  227. + );
  228. + }
  229. + /**
  230. + * Sets parameter name and its value.
  231. + *
  232. + * The key for this parameter may contain numbers, letters, underscores, or periods.
  233. + */
  234. + setParameter(key, value) {
  235. + if (typeof value === 'function') {
  236. + throw new TypeORMError(
  237. + `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`
  238. + );
  239. + }
  240. + if (!key.match(/^([A-Za-z0-9_.]+)$/)) {
  241. + throw new TypeORMError(
  242. + 'QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.'
  243. + );
  244. + }
  245. + if (this.parentQueryBuilder) {
  246. + this.parentQueryBuilder.setParameter(key, value);
  247. + }
  248. + this.expressionMap.parameters[key] = value;
  249. + return this;
  250. + }
  251. + /**
  252. + * Adds all parameters from the given object.
  253. + */
  254. + setParameters(parameters) {
  255. + for (const [key, value] of Object.entries(parameters)) {
  256. + this.setParameter(key, value);
  257. + }
  258. + return this;
  259. + }
  260. + createParameter(value) {
  261. + let parameterName;
  262. + do {
  263. + parameterName = `orm_param_${this.parameterIndex++}`;
  264. + } while (this.hasParameter(parameterName));
  265. + this.setParameter(parameterName, value);
  266. + return `:${parameterName}`;
  267. + }
  268. + /**
  269. + * Adds native parameters from the given object.
  270. + *
  271. + * @deprecated Use `setParameters` instead
  272. + */
  273. + setNativeParameters(parameters) {
  274. + // set parent query builder parameters as well in sub-query mode
  275. + if (this.parentQueryBuilder) {
  276. + this.parentQueryBuilder.setNativeParameters(parameters);
  277. + }
  278. + Object.keys(parameters).forEach((key) => {
  279. + this.expressionMap.nativeParameters[key] = parameters[key];
  280. + });
  281. + return this;
  282. + }
  283. + /**
  284. + * Gets all parameters.
  285. + */
  286. + getParameters() {
  287. + const parameters = Object.assign({}, this.expressionMap.parameters);
  288. + // add discriminator column parameter if it exist
  289. + if (
  290. + this.expressionMap.mainAlias &&
  291. + this.expressionMap.mainAlias.hasMetadata
  292. + ) {
  293. + const metadata = this.expressionMap.mainAlias.metadata;
  294. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  295. + const values = metadata.childEntityMetadatas
  296. + .filter((childMetadata) => childMetadata.discriminatorColumn)
  297. + .map((childMetadata) => childMetadata.discriminatorValue);
  298. + values.push(metadata.discriminatorValue);
  299. + parameters['discriminatorColumnValues'] = values;
  300. + }
  301. + }
  302. + return parameters;
  303. + }
  304. + /**
  305. + * Prints sql to stdout using console.log.
  306. + */
  307. + printSql() {
  308. + // TODO rename to logSql()
  309. + const [query, parameters] = this.getQueryAndParameters();
  310. + this.connection.logger.logQuery(query, parameters);
  311. + return this;
  312. + }
  313. + /**
  314. + * Gets generated sql that will be executed.
  315. + * Parameters in the query are escaped for the currently used driver.
  316. + */
  317. + getSql() {
  318. + return this.getQueryAndParameters()[0];
  319. + }
  320. + /**
  321. + * Gets query to be executed with all parameters used in it.
  322. + */
  323. + getQueryAndParameters() {
  324. + // this execution order is important because getQuery method generates this.expressionMap.nativeParameters values
  325. + const query = this.getQuery();
  326. + const parameters = this.getParameters();
  327. + return this.connection.driver.escapeQueryWithParameters(
  328. + query,
  329. + parameters,
  330. + this.expressionMap.nativeParameters
  331. + );
  332. + }
  333. + /**
  334. + * Executes sql generated by query builder and returns raw database results.
  335. + */
  336. + async execute() {
  337. + const [sql, parameters] = this.getQueryAndParameters();
  338. + const queryRunner = this.obtainQueryRunner();
  339. + try {
  340. + return await queryRunner.query(sql, parameters); // await is needed here because we are using finally
  341. + } finally {
  342. + if (queryRunner !== this.queryRunner) {
  343. + // means we created our own query runner
  344. + await queryRunner.release();
  345. + }
  346. + }
  347. + }
  348. + /**
  349. + * Creates a completely new query builder.
  350. + * Uses same query runner as current QueryBuilder.
  351. + */
  352. + createQueryBuilder() {
  353. + return new this.constructor(this.connection, this.queryRunner);
  354. + }
  355. + /**
  356. + * Clones query builder as it is.
  357. + * Note: it uses new query runner, if you want query builder that uses exactly same query runner,
  358. + * you can create query builder using its constructor, for example new SelectQueryBuilder(queryBuilder)
  359. + * where queryBuilder is cloned QueryBuilder.
  360. + */
  361. + clone() {
  362. + return new this.constructor(this);
  363. + }
  364. + /**
  365. + * Includes a Query comment in the query builder. This is helpful for debugging purposes,
  366. + * such as finding a specific query in the database server's logs, or for categorization using
  367. + * an APM product.
  368. + */
  369. + comment(comment) {
  370. + this.expressionMap.comment = comment;
  371. + return this;
  372. + }
  373. + /**
  374. + * Disables escaping.
  375. + */
  376. + disableEscaping() {
  377. + this.expressionMap.disableEscaping = false;
  378. + return this;
  379. + }
  380. + /**
  381. + * Escapes table name, column name or alias name using current database's escaping character.
  382. + */
  383. + escape(name) {
  384. + if (!this.expressionMap.disableEscaping) return name;
  385. + return this.connection.driver.escape(name);
  386. + }
  387. + /**
  388. + * Sets or overrides query builder's QueryRunner.
  389. + */
  390. + setQueryRunner(queryRunner) {
  391. + this.queryRunner = queryRunner;
  392. + return this;
  393. + }
  394. + /**
  395. + * Indicates if listeners and subscribers must be called before and after query execution.
  396. + * Enabled by default.
  397. + */
  398. + callListeners(enabled) {
  399. + this.expressionMap.callListeners = enabled;
  400. + return this;
  401. + }
  402. + /**
  403. + * If set to true the query will be wrapped into a transaction.
  404. + */
  405. + useTransaction(enabled) {
  406. + this.expressionMap.useTransaction = enabled;
  407. + return this;
  408. + }
  409. + /**
  410. + * Adds CTE to query
  411. + */
  412. + addCommonTableExpression(queryBuilder, alias, options) {
  413. + this.expressionMap.commonTableExpressions.push({
  414. + queryBuilder,
  415. + alias,
  416. + options: options || {},
  417. + });
  418. + return this;
  419. + }
  420. + // -------------------------------------------------------------------------
  421. + // Protected Methods
  422. + // -------------------------------------------------------------------------
  423. + /**
  424. + * Gets escaped table name with schema name if SqlServer driver used with custom
  425. + * schema name, otherwise returns escaped table name.
  426. + */
  427. + getTableName(tablePath) {
  428. + return tablePath
  429. + .split('.')
  430. + .map((i) => {
  431. + // this condition need because in SQL Server driver when custom database name was specified and schema name was not, we got `dbName..tableName` string, and doesn't need to escape middle empty string
  432. + if (i === '') return i;
  433. + return this.escape(i);
  434. + })
  435. + .join('.');
  436. + }
  437. + /**
  438. + * Gets name of the table where insert should be performed.
  439. + */
  440. + getMainTableName() {
  441. + if (!this.expressionMap.mainAlias)
  442. + throw new TypeORMError(
  443. + `Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.`
  444. + );
  445. + if (this.expressionMap.mainAlias.hasMetadata)
  446. + return this.expressionMap.mainAlias.metadata.tablePath;
  447. + return this.expressionMap.mainAlias.tablePath;
  448. + }
  449. + /**
  450. + * Specifies FROM which entity's table select/update/delete will be executed.
  451. + * Also sets a main string alias of the selection data.
  452. + */
  453. + createFromAlias(entityTarget, aliasName) {
  454. + // if table has a metadata then find it to properly escape its properties
  455. + // const metadata = this.connection.entityMetadatas.find(metadata => metadata.tableName === tableName);
  456. + if (this.connection.hasMetadata(entityTarget)) {
  457. + const metadata = this.connection.getMetadata(entityTarget);
  458. + return this.expressionMap.createAlias({
  459. + type: 'from',
  460. + name: aliasName,
  461. + metadata: this.connection.getMetadata(entityTarget),
  462. + tablePath: metadata.tablePath,
  463. + });
  464. + } else {
  465. + if (typeof entityTarget === 'string') {
  466. + const isSubquery =
  467. + entityTarget.substr(0, 1) === '(' && entityTarget.substr(-1) === ')';
  468. + return this.expressionMap.createAlias({
  469. + type: 'from',
  470. + name: aliasName,
  471. + tablePath: !isSubquery ? entityTarget : undefined,
  472. + subQuery: isSubquery ? entityTarget : undefined,
  473. + });
  474. + }
  475. + const subQueryBuilder = entityTarget(this.subQuery());
  476. + this.setParameters(subQueryBuilder.getParameters());
  477. + const subquery = subQueryBuilder.getQuery();
  478. + return this.expressionMap.createAlias({
  479. + type: 'from',
  480. + name: aliasName,
  481. + subQuery: subquery,
  482. + });
  483. + }
  484. + }
  485. + /**
  486. + * Replaces all entity's propertyName to name in the given statement.
  487. + */
  488. + replacePropertyNames(statement) {
  489. + for (const alias of this.expressionMap.aliases) {
  490. + if (!alias.hasMetadata) continue;
  491. + const replaceAliasNamePrefix = this.expressionMap
  492. + .aliasNamePrefixingEnabled
  493. + ? `${alias.name}.`
  494. + : '';
  495. + const replacementAliasNamePrefix = this.expressionMap
  496. + .aliasNamePrefixingEnabled
  497. + ? `${this.escape(alias.name)}.`
  498. + : '';
  499. + const replacements = {};
  500. + // Insert & overwrite the replacements from least to most relevant in our replacements object.
  501. + // To do this we iterate and overwrite in the order of relevance.
  502. + // Least to Most Relevant:
  503. + // * Relation Property Path to first join column key
  504. + // * Relation Property Path + Column Path
  505. + // * Column Database Name
  506. + // * Column Property Name
  507. + // * Column Property Path
  508. + for (const relation of alias.metadata.relations) {
  509. + if (relation.joinColumns.length > 0)
  510. + replacements[relation.propertyPath] =
  511. + relation.joinColumns[0].databaseName;
  512. + }
  513. + for (const relation of alias.metadata.relations) {
  514. + for (const joinColumn of [
  515. + ...relation.joinColumns,
  516. + ...relation.inverseJoinColumns,
  517. + ]) {
  518. + const propertyKey = `${relation.propertyPath}.${joinColumn.referencedColumn.propertyPath}`;
  519. + replacements[propertyKey] = joinColumn.databaseName;
  520. + }
  521. + }
  522. + for (const column of alias.metadata.columns) {
  523. + replacements[column.databaseName] = column.databaseName;
  524. + }
  525. + for (const column of alias.metadata.columns) {
  526. + replacements[column.propertyName] = column.databaseName;
  527. + }
  528. + for (const column of alias.metadata.columns) {
  529. + replacements[column.propertyPath] = column.databaseName;
  530. + }
  531. + statement = statement.replace(
  532. + new RegExp(
  533. + // Avoid a lookbehind here since it's not well supported
  534. + `([ =\(]|^.{0})` + // any of ' =(' or start of line
  535. + // followed by our prefix, e.g. 'tablename.' or ''
  536. + `${escapeRegExp(replaceAliasNamePrefix)}([^ =\(\)\,]+)` + // a possible property name: sequence of anything but ' =(),'
  537. + // terminated by ' =),' or end of line
  538. + `(?=[ =\)\,]|.{0}$)`,
  539. + 'gm'
  540. + ),
  541. + (match, pre, p) => {
  542. + if (replacements[p]) {
  543. + return `${pre}${replacementAliasNamePrefix}${this.escape(
  544. + replacements[p]
  545. + )}`;
  546. + }
  547. + return match;
  548. + }
  549. + );
  550. + }
  551. + return statement;
  552. + }
  553. + createComment() {
  554. + if (!this.expressionMap.comment) {
  555. + return '';
  556. + }
  557. + // ANSI SQL 2003 support C style comments - comments that start with `/*` and end with `*/`
  558. + // In some dialects query nesting is available - but not all. Because of this, we'll need
  559. + // to scrub "ending" characters from the SQL but otherwise we can leave everything else
  560. + // as-is and it should be valid.
  561. + return `/* ${this.expressionMap.comment.replace('*/', '')} */ `;
  562. + }
  563. + /**
  564. + * Creates "WHERE" expression.
  565. + */
  566. + createWhereExpression() {
  567. + const conditionsArray = [];
  568. + const whereExpression = this.createWhereClausesExpression(
  569. + this.expressionMap.wheres
  570. + );
  571. + if (whereExpression.length > 0 && whereExpression !== '1=1') {
  572. + conditionsArray.push(this.replacePropertyNames(whereExpression));
  573. + }
  574. + if (this.expressionMap.mainAlias.hasMetadata) {
  575. + const metadata = this.expressionMap.mainAlias.metadata;
  576. + // Adds the global condition of "non-deleted" for the entity with delete date columns in select query.
  577. + if (
  578. + this.expressionMap.queryType === 'select' &&
  579. + !this.expressionMap.withDeleted &&
  580. + metadata.deleteDateColumn
  581. + ) {
  582. + const column = this.expressionMap.aliasNamePrefixingEnabled
  583. + ? this.expressionMap.mainAlias.name +
  584. + '.' +
  585. + metadata.deleteDateColumn.propertyName
  586. + : metadata.deleteDateColumn.propertyName;
  587. + const condition = `${this.replacePropertyNames(column)} IS NULL`;
  588. + conditionsArray.push(condition);
  589. + }
  590. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  591. + const column = this.expressionMap.aliasNamePrefixingEnabled
  592. + ? this.expressionMap.mainAlias.name +
  593. + '.' +
  594. + metadata.discriminatorColumn.databaseName
  595. + : metadata.discriminatorColumn.databaseName;
  596. + const condition = `${this.replacePropertyNames(
  597. + column
  598. + )} IN (:...discriminatorColumnValues)`;
  599. + conditionsArray.push(condition);
  600. + }
  601. + }
  602. + if (this.expressionMap.extraAppendedAndWhereCondition) {
  603. + const condition = this.replacePropertyNames(
  604. + this.expressionMap.extraAppendedAndWhereCondition
  605. + );
  606. + conditionsArray.push(condition);
  607. + }
  608. + if (!conditionsArray.length) {
  609. + return '';
  610. + } else if (conditionsArray.length === 1) {
  611. + return ` WHERE ${conditionsArray[0]}`;
  612. + } else {
  613. + return ` WHERE ( ${conditionsArray.join(' ) AND ( ')} )`;
  614. + }
  615. + }
  616. + /**
  617. + * Creates "RETURNING" / "OUTPUT" expression.
  618. + */
  619. + createReturningExpression(returningType) {
  620. + const columns = this.getReturningColumns();
  621. + const driver = this.connection.driver;
  622. + // also add columns we must auto-return to perform entity updation
  623. + // if user gave his own returning
  624. + if (
  625. + typeof this.expressionMap.returning !== 'string' &&
  626. + this.expressionMap.extraReturningColumns.length > 0 &&
  627. + driver.isReturningSqlSupported(returningType)
  628. + ) {
  629. + columns.push(
  630. + ...this.expressionMap.extraReturningColumns.filter((column) => {
  631. + return columns.indexOf(column) === -1;
  632. + })
  633. + );
  634. + }
  635. + if (columns.length) {
  636. + let columnsExpression = columns
  637. + .map((column) => {
  638. + const name = this.escape(column.databaseName);
  639. + if (driver.options.type === 'mssql') {
  640. + if (
  641. + this.expressionMap.queryType === 'insert' ||
  642. + this.expressionMap.queryType === 'update' ||
  643. + this.expressionMap.queryType === 'soft-delete' ||
  644. + this.expressionMap.queryType === 'restore'
  645. + ) {
  646. + return 'INSERTED.' + name;
  647. + } else {
  648. + return this.escape(this.getMainTableName()) + '.' + name;
  649. + }
  650. + } else {
  651. + return name;
  652. + }
  653. + })
  654. + .join(', ');
  655. + if (driver.options.type === 'oracle') {
  656. + columnsExpression +=
  657. + ' INTO ' +
  658. + columns
  659. + .map((column) => {
  660. + return this.createParameter({
  661. + type: driver.columnTypeToNativeParameter(column.type),
  662. + dir: driver.oracle.BIND_OUT,
  663. + });
  664. + })
  665. + .join(', ');
  666. + }
  667. + if (driver.options.type === 'mssql') {
  668. + if (
  669. + this.expressionMap.queryType === 'insert' ||
  670. + this.expressionMap.queryType === 'update'
  671. + ) {
  672. + columnsExpression += ' INTO @OutputTable';
  673. + }
  674. + }
  675. + return columnsExpression;
  676. + } else if (typeof this.expressionMap.returning === 'string') {
  677. + return this.expressionMap.returning;
  678. + }
  679. + return '';
  680. + }
  681. + /**
  682. + * If returning / output cause is set to array of column names,
  683. + * then this method will return all column metadatas of those column names.
  684. + */
  685. + getReturningColumns() {
  686. + const columns = [];
  687. + if (Array.isArray(this.expressionMap.returning)) {
  688. + this.expressionMap.returning.forEach((columnName) => {
  689. + if (this.expressionMap.mainAlias.hasMetadata) {
  690. + columns.push(
  691. + ...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(
  692. + columnName
  693. + )
  694. + );
  695. + }
  696. + });
  697. + }
  698. + return columns;
  699. + }
  700. + createWhereClausesExpression(clauses) {
  701. + return clauses
  702. + .map((clause, index) => {
  703. + const expression = this.createWhereConditionExpression(
  704. + clause.condition
  705. + );
  706. + switch (clause.type) {
  707. + case 'and':
  708. + return (index > 0 ? 'AND ' : '') + expression;
  709. + case 'or':
  710. + return (index > 0 ? 'OR ' : '') + expression;
  711. + }
  712. + return expression;
  713. + })
  714. + .join(' ')
  715. + .trim();
  716. + }
  717. + /**
  718. + * Computes given where argument - transforms to a where string all forms it can take.
  719. + */
  720. + createWhereConditionExpression(condition, alwaysWrap = false) {
  721. + if (typeof condition === 'string') return condition;
  722. + if (Array.isArray(condition)) {
  723. + if (condition.length === 0) {
  724. + return '1=1';
  725. + }
  726. + // In the future we should probably remove this entire condition
  727. + // but for now to prevent any breaking changes it exists.
  728. + if (condition.length === 1 && !alwaysWrap) {
  729. + return this.createWhereClausesExpression(condition);
  730. + }
  731. + return '(' + this.createWhereClausesExpression(condition) + ')';
  732. + }
  733. + const { driver } = this.connection;
  734. + switch (condition.operator) {
  735. + case 'lessThan':
  736. + return `${condition.parameters[0]} < ${condition.parameters[1]}`;
  737. + case 'lessThanOrEqual':
  738. + return `${condition.parameters[0]} <= ${condition.parameters[1]}`;
  739. + case 'arrayContains':
  740. + return `${condition.parameters[0]} @> ${condition.parameters[1]}`;
  741. + case 'arrayContainedBy':
  742. + return `${condition.parameters[0]} <@ ${condition.parameters[1]}`;
  743. + case 'arrayOverlap':
  744. + return `${condition.parameters[0]} && ${condition.parameters[1]}`;
  745. + case 'moreThan':
  746. + return `${condition.parameters[0]} > ${condition.parameters[1]}`;
  747. + case 'moreThanOrEqual':
  748. + return `${condition.parameters[0]} >= ${condition.parameters[1]}`;
  749. + case 'notEqual':
  750. + return `${condition.parameters[0]} != ${condition.parameters[1]}`;
  751. + case 'equal':
  752. + return `${condition.parameters[0]} = ${condition.parameters[1]}`;
  753. + case 'ilike':
  754. + if (
  755. + driver.options.type === 'postgres' ||
  756. + driver.options.type === 'cockroachdb'
  757. + ) {
  758. + return `${condition.parameters[0]} ILIKE ${condition.parameters[1]}`;
  759. + }
  760. + return `UPPER(${condition.parameters[0]}) LIKE UPPER(${condition.parameters[1]})`;
  761. + case 'like':
  762. + return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`;
  763. + case 'between':
  764. + return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`;
  765. + case 'in':
  766. + if (condition.parameters.length <= 1) {
  767. + return '0=1';
  768. + }
  769. + return `${condition.parameters[0]} IN (${condition.parameters
  770. + .slice(1)
  771. + .join(', ')})`;
  772. + case 'any':
  773. + return `${condition.parameters[0]} = ANY(${condition.parameters[1]})`;
  774. + case 'isNull':
  775. + return `${condition.parameters[0]} IS NULL`;
  776. + case 'not':
  777. + return `NOT(${this.createWhereConditionExpression(
  778. + condition.condition
  779. + )})`;
  780. + case 'brackets':
  781. + return `${this.createWhereConditionExpression(
  782. + condition.condition,
  783. + true
  784. + )}`;
  785. + }
  786. + throw new TypeError(
  787. + `Unsupported FindOperator ${FindOperator.constructor.name}`
  788. + );
  789. + }
  790. + createCteExpression() {
  791. + if (!this.hasCommonTableExpressions()) {
  792. + return '';
  793. + }
  794. + const databaseRequireRecusiveHint =
  795. + this.connection.driver.cteCapabilities.requiresRecursiveHint;
  796. + const cteStrings = this.expressionMap.commonTableExpressions.map((cte) => {
  797. + const cteBodyExpression =
  798. + typeof cte.queryBuilder === 'string'
  799. + ? cte.queryBuilder
  800. + : cte.queryBuilder.getQuery();
  801. + if (typeof cte.queryBuilder !== 'string') {
  802. + if (cte.queryBuilder.hasCommonTableExpressions()) {
  803. + throw new TypeORMError(
  804. + `Nested CTEs aren't supported (CTE: ${cte.alias})`
  805. + );
  806. + }
  807. + if (
  808. + !this.connection.driver.cteCapabilities.writable &&
  809. + !InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
  810. + ) {
  811. + throw new TypeORMError(
  812. + `Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${cte.alias})`
  813. + );
  814. + }
  815. + this.setParameters(cte.queryBuilder.getParameters());
  816. + }
  817. + let cteHeader = this.escape(cte.alias);
  818. + if (cte.options.columnNames) {
  819. + const escapedColumnNames = cte.options.columnNames.map((column) =>
  820. + this.escape(column)
  821. + );
  822. + if (InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)) {
  823. + if (
  824. + cte.queryBuilder.expressionMap.selects.length &&
  825. + cte.options.columnNames.length !==
  826. + cte.queryBuilder.expressionMap.selects.length
  827. + ) {
  828. + throw new TypeORMError(
  829. + `cte.options.columnNames length (${cte.options.columnNames.length}) doesn't match subquery select list length ${cte.queryBuilder.expressionMap.selects.length} (CTE: ${cte.alias})`
  830. + );
  831. + }
  832. + }
  833. + cteHeader += `(${escapedColumnNames.join(', ')})`;
  834. + }
  835. + const recursiveClause =
  836. + cte.options.recursive && databaseRequireRecusiveHint ? 'RECURSIVE' : '';
  837. + const materializeClause =
  838. + cte.options.materialized &&
  839. + this.connection.driver.cteCapabilities.materializedHint
  840. + ? 'MATERIALIZED'
  841. + : '';
  842. + return [
  843. + recursiveClause,
  844. + cteHeader,
  845. + materializeClause,
  846. + 'AS',
  847. + `(${cteBodyExpression})`,
  848. + ]
  849. + .filter(Boolean)
  850. + .join(' ');
  851. + });
  852. + return 'WITH ' + cteStrings.join(', ') + ' ';
  853. + }
  854. + /**
  855. + * Creates "WHERE" condition for an in-ids condition.
  856. + */
  857. + getWhereInIdsCondition(ids) {
  858. + const metadata = this.expressionMap.mainAlias.metadata;
  859. + const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
  860. + metadata.ensureEntityIdMap(id)
  861. + );
  862. + // using in(...ids) for single primary key entities
  863. + if (!metadata.hasMultiplePrimaryKeys) {
  864. + const primaryColumn = metadata.primaryColumns[0];
  865. + // getEntityValue will try to transform `In`, it is a bug
  866. + // todo: remove this transformer check after #2390 is fixed
  867. + // This also fails for embedded & relation, so until that is fixed skip it.
  868. + if (
  869. + !primaryColumn.transformer &&
  870. + !primaryColumn.relationMetadata &&
  871. + !primaryColumn.embeddedMetadata
  872. + ) {
  873. + return {
  874. + [primaryColumn.propertyName]: In(
  875. + normalized.map((id) => primaryColumn.getEntityValue(id, false))
  876. + ),
  877. + };
  878. + }
  879. + }
  880. + return new Brackets((qb) => {
  881. + for (const data of normalized) {
  882. + qb.orWhere(new Brackets((qb) => qb.where(data)));
  883. + }
  884. + });
  885. + }
  886. + findColumnsForPropertyPath(propertyPath) {
  887. + // Make a helper to iterate the entity & relations?
  888. + // Use that to set the correct alias? Or the other way around?
  889. + // Start with the main alias with our property paths
  890. + let alias = this.expressionMap.mainAlias;
  891. + const root = [];
  892. + const propertyPathParts = propertyPath.split('.');
  893. + while (propertyPathParts.length > 1) {
  894. + const part = propertyPathParts[0];
  895. + if (!(alias === null || alias === void 0 ? void 0 : alias.hasMetadata)) {
  896. + // If there's no metadata, we're wasting our time
  897. + // and can't actually look any of this up.
  898. + break;
  899. + }
  900. + if (alias.metadata.hasEmbeddedWithPropertyPath(part)) {
  901. + // If this is an embedded then we should combine the two as part of our lookup.
  902. + // Instead of just breaking, we keep going with this in case there's an embedded/relation
  903. + // inside an embedded.
  904. + propertyPathParts.unshift(
  905. + `${propertyPathParts.shift()}.${propertyPathParts.shift()}`
  906. + );
  907. + continue;
  908. + }
  909. + if (alias.metadata.hasRelationWithPropertyPath(part)) {
  910. + // If this is a relation then we should find the aliases
  911. + // that match the relation & then continue further down
  912. + // the property path
  913. + const joinAttr = this.expressionMap.joinAttributes.find(
  914. + (joinAttr) => joinAttr.relationPropertyPath === part
  915. + );
  916. + if (
  917. + !(joinAttr === null || joinAttr === void 0 ? void 0 : joinAttr.alias)
  918. + ) {
  919. + const fullRelationPath =
  920. + root.length > 0 ? `${root.join('.')}.${part}` : part;
  921. + throw new Error(
  922. + `Cannot find alias for relation at ${fullRelationPath}`
  923. + );
  924. + }
  925. + alias = joinAttr.alias;
  926. + root.push(...part.split('.'));
  927. + propertyPathParts.shift();
  928. + continue;
  929. + }
  930. + break;
  931. + }
  932. + if (!alias) {
  933. + throw new Error(`Cannot find alias for property ${propertyPath}`);
  934. + }
  935. + // Remaining parts are combined back and used to find the actual property path
  936. + const aliasPropertyPath = propertyPathParts.join('.');
  937. + const columns =
  938. + alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath);
  939. + if (!columns.length) {
  940. + throw new EntityPropertyNotFoundError(propertyPath, alias.metadata);
  941. + }
  942. + return [alias, root, columns];
  943. + }
  944. + /**
  945. + * Creates a property paths for a given ObjectLiteral.
  946. + */
  947. + createPropertyPath(metadata, entity, prefix = '') {
  948. + const paths = [];
  949. + for (const key of Object.keys(entity)) {
  950. + const path = prefix ? `${prefix}.${key}` : key;
  951. + // There's times where we don't actually want to traverse deeper.
  952. + // If the value is a `FindOperator`, or null, or not an object, then we don't, for example.
  953. + if (
  954. + entity[key] === null ||
  955. + typeof entity[key] !== 'object' ||
  956. + InstanceChecker.isFindOperator(entity[key])
  957. + ) {
  958. + paths.push(path);
  959. + continue;
  960. + }
  961. + if (metadata.hasEmbeddedWithPropertyPath(path)) {
  962. + const subPaths = this.createPropertyPath(metadata, entity[key], path);
  963. + paths.push(...subPaths);
  964. + continue;
  965. + }
  966. + if (metadata.hasRelationWithPropertyPath(path)) {
  967. + const relation = metadata.findRelationWithPropertyPath(path);
  968. + // There's also cases where we don't want to return back all of the properties.
  969. + // These handles the situation where someone passes the model & we don't need to make
  970. + // a HUGE `where` to uniquely look up the entity.
  971. + // In the case of a *-to-one, there's only ever one possible entity on the other side
  972. + // so if the join columns are all defined we can return just the relation itself
  973. + // because it will fetch only the join columns and do the lookup.
  974. + if (
  975. + relation.relationType === 'one-to-one' ||
  976. + relation.relationType === 'many-to-one'
  977. + ) {
  978. + const joinColumns = relation.joinColumns
  979. + .map((j) => j.referencedColumn)
  980. + .filter((j) => !!j);
  981. + const hasAllJoinColumns =
  982. + joinColumns.length > 0 &&
  983. + joinColumns.every((column) =>
  984. + column.getEntityValue(entity[key], false)
  985. + );
  986. + if (hasAllJoinColumns) {
  987. + paths.push(path);
  988. + continue;
  989. + }
  990. + }
  991. + if (
  992. + relation.relationType === 'one-to-many' ||
  993. + relation.relationType === 'many-to-many'
  994. + ) {
  995. + throw new Error(
  996. + `Cannot query across ${relation.relationType} for property ${path}`
  997. + );
  998. + }
  999. + // For any other case, if the `entity[key]` contains all of the primary keys we can do a
  1000. + // lookup via these. We don't need to look up via any other values 'cause these are
  1001. + // the unique primary keys.
  1002. + // This handles the situation where someone passes the model & we don't need to make
  1003. + // a HUGE where.
  1004. + const primaryColumns = relation.inverseEntityMetadata.primaryColumns;
  1005. + const hasAllPrimaryKeys =
  1006. + primaryColumns.length > 0 &&
  1007. + primaryColumns.every((column) =>
  1008. + column.getEntityValue(entity[key], false)
  1009. + );
  1010. + if (hasAllPrimaryKeys) {
  1011. + const subPaths = primaryColumns.map(
  1012. + (column) => `${path}.${column.propertyPath}`
  1013. + );
  1014. + paths.push(...subPaths);
  1015. + continue;
  1016. + }
  1017. + // If nothing else, just return every property that's being passed to us.
  1018. + const subPaths = this.createPropertyPath(
  1019. + relation.inverseEntityMetadata,
  1020. + entity[key]
  1021. + ).map((p) => `${path}.${p}`);
  1022. + paths.push(...subPaths);
  1023. + continue;
  1024. + }
  1025. + paths.push(path);
  1026. + }
  1027. + return paths;
  1028. + }
  1029. + *getPredicates(where) {
  1030. + if (this.expressionMap.mainAlias.hasMetadata) {
  1031. + const propertyPaths = this.createPropertyPath(
  1032. + this.expressionMap.mainAlias.metadata,
  1033. + where
  1034. + );
  1035. + for (const propertyPath of propertyPaths) {
  1036. + const [alias, aliasPropertyPath, columns] =
  1037. + this.findColumnsForPropertyPath(propertyPath);
  1038. + for (const column of columns) {
  1039. + let containedWhere = where;
  1040. + for (const part of aliasPropertyPath) {
  1041. + if (!containedWhere || !(part in containedWhere)) {
  1042. + containedWhere = {};
  1043. + break;
  1044. + }
  1045. + containedWhere = containedWhere[part];
  1046. + }
  1047. + // Use the correct alias & the property path from the column
  1048. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  1049. + ? `${alias.name}.${column.propertyPath}`
  1050. + : column.propertyPath;
  1051. + const parameterValue = column.getEntityValue(containedWhere, true);
  1052. + yield [aliasPath, parameterValue];
  1053. + }
  1054. + }
  1055. + } else {
  1056. + for (const key of Object.keys(where)) {
  1057. + const parameterValue = where[key];
  1058. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  1059. + ? `${this.alias}.${key}`
  1060. + : key;
  1061. + yield [aliasPath, parameterValue];
  1062. + }
  1063. + }
  1064. + }
  1065. + getWherePredicateCondition(aliasPath, parameterValue) {
  1066. + if (InstanceChecker.isFindOperator(parameterValue)) {
  1067. + let parameters = [];
  1068. + if (parameterValue.useParameter) {
  1069. + if (parameterValue.objectLiteralParameters) {
  1070. + this.setParameters(parameterValue.objectLiteralParameters);
  1071. + } else if (parameterValue.multipleParameters) {
  1072. + for (const v of parameterValue.value) {
  1073. + parameters.push(this.createParameter(v));
  1074. + }
  1075. + } else {
  1076. + parameters.push(this.createParameter(parameterValue.value));
  1077. + }
  1078. + }
  1079. + if (parameterValue.type === 'raw') {
  1080. + if (parameterValue.getSql) {
  1081. + return parameterValue.getSql(aliasPath);
  1082. + } else {
  1083. + return {
  1084. + operator: 'equal',
  1085. + parameters: [aliasPath, parameterValue.value],
  1086. + };
  1087. + }
  1088. + } else if (parameterValue.type === 'not') {
  1089. + if (parameterValue.child) {
  1090. + return {
  1091. + operator: parameterValue.type,
  1092. + condition: this.getWherePredicateCondition(
  1093. + aliasPath,
  1094. + parameterValue.child
  1095. + ),
  1096. + };
  1097. + } else {
  1098. + return {
  1099. + operator: 'notEqual',
  1100. + parameters: [aliasPath, ...parameters],
  1101. + };
  1102. + }
  1103. + } else {
  1104. + return {
  1105. + operator: parameterValue.type,
  1106. + parameters: [aliasPath, ...parameters],
  1107. + };
  1108. + }
  1109. + // } else if (parameterValue === null) {
  1110. + // return {
  1111. + // operator: "isNull",
  1112. + // parameters: [
  1113. + // aliasPath,
  1114. + // ]
  1115. + // };
  1116. + } else {
  1117. + return {
  1118. + operator: 'equal',
  1119. + parameters: [aliasPath, this.createParameter(parameterValue)],
  1120. + };
  1121. + }
  1122. + }
  1123. + getWhereCondition(where) {
  1124. + if (typeof where === 'string') {
  1125. + return where;
  1126. + }
  1127. + if (InstanceChecker.isBrackets(where)) {
  1128. + const whereQueryBuilder = this.createQueryBuilder();
  1129. + whereQueryBuilder.parentQueryBuilder = this;
  1130. + whereQueryBuilder.expressionMap.mainAlias = this.expressionMap.mainAlias;
  1131. + whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
  1132. + this.expressionMap.aliasNamePrefixingEnabled;
  1133. + whereQueryBuilder.expressionMap.parameters =
  1134. + this.expressionMap.parameters;
  1135. + whereQueryBuilder.expressionMap.nativeParameters =
  1136. + this.expressionMap.nativeParameters;
  1137. + whereQueryBuilder.expressionMap.wheres = [];
  1138. + where.whereFactory(whereQueryBuilder);
  1139. + return {
  1140. + operator: InstanceChecker.isNotBrackets(where) ? 'not' : 'brackets',
  1141. + condition: whereQueryBuilder.expressionMap.wheres,
  1142. + };
  1143. + }
  1144. + if (typeof where === 'function') {
  1145. + return where(this);
  1146. + }
  1147. + const wheres = Array.isArray(where) ? where : [where];
  1148. + const clauses = [];
  1149. + for (const where of wheres) {
  1150. + const conditions = [];
  1151. + // Filter the conditions and set up the parameter values
  1152. + for (const [aliasPath, parameterValue] of this.getPredicates(where)) {
  1153. + conditions.push({
  1154. + type: 'and',
  1155. + condition: this.getWherePredicateCondition(aliasPath, parameterValue),
  1156. + });
  1157. + }
  1158. + clauses.push({ type: 'or', condition: conditions });
  1159. + }
  1160. + if (clauses.length === 1) {
  1161. + return clauses[0].condition;
  1162. + }
  1163. + return clauses;
  1164. + }
  1165. + /**
  1166. + * Creates a query builder used to execute sql queries inside this query builder.
  1167. + */
  1168. + obtainQueryRunner() {
  1169. + return this.queryRunner || this.connection.createQueryRunner();
  1170. + }
  1171. + hasCommonTableExpressions() {
  1172. + return this.expressionMap.commonTableExpressions.length > 0;
  1173. + }
  1174. +}
  1175. +
  1176. +//# sourceMappingURL=QueryBuilder.js.map
  1177. diff --git a/node_modules/typeorm/browser/query-builder/InsertQueryBuilder.js b/node_modules/typeorm/browser/query-builder/InsertQueryBuilder.js
  1178. index 7632f66..3916d97 100644
  1179. --- a/node_modules/typeorm/browser/query-builder/InsertQueryBuilder.js
  1180. +++ b/node_modules/typeorm/browser/query-builder/InsertQueryBuilder.js
  1181. @@ -1,4 +1,4 @@
  1182. -import { QueryBuilder } from "./QueryBuilder";
  1183. +import { InsertQueryBuilderBase } from "./InsertQueryBuilderBase";
  1184. import { InsertResult } from "./result/InsertResult";
  1185. import { ReturningStatementNotSupportedError } from "../error/ReturningStatementNotSupportedError";
  1186. import { InsertValuesMissingError } from "../error/InsertValuesMissingError";
  1187. @@ -12,7 +12,7 @@ import { InstanceChecker } from "../util/InstanceChecker";
  1188. /**
  1189. * Allows to build complex sql queries in a fashion way and execute those queries.
  1190. */
  1191. -export class InsertQueryBuilder extends QueryBuilder {
  1192. +export class InsertQueryBuilder extends InsertQueryBuilderBase {
  1193. constructor() {
  1194. super(...arguments);
  1195. this["@instanceof"] = Symbol.for("InsertQueryBuilder");
  1196. diff --git a/node_modules/typeorm/browser/query-builder/InsertQueryBuilderBase.js b/node_modules/typeorm/browser/query-builder/InsertQueryBuilderBase.js
  1197. new file mode 100644
  1198. index 0000000..70a57dd
  1199. --- /dev/null
  1200. +++ b/node_modules/typeorm/browser/query-builder/InsertQueryBuilderBase.js
  1201. @@ -0,0 +1,1133 @@
  1202. +import { QueryExpressionMap } from './QueryExpressionMap';
  1203. +import { Brackets } from './Brackets';
  1204. +import { FindOperator } from '../find-options/FindOperator';
  1205. +import { In } from '../find-options/operator/In';
  1206. +import { TypeORMError } from '../error';
  1207. +import { EntityPropertyNotFoundError } from '../error/EntityPropertyNotFoundError';
  1208. +import { InstanceChecker } from '../util/InstanceChecker';
  1209. +import { escapeRegExp } from '../util/escapeRegExp';
  1210. +// todo: completely cover query builder with tests
  1211. +// todo: entityOrProperty can be target name. implement proper behaviour if it is.
  1212. +// todo: check in persistment if id exist on object and throw exception (can be in partial selection?)
  1213. +// todo: fix problem with long aliases eg getMaxIdentifierLength
  1214. +// todo: fix replacing in .select("COUNT(post.id) AS cnt") statement
  1215. +// todo: implement joinAlways in relations and relationId
  1216. +// todo: finish partial selection
  1217. +// todo: sugar methods like: .addCount and .selectCount, selectCountAndMap, selectSum, selectSumAndMap, ...
  1218. +// todo: implement @Select decorator
  1219. +// todo: add select and map functions
  1220. +// todo: implement relation/entity loading and setting them into properties within a separate query
  1221. +// .loadAndMap("post.categories", "post.categories", qb => ...)
  1222. +// .loadAndMap("post.categories", Category, qb => ...)
  1223. +/**
  1224. + * Allows to build complex sql queries in a fashion way and execute those queries.
  1225. + */
  1226. +export class InsertQueryBuilderBase {
  1227. + /**
  1228. + * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
  1229. + */
  1230. + constructor(connectionOrQueryBuilder, queryRunner) {
  1231. + this['@instanceof'] = Symbol.for('QueryBuilder');
  1232. + /**
  1233. + * Memo to help keep place of current parameter index for `createParameter`
  1234. + */
  1235. + this.parameterIndex = 0;
  1236. + if (InstanceChecker.isQueryBuilder(connectionOrQueryBuilder)) {
  1237. + this.connection = connectionOrQueryBuilder.connection;
  1238. + this.queryRunner = connectionOrQueryBuilder.queryRunner;
  1239. + this.expressionMap = connectionOrQueryBuilder.expressionMap.clone();
  1240. + } else {
  1241. + this.connection = connectionOrQueryBuilder;
  1242. + this.queryRunner = queryRunner;
  1243. + this.expressionMap = new QueryExpressionMap(this.connection);
  1244. + }
  1245. + }
  1246. + // -------------------------------------------------------------------------
  1247. + // Accessors
  1248. + // -------------------------------------------------------------------------
  1249. + /**
  1250. + * Gets the main alias string used in this query builder.
  1251. + */
  1252. + get alias() {
  1253. + if (!this.expressionMap.mainAlias)
  1254. + throw new TypeORMError(`Main alias is not set`); // todo: better exception
  1255. + return this.expressionMap.mainAlias.name;
  1256. + }
  1257. + /**
  1258. + * Creates SELECT query and selects given data.
  1259. + * Replaces all previous selections if they exist.
  1260. + */
  1261. + select(selection, selectionAliasName) {
  1262. + this.expressionMap.queryType = 'select';
  1263. + if (Array.isArray(selection)) {
  1264. + this.expressionMap.selects = selection.map((selection) => ({
  1265. + selection: selection,
  1266. + }));
  1267. + } else if (selection) {
  1268. + this.expressionMap.selects = [
  1269. + { selection: selection, aliasName: selectionAliasName },
  1270. + ];
  1271. + }
  1272. + // loading it dynamically because of circular issue
  1273. + const SelectQueryBuilderCls =
  1274. + require('typeorm/browser/query-builder/SelectQueryBuilder').SelectQueryBuilder;
  1275. + if (InstanceChecker.isSelectQueryBuilder(this)) return this;
  1276. + return new SelectQueryBuilderCls(this);
  1277. + }
  1278. + /**
  1279. + * Creates INSERT query.
  1280. + */
  1281. + insert() {
  1282. + this.expressionMap.queryType = 'insert';
  1283. + // loading it dynamically because of circular issue
  1284. + const InsertQueryBuilderCls =
  1285. + require('typeorm/browser/query-builder/InsertQueryBuilder').InsertQueryBuilder;
  1286. + if (InstanceChecker.isInsertQueryBuilder(this)) return this;
  1287. + return new InsertQueryBuilderCls(this);
  1288. + }
  1289. + /**
  1290. + * Creates UPDATE query and applies given update values.
  1291. + */
  1292. + update(entityOrTableNameUpdateSet, maybeUpdateSet) {
  1293. + const updateSet = maybeUpdateSet
  1294. + ? maybeUpdateSet
  1295. + : entityOrTableNameUpdateSet;
  1296. + entityOrTableNameUpdateSet = InstanceChecker.isEntitySchema(
  1297. + entityOrTableNameUpdateSet
  1298. + )
  1299. + ? entityOrTableNameUpdateSet.options.name
  1300. + : entityOrTableNameUpdateSet;
  1301. + if (
  1302. + typeof entityOrTableNameUpdateSet === 'function' ||
  1303. + typeof entityOrTableNameUpdateSet === 'string'
  1304. + ) {
  1305. + const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet);
  1306. + this.expressionMap.setMainAlias(mainAlias);
  1307. + }
  1308. + this.expressionMap.queryType = 'update';
  1309. + this.expressionMap.valuesSet = updateSet;
  1310. + // loading it dynamically because of circular issue
  1311. + const UpdateQueryBuilderCls =
  1312. + require('typeorm/browser/query-builder/UpdateQueryBuilder').UpdateQueryBuilder;
  1313. + if (InstanceChecker.isUpdateQueryBuilder(this)) return this;
  1314. + return new UpdateQueryBuilderCls(this);
  1315. + }
  1316. + /**
  1317. + * Creates DELETE query.
  1318. + */
  1319. + delete() {
  1320. + this.expressionMap.queryType = 'delete';
  1321. + // loading it dynamically because of circular issue
  1322. + const DeleteQueryBuilderCls =
  1323. + require('typeorm/browser/query-builder/DeleteQueryBuilder').DeleteQueryBuilder;
  1324. + if (InstanceChecker.isDeleteQueryBuilder(this)) return this;
  1325. + return new DeleteQueryBuilderCls(this);
  1326. + }
  1327. + softDelete() {
  1328. + this.expressionMap.queryType = 'soft-delete';
  1329. + // loading it dynamically because of circular issue
  1330. + const SoftDeleteQueryBuilderCls =
  1331. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  1332. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  1333. + return new SoftDeleteQueryBuilderCls(this);
  1334. + }
  1335. + restore() {
  1336. + this.expressionMap.queryType = 'restore';
  1337. + // loading it dynamically because of circular issue
  1338. + const SoftDeleteQueryBuilderCls =
  1339. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  1340. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  1341. + return new SoftDeleteQueryBuilderCls(this);
  1342. + }
  1343. + /**
  1344. + * Sets entity's relation with which this query builder gonna work.
  1345. + */
  1346. + relation(entityTargetOrPropertyPath, maybePropertyPath) {
  1347. + const entityTarget =
  1348. + arguments.length === 2 ? entityTargetOrPropertyPath : undefined;
  1349. + const propertyPath =
  1350. + arguments.length === 2 ? maybePropertyPath : entityTargetOrPropertyPath;
  1351. + this.expressionMap.queryType = 'relation';
  1352. + this.expressionMap.relationPropertyPath = propertyPath;
  1353. + if (entityTarget) {
  1354. + const mainAlias = this.createFromAlias(entityTarget);
  1355. + this.expressionMap.setMainAlias(mainAlias);
  1356. + }
  1357. + // loading it dynamically because of circular issue
  1358. + const RelationQueryBuilderCls =
  1359. + require('typeorm/browser/query-builder/RelationQueryBuilder').RelationQueryBuilder;
  1360. + if (InstanceChecker.isRelationQueryBuilder(this)) return this;
  1361. + return new RelationQueryBuilderCls(this);
  1362. + }
  1363. + /**
  1364. + * Checks if given relation or relations exist in the entity.
  1365. + * Returns true if relation exists, false otherwise.
  1366. + *
  1367. + * todo: move this method to manager? or create a shortcut?
  1368. + */
  1369. + hasRelation(target, relation) {
  1370. + const entityMetadata = this.connection.getMetadata(target);
  1371. + const relations = Array.isArray(relation) ? relation : [relation];
  1372. + return relations.every((relation) => {
  1373. + return !!entityMetadata.findRelationWithPropertyPath(relation);
  1374. + });
  1375. + }
  1376. + /**
  1377. + * Check the existence of a parameter for this query builder.
  1378. + */
  1379. + hasParameter(key) {
  1380. + var _a;
  1381. + return (
  1382. + ((_a = this.parentQueryBuilder) === null || _a === void 0
  1383. + ? void 0
  1384. + : _a.hasParameter(key)) || key in this.expressionMap.parameters
  1385. + );
  1386. + }
  1387. + /**
  1388. + * Sets parameter name and its value.
  1389. + *
  1390. + * The key for this parameter may contain numbers, letters, underscores, or periods.
  1391. + */
  1392. + setParameter(key, value) {
  1393. + if (typeof value === 'function') {
  1394. + throw new TypeORMError(
  1395. + `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`
  1396. + );
  1397. + }
  1398. + if (!key.match(/^([A-Za-z0-9_.]+)$/)) {
  1399. + throw new TypeORMError(
  1400. + 'QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.'
  1401. + );
  1402. + }
  1403. + if (this.parentQueryBuilder) {
  1404. + this.parentQueryBuilder.setParameter(key, value);
  1405. + }
  1406. + this.expressionMap.parameters[key] = value;
  1407. + return this;
  1408. + }
  1409. + /**
  1410. + * Adds all parameters from the given object.
  1411. + */
  1412. + setParameters(parameters) {
  1413. + for (const [key, value] of Object.entries(parameters)) {
  1414. + this.setParameter(key, value);
  1415. + }
  1416. + return this;
  1417. + }
  1418. + createParameter(value) {
  1419. + let parameterName;
  1420. + do {
  1421. + parameterName = `orm_param_${this.parameterIndex++}`;
  1422. + } while (this.hasParameter(parameterName));
  1423. + this.setParameter(parameterName, value);
  1424. + return `:${parameterName}`;
  1425. + }
  1426. + /**
  1427. + * Adds native parameters from the given object.
  1428. + *
  1429. + * @deprecated Use `setParameters` instead
  1430. + */
  1431. + setNativeParameters(parameters) {
  1432. + // set parent query builder parameters as well in sub-query mode
  1433. + if (this.parentQueryBuilder) {
  1434. + this.parentQueryBuilder.setNativeParameters(parameters);
  1435. + }
  1436. + Object.keys(parameters).forEach((key) => {
  1437. + this.expressionMap.nativeParameters[key] = parameters[key];
  1438. + });
  1439. + return this;
  1440. + }
  1441. + /**
  1442. + * Gets all parameters.
  1443. + */
  1444. + getParameters() {
  1445. + const parameters = Object.assign({}, this.expressionMap.parameters);
  1446. + // add discriminator column parameter if it exist
  1447. + if (
  1448. + this.expressionMap.mainAlias &&
  1449. + this.expressionMap.mainAlias.hasMetadata
  1450. + ) {
  1451. + const metadata = this.expressionMap.mainAlias.metadata;
  1452. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  1453. + const values = metadata.childEntityMetadatas
  1454. + .filter((childMetadata) => childMetadata.discriminatorColumn)
  1455. + .map((childMetadata) => childMetadata.discriminatorValue);
  1456. + values.push(metadata.discriminatorValue);
  1457. + parameters['discriminatorColumnValues'] = values;
  1458. + }
  1459. + }
  1460. + return parameters;
  1461. + }
  1462. + /**
  1463. + * Prints sql to stdout using console.log.
  1464. + */
  1465. + printSql() {
  1466. + // TODO rename to logSql()
  1467. + const [query, parameters] = this.getQueryAndParameters();
  1468. + this.connection.logger.logQuery(query, parameters);
  1469. + return this;
  1470. + }
  1471. + /**
  1472. + * Gets generated sql that will be executed.
  1473. + * Parameters in the query are escaped for the currently used driver.
  1474. + */
  1475. + getSql() {
  1476. + return this.getQueryAndParameters()[0];
  1477. + }
  1478. + /**
  1479. + * Gets query to be executed with all parameters used in it.
  1480. + */
  1481. + getQueryAndParameters() {
  1482. + // this execution order is important because getQuery method generates this.expressionMap.nativeParameters values
  1483. + const query = this.getQuery();
  1484. + const parameters = this.getParameters();
  1485. + return this.connection.driver.escapeQueryWithParameters(
  1486. + query,
  1487. + parameters,
  1488. + this.expressionMap.nativeParameters
  1489. + );
  1490. + }
  1491. + /**
  1492. + * Executes sql generated by query builder and returns raw database results.
  1493. + */
  1494. + async execute() {
  1495. + const [sql, parameters] = this.getQueryAndParameters();
  1496. + const queryRunner = this.obtainQueryRunner();
  1497. + try {
  1498. + return await queryRunner.query(sql, parameters); // await is needed here because we are using finally
  1499. + } finally {
  1500. + if (queryRunner !== this.queryRunner) {
  1501. + // means we created our own query runner
  1502. + await queryRunner.release();
  1503. + }
  1504. + }
  1505. + }
  1506. + /**
  1507. + * Creates a completely new query builder.
  1508. + * Uses same query runner as current QueryBuilder.
  1509. + */
  1510. + createQueryBuilder() {
  1511. + return new this.constructor(this.connection, this.queryRunner);
  1512. + }
  1513. + /**
  1514. + * Clones query builder as it is.
  1515. + * Note: it uses new query runner, if you want query builder that uses exactly same query runner,
  1516. + * you can create query builder using its constructor, for example new SelectQueryBuilder(queryBuilder)
  1517. + * where queryBuilder is cloned QueryBuilder.
  1518. + */
  1519. + clone() {
  1520. + return new this.constructor(this);
  1521. + }
  1522. + /**
  1523. + * Includes a Query comment in the query builder. This is helpful for debugging purposes,
  1524. + * such as finding a specific query in the database server's logs, or for categorization using
  1525. + * an APM product.
  1526. + */
  1527. + comment(comment) {
  1528. + this.expressionMap.comment = comment;
  1529. + return this;
  1530. + }
  1531. + /**
  1532. + * Disables escaping.
  1533. + */
  1534. + disableEscaping() {
  1535. + this.expressionMap.disableEscaping = false;
  1536. + return this;
  1537. + }
  1538. + /**
  1539. + * Escapes table name, column name or alias name using current database's escaping character.
  1540. + */
  1541. + escape(name) {
  1542. + if (!this.expressionMap.disableEscaping) return name;
  1543. + return this.connection.driver.escape(name);
  1544. + }
  1545. + /**
  1546. + * Sets or overrides query builder's QueryRunner.
  1547. + */
  1548. + setQueryRunner(queryRunner) {
  1549. + this.queryRunner = queryRunner;
  1550. + return this;
  1551. + }
  1552. + /**
  1553. + * Indicates if listeners and subscribers must be called before and after query execution.
  1554. + * Enabled by default.
  1555. + */
  1556. + callListeners(enabled) {
  1557. + this.expressionMap.callListeners = enabled;
  1558. + return this;
  1559. + }
  1560. + /**
  1561. + * If set to true the query will be wrapped into a transaction.
  1562. + */
  1563. + useTransaction(enabled) {
  1564. + this.expressionMap.useTransaction = enabled;
  1565. + return this;
  1566. + }
  1567. + /**
  1568. + * Adds CTE to query
  1569. + */
  1570. + addCommonTableExpression(queryBuilder, alias, options) {
  1571. + this.expressionMap.commonTableExpressions.push({
  1572. + queryBuilder,
  1573. + alias,
  1574. + options: options || {},
  1575. + });
  1576. + return this;
  1577. + }
  1578. + // -------------------------------------------------------------------------
  1579. + // Protected Methods
  1580. + // -------------------------------------------------------------------------
  1581. + /**
  1582. + * Gets escaped table name with schema name if SqlServer driver used with custom
  1583. + * schema name, otherwise returns escaped table name.
  1584. + */
  1585. + getTableName(tablePath) {
  1586. + return tablePath
  1587. + .split('.')
  1588. + .map((i) => {
  1589. + // this condition need because in SQL Server driver when custom database name was specified and schema name was not, we got `dbName..tableName` string, and doesn't need to escape middle empty string
  1590. + if (i === '') return i;
  1591. + return this.escape(i);
  1592. + })
  1593. + .join('.');
  1594. + }
  1595. + /**
  1596. + * Gets name of the table where insert should be performed.
  1597. + */
  1598. + getMainTableName() {
  1599. + if (!this.expressionMap.mainAlias)
  1600. + throw new TypeORMError(
  1601. + `Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.`
  1602. + );
  1603. + if (this.expressionMap.mainAlias.hasMetadata)
  1604. + return this.expressionMap.mainAlias.metadata.tablePath;
  1605. + return this.expressionMap.mainAlias.tablePath;
  1606. + }
  1607. + /**
  1608. + * Specifies FROM which entity's table select/update/delete will be executed.
  1609. + * Also sets a main string alias of the selection data.
  1610. + */
  1611. + createFromAlias(entityTarget, aliasName) {
  1612. + // if table has a metadata then find it to properly escape its properties
  1613. + // const metadata = this.connection.entityMetadatas.find(metadata => metadata.tableName === tableName);
  1614. + if (this.connection.hasMetadata(entityTarget)) {
  1615. + const metadata = this.connection.getMetadata(entityTarget);
  1616. + return this.expressionMap.createAlias({
  1617. + type: 'from',
  1618. + name: aliasName,
  1619. + metadata: this.connection.getMetadata(entityTarget),
  1620. + tablePath: metadata.tablePath,
  1621. + });
  1622. + } else {
  1623. + if (typeof entityTarget === 'string') {
  1624. + const isSubquery =
  1625. + entityTarget.substr(0, 1) === '(' && entityTarget.substr(-1) === ')';
  1626. + return this.expressionMap.createAlias({
  1627. + type: 'from',
  1628. + name: aliasName,
  1629. + tablePath: !isSubquery ? entityTarget : undefined,
  1630. + subQuery: isSubquery ? entityTarget : undefined,
  1631. + });
  1632. + }
  1633. + const subQueryBuilder = entityTarget(this.subQuery());
  1634. + this.setParameters(subQueryBuilder.getParameters());
  1635. + const subquery = subQueryBuilder.getQuery();
  1636. + return this.expressionMap.createAlias({
  1637. + type: 'from',
  1638. + name: aliasName,
  1639. + subQuery: subquery,
  1640. + });
  1641. + }
  1642. + }
  1643. + /**
  1644. + * Replaces all entity's propertyName to name in the given statement.
  1645. + */
  1646. + replacePropertyNames(statement) {
  1647. + for (const alias of this.expressionMap.aliases) {
  1648. + if (!alias.hasMetadata) continue;
  1649. + const replaceAliasNamePrefix = this.expressionMap
  1650. + .aliasNamePrefixingEnabled
  1651. + ? `${alias.name}.`
  1652. + : '';
  1653. + const replacementAliasNamePrefix = this.expressionMap
  1654. + .aliasNamePrefixingEnabled
  1655. + ? `${this.escape(alias.name)}.`
  1656. + : '';
  1657. + const replacements = {};
  1658. + // Insert & overwrite the replacements from least to most relevant in our replacements object.
  1659. + // To do this we iterate and overwrite in the order of relevance.
  1660. + // Least to Most Relevant:
  1661. + // * Relation Property Path to first join column key
  1662. + // * Relation Property Path + Column Path
  1663. + // * Column Database Name
  1664. + // * Column Property Name
  1665. + // * Column Property Path
  1666. + for (const relation of alias.metadata.relations) {
  1667. + if (relation.joinColumns.length > 0)
  1668. + replacements[relation.propertyPath] =
  1669. + relation.joinColumns[0].databaseName;
  1670. + }
  1671. + for (const relation of alias.metadata.relations) {
  1672. + for (const joinColumn of [
  1673. + ...relation.joinColumns,
  1674. + ...relation.inverseJoinColumns,
  1675. + ]) {
  1676. + const propertyKey = `${relation.propertyPath}.${joinColumn.referencedColumn.propertyPath}`;
  1677. + replacements[propertyKey] = joinColumn.databaseName;
  1678. + }
  1679. + }
  1680. + for (const column of alias.metadata.columns) {
  1681. + replacements[column.databaseName] = column.databaseName;
  1682. + }
  1683. + for (const column of alias.metadata.columns) {
  1684. + replacements[column.propertyName] = column.databaseName;
  1685. + }
  1686. + for (const column of alias.metadata.columns) {
  1687. + replacements[column.propertyPath] = column.databaseName;
  1688. + }
  1689. + statement = statement.replace(
  1690. + new RegExp(
  1691. + // Avoid a lookbehind here since it's not well supported
  1692. + `([ =\(]|^.{0})` + // any of ' =(' or start of line
  1693. + // followed by our prefix, e.g. 'tablename.' or ''
  1694. + `${escapeRegExp(replaceAliasNamePrefix)}([^ =\(\)\,]+)` + // a possible property name: sequence of anything but ' =(),'
  1695. + // terminated by ' =),' or end of line
  1696. + `(?=[ =\)\,]|.{0}$)`,
  1697. + 'gm'
  1698. + ),
  1699. + (match, pre, p) => {
  1700. + if (replacements[p]) {
  1701. + return `${pre}${replacementAliasNamePrefix}${this.escape(
  1702. + replacements[p]
  1703. + )}`;
  1704. + }
  1705. + return match;
  1706. + }
  1707. + );
  1708. + }
  1709. + return statement;
  1710. + }
  1711. + createComment() {
  1712. + if (!this.expressionMap.comment) {
  1713. + return '';
  1714. + }
  1715. + // ANSI SQL 2003 support C style comments - comments that start with `/*` and end with `*/`
  1716. + // In some dialects query nesting is available - but not all. Because of this, we'll need
  1717. + // to scrub "ending" characters from the SQL but otherwise we can leave everything else
  1718. + // as-is and it should be valid.
  1719. + return `/* ${this.expressionMap.comment.replace('*/', '')} */ `;
  1720. + }
  1721. + /**
  1722. + * Creates "WHERE" expression.
  1723. + */
  1724. + createWhereExpression() {
  1725. + const conditionsArray = [];
  1726. + const whereExpression = this.createWhereClausesExpression(
  1727. + this.expressionMap.wheres
  1728. + );
  1729. + if (whereExpression.length > 0 && whereExpression !== '1=1') {
  1730. + conditionsArray.push(this.replacePropertyNames(whereExpression));
  1731. + }
  1732. + if (this.expressionMap.mainAlias.hasMetadata) {
  1733. + const metadata = this.expressionMap.mainAlias.metadata;
  1734. + // Adds the global condition of "non-deleted" for the entity with delete date columns in select query.
  1735. + if (
  1736. + this.expressionMap.queryType === 'select' &&
  1737. + !this.expressionMap.withDeleted &&
  1738. + metadata.deleteDateColumn
  1739. + ) {
  1740. + const column = this.expressionMap.aliasNamePrefixingEnabled
  1741. + ? this.expressionMap.mainAlias.name +
  1742. + '.' +
  1743. + metadata.deleteDateColumn.propertyName
  1744. + : metadata.deleteDateColumn.propertyName;
  1745. + const condition = `${this.replacePropertyNames(column)} IS NULL`;
  1746. + conditionsArray.push(condition);
  1747. + }
  1748. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  1749. + const column = this.expressionMap.aliasNamePrefixingEnabled
  1750. + ? this.expressionMap.mainAlias.name +
  1751. + '.' +
  1752. + metadata.discriminatorColumn.databaseName
  1753. + : metadata.discriminatorColumn.databaseName;
  1754. + const condition = `${this.replacePropertyNames(
  1755. + column
  1756. + )} IN (:...discriminatorColumnValues)`;
  1757. + conditionsArray.push(condition);
  1758. + }
  1759. + }
  1760. + if (this.expressionMap.extraAppendedAndWhereCondition) {
  1761. + const condition = this.replacePropertyNames(
  1762. + this.expressionMap.extraAppendedAndWhereCondition
  1763. + );
  1764. + conditionsArray.push(condition);
  1765. + }
  1766. + if (!conditionsArray.length) {
  1767. + return '';
  1768. + } else if (conditionsArray.length === 1) {
  1769. + return ` WHERE ${conditionsArray[0]}`;
  1770. + } else {
  1771. + return ` WHERE ( ${conditionsArray.join(' ) AND ( ')} )`;
  1772. + }
  1773. + }
  1774. + /**
  1775. + * Creates "RETURNING" / "OUTPUT" expression.
  1776. + */
  1777. + createReturningExpression(returningType) {
  1778. + const columns = this.getReturningColumns();
  1779. + const driver = this.connection.driver;
  1780. + // also add columns we must auto-return to perform entity updation
  1781. + // if user gave his own returning
  1782. + if (
  1783. + typeof this.expressionMap.returning !== 'string' &&
  1784. + this.expressionMap.extraReturningColumns.length > 0 &&
  1785. + driver.isReturningSqlSupported(returningType)
  1786. + ) {
  1787. + columns.push(
  1788. + ...this.expressionMap.extraReturningColumns.filter((column) => {
  1789. + return columns.indexOf(column) === -1;
  1790. + })
  1791. + );
  1792. + }
  1793. + if (columns.length) {
  1794. + let columnsExpression = columns
  1795. + .map((column) => {
  1796. + const name = this.escape(column.databaseName);
  1797. + if (driver.options.type === 'mssql') {
  1798. + if (
  1799. + this.expressionMap.queryType === 'insert' ||
  1800. + this.expressionMap.queryType === 'update' ||
  1801. + this.expressionMap.queryType === 'soft-delete' ||
  1802. + this.expressionMap.queryType === 'restore'
  1803. + ) {
  1804. + return 'INSERTED.' + name;
  1805. + } else {
  1806. + return this.escape(this.getMainTableName()) + '.' + name;
  1807. + }
  1808. + } else {
  1809. + return name;
  1810. + }
  1811. + })
  1812. + .join(', ');
  1813. + if (driver.options.type === 'oracle') {
  1814. + columnsExpression +=
  1815. + ' INTO ' +
  1816. + columns
  1817. + .map((column) => {
  1818. + return this.createParameter({
  1819. + type: driver.columnTypeToNativeParameter(column.type),
  1820. + dir: driver.oracle.BIND_OUT,
  1821. + });
  1822. + })
  1823. + .join(', ');
  1824. + }
  1825. + if (driver.options.type === 'mssql') {
  1826. + if (
  1827. + this.expressionMap.queryType === 'insert' ||
  1828. + this.expressionMap.queryType === 'update'
  1829. + ) {
  1830. + columnsExpression += ' INTO @OutputTable';
  1831. + }
  1832. + }
  1833. + return columnsExpression;
  1834. + } else if (typeof this.expressionMap.returning === 'string') {
  1835. + return this.expressionMap.returning;
  1836. + }
  1837. + return '';
  1838. + }
  1839. + /**
  1840. + * If returning / output cause is set to array of column names,
  1841. + * then this method will return all column metadatas of those column names.
  1842. + */
  1843. + getReturningColumns() {
  1844. + const columns = [];
  1845. + if (Array.isArray(this.expressionMap.returning)) {
  1846. + this.expressionMap.returning.forEach((columnName) => {
  1847. + if (this.expressionMap.mainAlias.hasMetadata) {
  1848. + columns.push(
  1849. + ...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(
  1850. + columnName
  1851. + )
  1852. + );
  1853. + }
  1854. + });
  1855. + }
  1856. + return columns;
  1857. + }
  1858. + createWhereClausesExpression(clauses) {
  1859. + return clauses
  1860. + .map((clause, index) => {
  1861. + const expression = this.createWhereConditionExpression(
  1862. + clause.condition
  1863. + );
  1864. + switch (clause.type) {
  1865. + case 'and':
  1866. + return (index > 0 ? 'AND ' : '') + expression;
  1867. + case 'or':
  1868. + return (index > 0 ? 'OR ' : '') + expression;
  1869. + }
  1870. + return expression;
  1871. + })
  1872. + .join(' ')
  1873. + .trim();
  1874. + }
  1875. + /**
  1876. + * Computes given where argument - transforms to a where string all forms it can take.
  1877. + */
  1878. + createWhereConditionExpression(condition, alwaysWrap = false) {
  1879. + if (typeof condition === 'string') return condition;
  1880. + if (Array.isArray(condition)) {
  1881. + if (condition.length === 0) {
  1882. + return '1=1';
  1883. + }
  1884. + // In the future we should probably remove this entire condition
  1885. + // but for now to prevent any breaking changes it exists.
  1886. + if (condition.length === 1 && !alwaysWrap) {
  1887. + return this.createWhereClausesExpression(condition);
  1888. + }
  1889. + return '(' + this.createWhereClausesExpression(condition) + ')';
  1890. + }
  1891. + const { driver } = this.connection;
  1892. + switch (condition.operator) {
  1893. + case 'lessThan':
  1894. + return `${condition.parameters[0]} < ${condition.parameters[1]}`;
  1895. + case 'lessThanOrEqual':
  1896. + return `${condition.parameters[0]} <= ${condition.parameters[1]}`;
  1897. + case 'arrayContains':
  1898. + return `${condition.parameters[0]} @> ${condition.parameters[1]}`;
  1899. + case 'arrayContainedBy':
  1900. + return `${condition.parameters[0]} <@ ${condition.parameters[1]}`;
  1901. + case 'arrayOverlap':
  1902. + return `${condition.parameters[0]} && ${condition.parameters[1]}`;
  1903. + case 'moreThan':
  1904. + return `${condition.parameters[0]} > ${condition.parameters[1]}`;
  1905. + case 'moreThanOrEqual':
  1906. + return `${condition.parameters[0]} >= ${condition.parameters[1]}`;
  1907. + case 'notEqual':
  1908. + return `${condition.parameters[0]} != ${condition.parameters[1]}`;
  1909. + case 'equal':
  1910. + return `${condition.parameters[0]} = ${condition.parameters[1]}`;
  1911. + case 'ilike':
  1912. + if (
  1913. + driver.options.type === 'postgres' ||
  1914. + driver.options.type === 'cockroachdb'
  1915. + ) {
  1916. + return `${condition.parameters[0]} ILIKE ${condition.parameters[1]}`;
  1917. + }
  1918. + return `UPPER(${condition.parameters[0]}) LIKE UPPER(${condition.parameters[1]})`;
  1919. + case 'like':
  1920. + return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`;
  1921. + case 'between':
  1922. + return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`;
  1923. + case 'in':
  1924. + if (condition.parameters.length <= 1) {
  1925. + return '0=1';
  1926. + }
  1927. + return `${condition.parameters[0]} IN (${condition.parameters
  1928. + .slice(1)
  1929. + .join(', ')})`;
  1930. + case 'any':
  1931. + return `${condition.parameters[0]} = ANY(${condition.parameters[1]})`;
  1932. + case 'isNull':
  1933. + return `${condition.parameters[0]} IS NULL`;
  1934. + case 'not':
  1935. + return `NOT(${this.createWhereConditionExpression(
  1936. + condition.condition
  1937. + )})`;
  1938. + case 'brackets':
  1939. + return `${this.createWhereConditionExpression(
  1940. + condition.condition,
  1941. + true
  1942. + )}`;
  1943. + }
  1944. + throw new TypeError(
  1945. + `Unsupported FindOperator ${FindOperator.constructor.name}`
  1946. + );
  1947. + }
  1948. + createCteExpression() {
  1949. + if (!this.hasCommonTableExpressions()) {
  1950. + return '';
  1951. + }
  1952. + const databaseRequireRecusiveHint =
  1953. + this.connection.driver.cteCapabilities.requiresRecursiveHint;
  1954. + const cteStrings = this.expressionMap.commonTableExpressions.map((cte) => {
  1955. + const cteBodyExpression =
  1956. + typeof cte.queryBuilder === 'string'
  1957. + ? cte.queryBuilder
  1958. + : cte.queryBuilder.getQuery();
  1959. + if (typeof cte.queryBuilder !== 'string') {
  1960. + if (cte.queryBuilder.hasCommonTableExpressions()) {
  1961. + throw new TypeORMError(
  1962. + `Nested CTEs aren't supported (CTE: ${cte.alias})`
  1963. + );
  1964. + }
  1965. + if (
  1966. + !this.connection.driver.cteCapabilities.writable &&
  1967. + !InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
  1968. + ) {
  1969. + throw new TypeORMError(
  1970. + `Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${cte.alias})`
  1971. + );
  1972. + }
  1973. + this.setParameters(cte.queryBuilder.getParameters());
  1974. + }
  1975. + let cteHeader = this.escape(cte.alias);
  1976. + if (cte.options.columnNames) {
  1977. + const escapedColumnNames = cte.options.columnNames.map((column) =>
  1978. + this.escape(column)
  1979. + );
  1980. + if (InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)) {
  1981. + if (
  1982. + cte.queryBuilder.expressionMap.selects.length &&
  1983. + cte.options.columnNames.length !==
  1984. + cte.queryBuilder.expressionMap.selects.length
  1985. + ) {
  1986. + throw new TypeORMError(
  1987. + `cte.options.columnNames length (${cte.options.columnNames.length}) doesn't match subquery select list length ${cte.queryBuilder.expressionMap.selects.length} (CTE: ${cte.alias})`
  1988. + );
  1989. + }
  1990. + }
  1991. + cteHeader += `(${escapedColumnNames.join(', ')})`;
  1992. + }
  1993. + const recursiveClause =
  1994. + cte.options.recursive && databaseRequireRecusiveHint ? 'RECURSIVE' : '';
  1995. + const materializeClause =
  1996. + cte.options.materialized &&
  1997. + this.connection.driver.cteCapabilities.materializedHint
  1998. + ? 'MATERIALIZED'
  1999. + : '';
  2000. + return [
  2001. + recursiveClause,
  2002. + cteHeader,
  2003. + materializeClause,
  2004. + 'AS',
  2005. + `(${cteBodyExpression})`,
  2006. + ]
  2007. + .filter(Boolean)
  2008. + .join(' ');
  2009. + });
  2010. + return 'WITH ' + cteStrings.join(', ') + ' ';
  2011. + }
  2012. + /**
  2013. + * Creates "WHERE" condition for an in-ids condition.
  2014. + */
  2015. + getWhereInIdsCondition(ids) {
  2016. + const metadata = this.expressionMap.mainAlias.metadata;
  2017. + const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
  2018. + metadata.ensureEntityIdMap(id)
  2019. + );
  2020. + // using in(...ids) for single primary key entities
  2021. + if (!metadata.hasMultiplePrimaryKeys) {
  2022. + const primaryColumn = metadata.primaryColumns[0];
  2023. + // getEntityValue will try to transform `In`, it is a bug
  2024. + // todo: remove this transformer check after #2390 is fixed
  2025. + // This also fails for embedded & relation, so until that is fixed skip it.
  2026. + if (
  2027. + !primaryColumn.transformer &&
  2028. + !primaryColumn.relationMetadata &&
  2029. + !primaryColumn.embeddedMetadata
  2030. + ) {
  2031. + return {
  2032. + [primaryColumn.propertyName]: In(
  2033. + normalized.map((id) => primaryColumn.getEntityValue(id, false))
  2034. + ),
  2035. + };
  2036. + }
  2037. + }
  2038. + return new Brackets((qb) => {
  2039. + for (const data of normalized) {
  2040. + qb.orWhere(new Brackets((qb) => qb.where(data)));
  2041. + }
  2042. + });
  2043. + }
  2044. + findColumnsForPropertyPath(propertyPath) {
  2045. + // Make a helper to iterate the entity & relations?
  2046. + // Use that to set the correct alias? Or the other way around?
  2047. + // Start with the main alias with our property paths
  2048. + let alias = this.expressionMap.mainAlias;
  2049. + const root = [];
  2050. + const propertyPathParts = propertyPath.split('.');
  2051. + while (propertyPathParts.length > 1) {
  2052. + const part = propertyPathParts[0];
  2053. + if (!(alias === null || alias === void 0 ? void 0 : alias.hasMetadata)) {
  2054. + // If there's no metadata, we're wasting our time
  2055. + // and can't actually look any of this up.
  2056. + break;
  2057. + }
  2058. + if (alias.metadata.hasEmbeddedWithPropertyPath(part)) {
  2059. + // If this is an embedded then we should combine the two as part of our lookup.
  2060. + // Instead of just breaking, we keep going with this in case there's an embedded/relation
  2061. + // inside an embedded.
  2062. + propertyPathParts.unshift(
  2063. + `${propertyPathParts.shift()}.${propertyPathParts.shift()}`
  2064. + );
  2065. + continue;
  2066. + }
  2067. + if (alias.metadata.hasRelationWithPropertyPath(part)) {
  2068. + // If this is a relation then we should find the aliases
  2069. + // that match the relation & then continue further down
  2070. + // the property path
  2071. + const joinAttr = this.expressionMap.joinAttributes.find(
  2072. + (joinAttr) => joinAttr.relationPropertyPath === part
  2073. + );
  2074. + if (
  2075. + !(joinAttr === null || joinAttr === void 0 ? void 0 : joinAttr.alias)
  2076. + ) {
  2077. + const fullRelationPath =
  2078. + root.length > 0 ? `${root.join('.')}.${part}` : part;
  2079. + throw new Error(
  2080. + `Cannot find alias for relation at ${fullRelationPath}`
  2081. + );
  2082. + }
  2083. + alias = joinAttr.alias;
  2084. + root.push(...part.split('.'));
  2085. + propertyPathParts.shift();
  2086. + continue;
  2087. + }
  2088. + break;
  2089. + }
  2090. + if (!alias) {
  2091. + throw new Error(`Cannot find alias for property ${propertyPath}`);
  2092. + }
  2093. + // Remaining parts are combined back and used to find the actual property path
  2094. + const aliasPropertyPath = propertyPathParts.join('.');
  2095. + const columns =
  2096. + alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath);
  2097. + if (!columns.length) {
  2098. + throw new EntityPropertyNotFoundError(propertyPath, alias.metadata);
  2099. + }
  2100. + return [alias, root, columns];
  2101. + }
  2102. + /**
  2103. + * Creates a property paths for a given ObjectLiteral.
  2104. + */
  2105. + createPropertyPath(metadata, entity, prefix = '') {
  2106. + const paths = [];
  2107. + for (const key of Object.keys(entity)) {
  2108. + const path = prefix ? `${prefix}.${key}` : key;
  2109. + // There's times where we don't actually want to traverse deeper.
  2110. + // If the value is a `FindOperator`, or null, or not an object, then we don't, for example.
  2111. + if (
  2112. + entity[key] === null ||
  2113. + typeof entity[key] !== 'object' ||
  2114. + InstanceChecker.isFindOperator(entity[key])
  2115. + ) {
  2116. + paths.push(path);
  2117. + continue;
  2118. + }
  2119. + if (metadata.hasEmbeddedWithPropertyPath(path)) {
  2120. + const subPaths = this.createPropertyPath(metadata, entity[key], path);
  2121. + paths.push(...subPaths);
  2122. + continue;
  2123. + }
  2124. + if (metadata.hasRelationWithPropertyPath(path)) {
  2125. + const relation = metadata.findRelationWithPropertyPath(path);
  2126. + // There's also cases where we don't want to return back all of the properties.
  2127. + // These handles the situation where someone passes the model & we don't need to make
  2128. + // a HUGE `where` to uniquely look up the entity.
  2129. + // In the case of a *-to-one, there's only ever one possible entity on the other side
  2130. + // so if the join columns are all defined we can return just the relation itself
  2131. + // because it will fetch only the join columns and do the lookup.
  2132. + if (
  2133. + relation.relationType === 'one-to-one' ||
  2134. + relation.relationType === 'many-to-one'
  2135. + ) {
  2136. + const joinColumns = relation.joinColumns
  2137. + .map((j) => j.referencedColumn)
  2138. + .filter((j) => !!j);
  2139. + const hasAllJoinColumns =
  2140. + joinColumns.length > 0 &&
  2141. + joinColumns.every((column) =>
  2142. + column.getEntityValue(entity[key], false)
  2143. + );
  2144. + if (hasAllJoinColumns) {
  2145. + paths.push(path);
  2146. + continue;
  2147. + }
  2148. + }
  2149. + if (
  2150. + relation.relationType === 'one-to-many' ||
  2151. + relation.relationType === 'many-to-many'
  2152. + ) {
  2153. + throw new Error(
  2154. + `Cannot query across ${relation.relationType} for property ${path}`
  2155. + );
  2156. + }
  2157. + // For any other case, if the `entity[key]` contains all of the primary keys we can do a
  2158. + // lookup via these. We don't need to look up via any other values 'cause these are
  2159. + // the unique primary keys.
  2160. + // This handles the situation where someone passes the model & we don't need to make
  2161. + // a HUGE where.
  2162. + const primaryColumns = relation.inverseEntityMetadata.primaryColumns;
  2163. + const hasAllPrimaryKeys =
  2164. + primaryColumns.length > 0 &&
  2165. + primaryColumns.every((column) =>
  2166. + column.getEntityValue(entity[key], false)
  2167. + );
  2168. + if (hasAllPrimaryKeys) {
  2169. + const subPaths = primaryColumns.map(
  2170. + (column) => `${path}.${column.propertyPath}`
  2171. + );
  2172. + paths.push(...subPaths);
  2173. + continue;
  2174. + }
  2175. + // If nothing else, just return every property that's being passed to us.
  2176. + const subPaths = this.createPropertyPath(
  2177. + relation.inverseEntityMetadata,
  2178. + entity[key]
  2179. + ).map((p) => `${path}.${p}`);
  2180. + paths.push(...subPaths);
  2181. + continue;
  2182. + }
  2183. + paths.push(path);
  2184. + }
  2185. + return paths;
  2186. + }
  2187. + *getPredicates(where) {
  2188. + if (this.expressionMap.mainAlias.hasMetadata) {
  2189. + const propertyPaths = this.createPropertyPath(
  2190. + this.expressionMap.mainAlias.metadata,
  2191. + where
  2192. + );
  2193. + for (const propertyPath of propertyPaths) {
  2194. + const [alias, aliasPropertyPath, columns] =
  2195. + this.findColumnsForPropertyPath(propertyPath);
  2196. + for (const column of columns) {
  2197. + let containedWhere = where;
  2198. + for (const part of aliasPropertyPath) {
  2199. + if (!containedWhere || !(part in containedWhere)) {
  2200. + containedWhere = {};
  2201. + break;
  2202. + }
  2203. + containedWhere = containedWhere[part];
  2204. + }
  2205. + // Use the correct alias & the property path from the column
  2206. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  2207. + ? `${alias.name}.${column.propertyPath}`
  2208. + : column.propertyPath;
  2209. + const parameterValue = column.getEntityValue(containedWhere, true);
  2210. + yield [aliasPath, parameterValue];
  2211. + }
  2212. + }
  2213. + } else {
  2214. + for (const key of Object.keys(where)) {
  2215. + const parameterValue = where[key];
  2216. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  2217. + ? `${this.alias}.${key}`
  2218. + : key;
  2219. + yield [aliasPath, parameterValue];
  2220. + }
  2221. + }
  2222. + }
  2223. + getWherePredicateCondition(aliasPath, parameterValue) {
  2224. + if (InstanceChecker.isFindOperator(parameterValue)) {
  2225. + let parameters = [];
  2226. + if (parameterValue.useParameter) {
  2227. + if (parameterValue.objectLiteralParameters) {
  2228. + this.setParameters(parameterValue.objectLiteralParameters);
  2229. + } else if (parameterValue.multipleParameters) {
  2230. + for (const v of parameterValue.value) {
  2231. + parameters.push(this.createParameter(v));
  2232. + }
  2233. + } else {
  2234. + parameters.push(this.createParameter(parameterValue.value));
  2235. + }
  2236. + }
  2237. + if (parameterValue.type === 'raw') {
  2238. + if (parameterValue.getSql) {
  2239. + return parameterValue.getSql(aliasPath);
  2240. + } else {
  2241. + return {
  2242. + operator: 'equal',
  2243. + parameters: [aliasPath, parameterValue.value],
  2244. + };
  2245. + }
  2246. + } else if (parameterValue.type === 'not') {
  2247. + if (parameterValue.child) {
  2248. + return {
  2249. + operator: parameterValue.type,
  2250. + condition: this.getWherePredicateCondition(
  2251. + aliasPath,
  2252. + parameterValue.child
  2253. + ),
  2254. + };
  2255. + } else {
  2256. + return {
  2257. + operator: 'notEqual',
  2258. + parameters: [aliasPath, ...parameters],
  2259. + };
  2260. + }
  2261. + } else {
  2262. + return {
  2263. + operator: parameterValue.type,
  2264. + parameters: [aliasPath, ...parameters],
  2265. + };
  2266. + }
  2267. + // } else if (parameterValue === null) {
  2268. + // return {
  2269. + // operator: "isNull",
  2270. + // parameters: [
  2271. + // aliasPath,
  2272. + // ]
  2273. + // };
  2274. + } else {
  2275. + return {
  2276. + operator: 'equal',
  2277. + parameters: [aliasPath, this.createParameter(parameterValue)],
  2278. + };
  2279. + }
  2280. + }
  2281. + getWhereCondition(where) {
  2282. + if (typeof where === 'string') {
  2283. + return where;
  2284. + }
  2285. + if (InstanceChecker.isBrackets(where)) {
  2286. + const whereQueryBuilder = this.createQueryBuilder();
  2287. + whereQueryBuilder.parentQueryBuilder = this;
  2288. + whereQueryBuilder.expressionMap.mainAlias = this.expressionMap.mainAlias;
  2289. + whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
  2290. + this.expressionMap.aliasNamePrefixingEnabled;
  2291. + whereQueryBuilder.expressionMap.parameters =
  2292. + this.expressionMap.parameters;
  2293. + whereQueryBuilder.expressionMap.nativeParameters =
  2294. + this.expressionMap.nativeParameters;
  2295. + whereQueryBuilder.expressionMap.wheres = [];
  2296. + where.whereFactory(whereQueryBuilder);
  2297. + return {
  2298. + operator: InstanceChecker.isNotBrackets(where) ? 'not' : 'brackets',
  2299. + condition: whereQueryBuilder.expressionMap.wheres,
  2300. + };
  2301. + }
  2302. + if (typeof where === 'function') {
  2303. + return where(this);
  2304. + }
  2305. + const wheres = Array.isArray(where) ? where : [where];
  2306. + const clauses = [];
  2307. + for (const where of wheres) {
  2308. + const conditions = [];
  2309. + // Filter the conditions and set up the parameter values
  2310. + for (const [aliasPath, parameterValue] of this.getPredicates(where)) {
  2311. + conditions.push({
  2312. + type: 'and',
  2313. + condition: this.getWherePredicateCondition(aliasPath, parameterValue),
  2314. + });
  2315. + }
  2316. + clauses.push({ type: 'or', condition: conditions });
  2317. + }
  2318. + if (clauses.length === 1) {
  2319. + return clauses[0].condition;
  2320. + }
  2321. + return clauses;
  2322. + }
  2323. + /**
  2324. + * Creates a query builder used to execute sql queries inside this query builder.
  2325. + */
  2326. + obtainQueryRunner() {
  2327. + return this.queryRunner || this.connection.createQueryRunner();
  2328. + }
  2329. + hasCommonTableExpressions() {
  2330. + return this.expressionMap.commonTableExpressions.length > 0;
  2331. + }
  2332. +}
  2333. +
  2334. +//# sourceMappingURL=QueryBuilder.js.map
  2335. diff --git a/node_modules/typeorm/browser/query-builder/RelationQueryBuilder.js b/node_modules/typeorm/browser/query-builder/RelationQueryBuilder.js
  2336. index 23a19c3..013ba97 100644
  2337. --- a/node_modules/typeorm/browser/query-builder/RelationQueryBuilder.js
  2338. +++ b/node_modules/typeorm/browser/query-builder/RelationQueryBuilder.js
  2339. @@ -1,14 +1,14 @@
  2340. -import { QueryBuilder } from "./QueryBuilder";
  2341. import { RelationUpdater } from "./RelationUpdater";
  2342. import { RelationRemover } from "./RelationRemover";
  2343. import { TypeORMError } from "../error";
  2344. import { ObjectUtils } from "../util/ObjectUtils";
  2345. +import { RelationQueryBuilderBase } from "./RelationQueryBuilderBase";
  2346. /**
  2347. * Allows to work with entity relations and perform specific operations with those relations.
  2348. *
  2349. * todo: add transactions everywhere
  2350. */
  2351. -export class RelationQueryBuilder extends QueryBuilder {
  2352. +export class RelationQueryBuilder extends RelationQueryBuilderBase {
  2353. constructor() {
  2354. super(...arguments);
  2355. this["@instanceof"] = Symbol.for("RelationQueryBuilder");
  2356. diff --git a/node_modules/typeorm/browser/query-builder/RelationQueryBuilderBase.js b/node_modules/typeorm/browser/query-builder/RelationQueryBuilderBase.js
  2357. new file mode 100644
  2358. index 0000000..0412b83
  2359. --- /dev/null
  2360. +++ b/node_modules/typeorm/browser/query-builder/RelationQueryBuilderBase.js
  2361. @@ -0,0 +1,1133 @@
  2362. +import { QueryExpressionMap } from './QueryExpressionMap';
  2363. +import { Brackets } from './Brackets';
  2364. +import { FindOperator } from '../find-options/FindOperator';
  2365. +import { In } from '../find-options/operator/In';
  2366. +import { TypeORMError } from '../error';
  2367. +import { EntityPropertyNotFoundError } from '../error/EntityPropertyNotFoundError';
  2368. +import { InstanceChecker } from '../util/InstanceChecker';
  2369. +import { escapeRegExp } from '../util/escapeRegExp';
  2370. +// todo: completely cover query builder with tests
  2371. +// todo: entityOrProperty can be target name. implement proper behaviour if it is.
  2372. +// todo: check in persistment if id exist on object and throw exception (can be in partial selection?)
  2373. +// todo: fix problem with long aliases eg getMaxIdentifierLength
  2374. +// todo: fix replacing in .select("COUNT(post.id) AS cnt") statement
  2375. +// todo: implement joinAlways in relations and relationId
  2376. +// todo: finish partial selection
  2377. +// todo: sugar methods like: .addCount and .selectCount, selectCountAndMap, selectSum, selectSumAndMap, ...
  2378. +// todo: implement @Select decorator
  2379. +// todo: add select and map functions
  2380. +// todo: implement relation/entity loading and setting them into properties within a separate query
  2381. +// .loadAndMap("post.categories", "post.categories", qb => ...)
  2382. +// .loadAndMap("post.categories", Category, qb => ...)
  2383. +/**
  2384. + * Allows to build complex sql queries in a fashion way and execute those queries.
  2385. + */
  2386. +export class RelationQueryBuilderBase {
  2387. + /**
  2388. + * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
  2389. + */
  2390. + constructor(connectionOrQueryBuilder, queryRunner) {
  2391. + this['@instanceof'] = Symbol.for('QueryBuilder');
  2392. + /**
  2393. + * Memo to help keep place of current parameter index for `createParameter`
  2394. + */
  2395. + this.parameterIndex = 0;
  2396. + if (InstanceChecker.isQueryBuilder(connectionOrQueryBuilder)) {
  2397. + this.connection = connectionOrQueryBuilder.connection;
  2398. + this.queryRunner = connectionOrQueryBuilder.queryRunner;
  2399. + this.expressionMap = connectionOrQueryBuilder.expressionMap.clone();
  2400. + } else {
  2401. + this.connection = connectionOrQueryBuilder;
  2402. + this.queryRunner = queryRunner;
  2403. + this.expressionMap = new QueryExpressionMap(this.connection);
  2404. + }
  2405. + }
  2406. + // -------------------------------------------------------------------------
  2407. + // Accessors
  2408. + // -------------------------------------------------------------------------
  2409. + /**
  2410. + * Gets the main alias string used in this query builder.
  2411. + */
  2412. + get alias() {
  2413. + if (!this.expressionMap.mainAlias)
  2414. + throw new TypeORMError(`Main alias is not set`); // todo: better exception
  2415. + return this.expressionMap.mainAlias.name;
  2416. + }
  2417. + /**
  2418. + * Creates SELECT query and selects given data.
  2419. + * Replaces all previous selections if they exist.
  2420. + */
  2421. + select(selection, selectionAliasName) {
  2422. + this.expressionMap.queryType = 'select';
  2423. + if (Array.isArray(selection)) {
  2424. + this.expressionMap.selects = selection.map((selection) => ({
  2425. + selection: selection,
  2426. + }));
  2427. + } else if (selection) {
  2428. + this.expressionMap.selects = [
  2429. + { selection: selection, aliasName: selectionAliasName },
  2430. + ];
  2431. + }
  2432. + // loading it dynamically because of circular issue
  2433. + const SelectQueryBuilderCls =
  2434. + require('typeorm/browser/query-builder/SelectQueryBuilder').SelectQueryBuilder;
  2435. + if (InstanceChecker.isSelectQueryBuilder(this)) return this;
  2436. + return new SelectQueryBuilderCls(this);
  2437. + }
  2438. + /**
  2439. + * Creates INSERT query.
  2440. + */
  2441. + insert() {
  2442. + this.expressionMap.queryType = 'insert';
  2443. + // loading it dynamically because of circular issue
  2444. + const InsertQueryBuilderCls =
  2445. + require('typeorm/browser/query-builder/InsertQueryBuilder').InsertQueryBuilder;
  2446. + if (InstanceChecker.isInsertQueryBuilder(this)) return this;
  2447. + return new InsertQueryBuilderCls(this);
  2448. + }
  2449. + /**
  2450. + * Creates UPDATE query and applies given update values.
  2451. + */
  2452. + update(entityOrTableNameUpdateSet, maybeUpdateSet) {
  2453. + const updateSet = maybeUpdateSet
  2454. + ? maybeUpdateSet
  2455. + : entityOrTableNameUpdateSet;
  2456. + entityOrTableNameUpdateSet = InstanceChecker.isEntitySchema(
  2457. + entityOrTableNameUpdateSet
  2458. + )
  2459. + ? entityOrTableNameUpdateSet.options.name
  2460. + : entityOrTableNameUpdateSet;
  2461. + if (
  2462. + typeof entityOrTableNameUpdateSet === 'function' ||
  2463. + typeof entityOrTableNameUpdateSet === 'string'
  2464. + ) {
  2465. + const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet);
  2466. + this.expressionMap.setMainAlias(mainAlias);
  2467. + }
  2468. + this.expressionMap.queryType = 'update';
  2469. + this.expressionMap.valuesSet = updateSet;
  2470. + // loading it dynamically because of circular issue
  2471. + const UpdateQueryBuilderCls =
  2472. + require('typeorm/browser/query-builder/UpdateQueryBuilder').UpdateQueryBuilder;
  2473. + if (InstanceChecker.isUpdateQueryBuilder(this)) return this;
  2474. + return new UpdateQueryBuilderCls(this);
  2475. + }
  2476. + /**
  2477. + * Creates DELETE query.
  2478. + */
  2479. + delete() {
  2480. + this.expressionMap.queryType = 'delete';
  2481. + // loading it dynamically because of circular issue
  2482. + const DeleteQueryBuilderCls =
  2483. + require('typeorm/browser/query-builder/DeleteQueryBuilder').DeleteQueryBuilder;
  2484. + if (InstanceChecker.isDeleteQueryBuilder(this)) return this;
  2485. + return new DeleteQueryBuilderCls(this);
  2486. + }
  2487. + softDelete() {
  2488. + this.expressionMap.queryType = 'soft-delete';
  2489. + // loading it dynamically because of circular issue
  2490. + const SoftDeleteQueryBuilderCls =
  2491. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  2492. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  2493. + return new SoftDeleteQueryBuilderCls(this);
  2494. + }
  2495. + restore() {
  2496. + this.expressionMap.queryType = 'restore';
  2497. + // loading it dynamically because of circular issue
  2498. + const SoftDeleteQueryBuilderCls =
  2499. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  2500. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  2501. + return new SoftDeleteQueryBuilderCls(this);
  2502. + }
  2503. + /**
  2504. + * Sets entity's relation with which this query builder gonna work.
  2505. + */
  2506. + relation(entityTargetOrPropertyPath, maybePropertyPath) {
  2507. + const entityTarget =
  2508. + arguments.length === 2 ? entityTargetOrPropertyPath : undefined;
  2509. + const propertyPath =
  2510. + arguments.length === 2 ? maybePropertyPath : entityTargetOrPropertyPath;
  2511. + this.expressionMap.queryType = 'relation';
  2512. + this.expressionMap.relationPropertyPath = propertyPath;
  2513. + if (entityTarget) {
  2514. + const mainAlias = this.createFromAlias(entityTarget);
  2515. + this.expressionMap.setMainAlias(mainAlias);
  2516. + }
  2517. + // loading it dynamically because of circular issue
  2518. + const RelationQueryBuilderCls =
  2519. + require('typeorm/browser/query-builder/RelationQueryBuilder').RelationQueryBuilder;
  2520. + if (InstanceChecker.isRelationQueryBuilder(this)) return this;
  2521. + return new RelationQueryBuilderCls(this);
  2522. + }
  2523. + /**
  2524. + * Checks if given relation or relations exist in the entity.
  2525. + * Returns true if relation exists, false otherwise.
  2526. + *
  2527. + * todo: move this method to manager? or create a shortcut?
  2528. + */
  2529. + hasRelation(target, relation) {
  2530. + const entityMetadata = this.connection.getMetadata(target);
  2531. + const relations = Array.isArray(relation) ? relation : [relation];
  2532. + return relations.every((relation) => {
  2533. + return !!entityMetadata.findRelationWithPropertyPath(relation);
  2534. + });
  2535. + }
  2536. + /**
  2537. + * Check the existence of a parameter for this query builder.
  2538. + */
  2539. + hasParameter(key) {
  2540. + var _a;
  2541. + return (
  2542. + ((_a = this.parentQueryBuilder) === null || _a === void 0
  2543. + ? void 0
  2544. + : _a.hasParameter(key)) || key in this.expressionMap.parameters
  2545. + );
  2546. + }
  2547. + /**
  2548. + * Sets parameter name and its value.
  2549. + *
  2550. + * The key for this parameter may contain numbers, letters, underscores, or periods.
  2551. + */
  2552. + setParameter(key, value) {
  2553. + if (typeof value === 'function') {
  2554. + throw new TypeORMError(
  2555. + `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`
  2556. + );
  2557. + }
  2558. + if (!key.match(/^([A-Za-z0-9_.]+)$/)) {
  2559. + throw new TypeORMError(
  2560. + 'QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.'
  2561. + );
  2562. + }
  2563. + if (this.parentQueryBuilder) {
  2564. + this.parentQueryBuilder.setParameter(key, value);
  2565. + }
  2566. + this.expressionMap.parameters[key] = value;
  2567. + return this;
  2568. + }
  2569. + /**
  2570. + * Adds all parameters from the given object.
  2571. + */
  2572. + setParameters(parameters) {
  2573. + for (const [key, value] of Object.entries(parameters)) {
  2574. + this.setParameter(key, value);
  2575. + }
  2576. + return this;
  2577. + }
  2578. + createParameter(value) {
  2579. + let parameterName;
  2580. + do {
  2581. + parameterName = `orm_param_${this.parameterIndex++}`;
  2582. + } while (this.hasParameter(parameterName));
  2583. + this.setParameter(parameterName, value);
  2584. + return `:${parameterName}`;
  2585. + }
  2586. + /**
  2587. + * Adds native parameters from the given object.
  2588. + *
  2589. + * @deprecated Use `setParameters` instead
  2590. + */
  2591. + setNativeParameters(parameters) {
  2592. + // set parent query builder parameters as well in sub-query mode
  2593. + if (this.parentQueryBuilder) {
  2594. + this.parentQueryBuilder.setNativeParameters(parameters);
  2595. + }
  2596. + Object.keys(parameters).forEach((key) => {
  2597. + this.expressionMap.nativeParameters[key] = parameters[key];
  2598. + });
  2599. + return this;
  2600. + }
  2601. + /**
  2602. + * Gets all parameters.
  2603. + */
  2604. + getParameters() {
  2605. + const parameters = Object.assign({}, this.expressionMap.parameters);
  2606. + // add discriminator column parameter if it exist
  2607. + if (
  2608. + this.expressionMap.mainAlias &&
  2609. + this.expressionMap.mainAlias.hasMetadata
  2610. + ) {
  2611. + const metadata = this.expressionMap.mainAlias.metadata;
  2612. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  2613. + const values = metadata.childEntityMetadatas
  2614. + .filter((childMetadata) => childMetadata.discriminatorColumn)
  2615. + .map((childMetadata) => childMetadata.discriminatorValue);
  2616. + values.push(metadata.discriminatorValue);
  2617. + parameters['discriminatorColumnValues'] = values;
  2618. + }
  2619. + }
  2620. + return parameters;
  2621. + }
  2622. + /**
  2623. + * Prints sql to stdout using console.log.
  2624. + */
  2625. + printSql() {
  2626. + // TODO rename to logSql()
  2627. + const [query, parameters] = this.getQueryAndParameters();
  2628. + this.connection.logger.logQuery(query, parameters);
  2629. + return this;
  2630. + }
  2631. + /**
  2632. + * Gets generated sql that will be executed.
  2633. + * Parameters in the query are escaped for the currently used driver.
  2634. + */
  2635. + getSql() {
  2636. + return this.getQueryAndParameters()[0];
  2637. + }
  2638. + /**
  2639. + * Gets query to be executed with all parameters used in it.
  2640. + */
  2641. + getQueryAndParameters() {
  2642. + // this execution order is important because getQuery method generates this.expressionMap.nativeParameters values
  2643. + const query = this.getQuery();
  2644. + const parameters = this.getParameters();
  2645. + return this.connection.driver.escapeQueryWithParameters(
  2646. + query,
  2647. + parameters,
  2648. + this.expressionMap.nativeParameters
  2649. + );
  2650. + }
  2651. + /**
  2652. + * Executes sql generated by query builder and returns raw database results.
  2653. + */
  2654. + async execute() {
  2655. + const [sql, parameters] = this.getQueryAndParameters();
  2656. + const queryRunner = this.obtainQueryRunner();
  2657. + try {
  2658. + return await queryRunner.query(sql, parameters); // await is needed here because we are using finally
  2659. + } finally {
  2660. + if (queryRunner !== this.queryRunner) {
  2661. + // means we created our own query runner
  2662. + await queryRunner.release();
  2663. + }
  2664. + }
  2665. + }
  2666. + /**
  2667. + * Creates a completely new query builder.
  2668. + * Uses same query runner as current QueryBuilder.
  2669. + */
  2670. + createQueryBuilder() {
  2671. + return new this.constructor(this.connection, this.queryRunner);
  2672. + }
  2673. + /**
  2674. + * Clones query builder as it is.
  2675. + * Note: it uses new query runner, if you want query builder that uses exactly same query runner,
  2676. + * you can create query builder using its constructor, for example new SelectQueryBuilder(queryBuilder)
  2677. + * where queryBuilder is cloned QueryBuilder.
  2678. + */
  2679. + clone() {
  2680. + return new this.constructor(this);
  2681. + }
  2682. + /**
  2683. + * Includes a Query comment in the query builder. This is helpful for debugging purposes,
  2684. + * such as finding a specific query in the database server's logs, or for categorization using
  2685. + * an APM product.
  2686. + */
  2687. + comment(comment) {
  2688. + this.expressionMap.comment = comment;
  2689. + return this;
  2690. + }
  2691. + /**
  2692. + * Disables escaping.
  2693. + */
  2694. + disableEscaping() {
  2695. + this.expressionMap.disableEscaping = false;
  2696. + return this;
  2697. + }
  2698. + /**
  2699. + * Escapes table name, column name or alias name using current database's escaping character.
  2700. + */
  2701. + escape(name) {
  2702. + if (!this.expressionMap.disableEscaping) return name;
  2703. + return this.connection.driver.escape(name);
  2704. + }
  2705. + /**
  2706. + * Sets or overrides query builder's QueryRunner.
  2707. + */
  2708. + setQueryRunner(queryRunner) {
  2709. + this.queryRunner = queryRunner;
  2710. + return this;
  2711. + }
  2712. + /**
  2713. + * Indicates if listeners and subscribers must be called before and after query execution.
  2714. + * Enabled by default.
  2715. + */
  2716. + callListeners(enabled) {
  2717. + this.expressionMap.callListeners = enabled;
  2718. + return this;
  2719. + }
  2720. + /**
  2721. + * If set to true the query will be wrapped into a transaction.
  2722. + */
  2723. + useTransaction(enabled) {
  2724. + this.expressionMap.useTransaction = enabled;
  2725. + return this;
  2726. + }
  2727. + /**
  2728. + * Adds CTE to query
  2729. + */
  2730. + addCommonTableExpression(queryBuilder, alias, options) {
  2731. + this.expressionMap.commonTableExpressions.push({
  2732. + queryBuilder,
  2733. + alias,
  2734. + options: options || {},
  2735. + });
  2736. + return this;
  2737. + }
  2738. + // -------------------------------------------------------------------------
  2739. + // Protected Methods
  2740. + // -------------------------------------------------------------------------
  2741. + /**
  2742. + * Gets escaped table name with schema name if SqlServer driver used with custom
  2743. + * schema name, otherwise returns escaped table name.
  2744. + */
  2745. + getTableName(tablePath) {
  2746. + return tablePath
  2747. + .split('.')
  2748. + .map((i) => {
  2749. + // this condition need because in SQL Server driver when custom database name was specified and schema name was not, we got `dbName..tableName` string, and doesn't need to escape middle empty string
  2750. + if (i === '') return i;
  2751. + return this.escape(i);
  2752. + })
  2753. + .join('.');
  2754. + }
  2755. + /**
  2756. + * Gets name of the table where insert should be performed.
  2757. + */
  2758. + getMainTableName() {
  2759. + if (!this.expressionMap.mainAlias)
  2760. + throw new TypeORMError(
  2761. + `Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.`
  2762. + );
  2763. + if (this.expressionMap.mainAlias.hasMetadata)
  2764. + return this.expressionMap.mainAlias.metadata.tablePath;
  2765. + return this.expressionMap.mainAlias.tablePath;
  2766. + }
  2767. + /**
  2768. + * Specifies FROM which entity's table select/update/delete will be executed.
  2769. + * Also sets a main string alias of the selection data.
  2770. + */
  2771. + createFromAlias(entityTarget, aliasName) {
  2772. + // if table has a metadata then find it to properly escape its properties
  2773. + // const metadata = this.connection.entityMetadatas.find(metadata => metadata.tableName === tableName);
  2774. + if (this.connection.hasMetadata(entityTarget)) {
  2775. + const metadata = this.connection.getMetadata(entityTarget);
  2776. + return this.expressionMap.createAlias({
  2777. + type: 'from',
  2778. + name: aliasName,
  2779. + metadata: this.connection.getMetadata(entityTarget),
  2780. + tablePath: metadata.tablePath,
  2781. + });
  2782. + } else {
  2783. + if (typeof entityTarget === 'string') {
  2784. + const isSubquery =
  2785. + entityTarget.substr(0, 1) === '(' && entityTarget.substr(-1) === ')';
  2786. + return this.expressionMap.createAlias({
  2787. + type: 'from',
  2788. + name: aliasName,
  2789. + tablePath: !isSubquery ? entityTarget : undefined,
  2790. + subQuery: isSubquery ? entityTarget : undefined,
  2791. + });
  2792. + }
  2793. + const subQueryBuilder = entityTarget(this.subQuery());
  2794. + this.setParameters(subQueryBuilder.getParameters());
  2795. + const subquery = subQueryBuilder.getQuery();
  2796. + return this.expressionMap.createAlias({
  2797. + type: 'from',
  2798. + name: aliasName,
  2799. + subQuery: subquery,
  2800. + });
  2801. + }
  2802. + }
  2803. + /**
  2804. + * Replaces all entity's propertyName to name in the given statement.
  2805. + */
  2806. + replacePropertyNames(statement) {
  2807. + for (const alias of this.expressionMap.aliases) {
  2808. + if (!alias.hasMetadata) continue;
  2809. + const replaceAliasNamePrefix = this.expressionMap
  2810. + .aliasNamePrefixingEnabled
  2811. + ? `${alias.name}.`
  2812. + : '';
  2813. + const replacementAliasNamePrefix = this.expressionMap
  2814. + .aliasNamePrefixingEnabled
  2815. + ? `${this.escape(alias.name)}.`
  2816. + : '';
  2817. + const replacements = {};
  2818. + // Insert & overwrite the replacements from least to most relevant in our replacements object.
  2819. + // To do this we iterate and overwrite in the order of relevance.
  2820. + // Least to Most Relevant:
  2821. + // * Relation Property Path to first join column key
  2822. + // * Relation Property Path + Column Path
  2823. + // * Column Database Name
  2824. + // * Column Property Name
  2825. + // * Column Property Path
  2826. + for (const relation of alias.metadata.relations) {
  2827. + if (relation.joinColumns.length > 0)
  2828. + replacements[relation.propertyPath] =
  2829. + relation.joinColumns[0].databaseName;
  2830. + }
  2831. + for (const relation of alias.metadata.relations) {
  2832. + for (const joinColumn of [
  2833. + ...relation.joinColumns,
  2834. + ...relation.inverseJoinColumns,
  2835. + ]) {
  2836. + const propertyKey = `${relation.propertyPath}.${joinColumn.referencedColumn.propertyPath}`;
  2837. + replacements[propertyKey] = joinColumn.databaseName;
  2838. + }
  2839. + }
  2840. + for (const column of alias.metadata.columns) {
  2841. + replacements[column.databaseName] = column.databaseName;
  2842. + }
  2843. + for (const column of alias.metadata.columns) {
  2844. + replacements[column.propertyName] = column.databaseName;
  2845. + }
  2846. + for (const column of alias.metadata.columns) {
  2847. + replacements[column.propertyPath] = column.databaseName;
  2848. + }
  2849. + statement = statement.replace(
  2850. + new RegExp(
  2851. + // Avoid a lookbehind here since it's not well supported
  2852. + `([ =\(]|^.{0})` + // any of ' =(' or start of line
  2853. + // followed by our prefix, e.g. 'tablename.' or ''
  2854. + `${escapeRegExp(replaceAliasNamePrefix)}([^ =\(\)\,]+)` + // a possible property name: sequence of anything but ' =(),'
  2855. + // terminated by ' =),' or end of line
  2856. + `(?=[ =\)\,]|.{0}$)`,
  2857. + 'gm'
  2858. + ),
  2859. + (match, pre, p) => {
  2860. + if (replacements[p]) {
  2861. + return `${pre}${replacementAliasNamePrefix}${this.escape(
  2862. + replacements[p]
  2863. + )}`;
  2864. + }
  2865. + return match;
  2866. + }
  2867. + );
  2868. + }
  2869. + return statement;
  2870. + }
  2871. + createComment() {
  2872. + if (!this.expressionMap.comment) {
  2873. + return '';
  2874. + }
  2875. + // ANSI SQL 2003 support C style comments - comments that start with `/*` and end with `*/`
  2876. + // In some dialects query nesting is available - but not all. Because of this, we'll need
  2877. + // to scrub "ending" characters from the SQL but otherwise we can leave everything else
  2878. + // as-is and it should be valid.
  2879. + return `/* ${this.expressionMap.comment.replace('*/', '')} */ `;
  2880. + }
  2881. + /**
  2882. + * Creates "WHERE" expression.
  2883. + */
  2884. + createWhereExpression() {
  2885. + const conditionsArray = [];
  2886. + const whereExpression = this.createWhereClausesExpression(
  2887. + this.expressionMap.wheres
  2888. + );
  2889. + if (whereExpression.length > 0 && whereExpression !== '1=1') {
  2890. + conditionsArray.push(this.replacePropertyNames(whereExpression));
  2891. + }
  2892. + if (this.expressionMap.mainAlias.hasMetadata) {
  2893. + const metadata = this.expressionMap.mainAlias.metadata;
  2894. + // Adds the global condition of "non-deleted" for the entity with delete date columns in select query.
  2895. + if (
  2896. + this.expressionMap.queryType === 'select' &&
  2897. + !this.expressionMap.withDeleted &&
  2898. + metadata.deleteDateColumn
  2899. + ) {
  2900. + const column = this.expressionMap.aliasNamePrefixingEnabled
  2901. + ? this.expressionMap.mainAlias.name +
  2902. + '.' +
  2903. + metadata.deleteDateColumn.propertyName
  2904. + : metadata.deleteDateColumn.propertyName;
  2905. + const condition = `${this.replacePropertyNames(column)} IS NULL`;
  2906. + conditionsArray.push(condition);
  2907. + }
  2908. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  2909. + const column = this.expressionMap.aliasNamePrefixingEnabled
  2910. + ? this.expressionMap.mainAlias.name +
  2911. + '.' +
  2912. + metadata.discriminatorColumn.databaseName
  2913. + : metadata.discriminatorColumn.databaseName;
  2914. + const condition = `${this.replacePropertyNames(
  2915. + column
  2916. + )} IN (:...discriminatorColumnValues)`;
  2917. + conditionsArray.push(condition);
  2918. + }
  2919. + }
  2920. + if (this.expressionMap.extraAppendedAndWhereCondition) {
  2921. + const condition = this.replacePropertyNames(
  2922. + this.expressionMap.extraAppendedAndWhereCondition
  2923. + );
  2924. + conditionsArray.push(condition);
  2925. + }
  2926. + if (!conditionsArray.length) {
  2927. + return '';
  2928. + } else if (conditionsArray.length === 1) {
  2929. + return ` WHERE ${conditionsArray[0]}`;
  2930. + } else {
  2931. + return ` WHERE ( ${conditionsArray.join(' ) AND ( ')} )`;
  2932. + }
  2933. + }
  2934. + /**
  2935. + * Creates "RETURNING" / "OUTPUT" expression.
  2936. + */
  2937. + createReturningExpression(returningType) {
  2938. + const columns = this.getReturningColumns();
  2939. + const driver = this.connection.driver;
  2940. + // also add columns we must auto-return to perform entity updation
  2941. + // if user gave his own returning
  2942. + if (
  2943. + typeof this.expressionMap.returning !== 'string' &&
  2944. + this.expressionMap.extraReturningColumns.length > 0 &&
  2945. + driver.isReturningSqlSupported(returningType)
  2946. + ) {
  2947. + columns.push(
  2948. + ...this.expressionMap.extraReturningColumns.filter((column) => {
  2949. + return columns.indexOf(column) === -1;
  2950. + })
  2951. + );
  2952. + }
  2953. + if (columns.length) {
  2954. + let columnsExpression = columns
  2955. + .map((column) => {
  2956. + const name = this.escape(column.databaseName);
  2957. + if (driver.options.type === 'mssql') {
  2958. + if (
  2959. + this.expressionMap.queryType === 'insert' ||
  2960. + this.expressionMap.queryType === 'update' ||
  2961. + this.expressionMap.queryType === 'soft-delete' ||
  2962. + this.expressionMap.queryType === 'restore'
  2963. + ) {
  2964. + return 'INSERTED.' + name;
  2965. + } else {
  2966. + return this.escape(this.getMainTableName()) + '.' + name;
  2967. + }
  2968. + } else {
  2969. + return name;
  2970. + }
  2971. + })
  2972. + .join(', ');
  2973. + if (driver.options.type === 'oracle') {
  2974. + columnsExpression +=
  2975. + ' INTO ' +
  2976. + columns
  2977. + .map((column) => {
  2978. + return this.createParameter({
  2979. + type: driver.columnTypeToNativeParameter(column.type),
  2980. + dir: driver.oracle.BIND_OUT,
  2981. + });
  2982. + })
  2983. + .join(', ');
  2984. + }
  2985. + if (driver.options.type === 'mssql') {
  2986. + if (
  2987. + this.expressionMap.queryType === 'insert' ||
  2988. + this.expressionMap.queryType === 'update'
  2989. + ) {
  2990. + columnsExpression += ' INTO @OutputTable';
  2991. + }
  2992. + }
  2993. + return columnsExpression;
  2994. + } else if (typeof this.expressionMap.returning === 'string') {
  2995. + return this.expressionMap.returning;
  2996. + }
  2997. + return '';
  2998. + }
  2999. + /**
  3000. + * If returning / output cause is set to array of column names,
  3001. + * then this method will return all column metadatas of those column names.
  3002. + */
  3003. + getReturningColumns() {
  3004. + const columns = [];
  3005. + if (Array.isArray(this.expressionMap.returning)) {
  3006. + this.expressionMap.returning.forEach((columnName) => {
  3007. + if (this.expressionMap.mainAlias.hasMetadata) {
  3008. + columns.push(
  3009. + ...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(
  3010. + columnName
  3011. + )
  3012. + );
  3013. + }
  3014. + });
  3015. + }
  3016. + return columns;
  3017. + }
  3018. + createWhereClausesExpression(clauses) {
  3019. + return clauses
  3020. + .map((clause, index) => {
  3021. + const expression = this.createWhereConditionExpression(
  3022. + clause.condition
  3023. + );
  3024. + switch (clause.type) {
  3025. + case 'and':
  3026. + return (index > 0 ? 'AND ' : '') + expression;
  3027. + case 'or':
  3028. + return (index > 0 ? 'OR ' : '') + expression;
  3029. + }
  3030. + return expression;
  3031. + })
  3032. + .join(' ')
  3033. + .trim();
  3034. + }
  3035. + /**
  3036. + * Computes given where argument - transforms to a where string all forms it can take.
  3037. + */
  3038. + createWhereConditionExpression(condition, alwaysWrap = false) {
  3039. + if (typeof condition === 'string') return condition;
  3040. + if (Array.isArray(condition)) {
  3041. + if (condition.length === 0) {
  3042. + return '1=1';
  3043. + }
  3044. + // In the future we should probably remove this entire condition
  3045. + // but for now to prevent any breaking changes it exists.
  3046. + if (condition.length === 1 && !alwaysWrap) {
  3047. + return this.createWhereClausesExpression(condition);
  3048. + }
  3049. + return '(' + this.createWhereClausesExpression(condition) + ')';
  3050. + }
  3051. + const { driver } = this.connection;
  3052. + switch (condition.operator) {
  3053. + case 'lessThan':
  3054. + return `${condition.parameters[0]} < ${condition.parameters[1]}`;
  3055. + case 'lessThanOrEqual':
  3056. + return `${condition.parameters[0]} <= ${condition.parameters[1]}`;
  3057. + case 'arrayContains':
  3058. + return `${condition.parameters[0]} @> ${condition.parameters[1]}`;
  3059. + case 'arrayContainedBy':
  3060. + return `${condition.parameters[0]} <@ ${condition.parameters[1]}`;
  3061. + case 'arrayOverlap':
  3062. + return `${condition.parameters[0]} && ${condition.parameters[1]}`;
  3063. + case 'moreThan':
  3064. + return `${condition.parameters[0]} > ${condition.parameters[1]}`;
  3065. + case 'moreThanOrEqual':
  3066. + return `${condition.parameters[0]} >= ${condition.parameters[1]}`;
  3067. + case 'notEqual':
  3068. + return `${condition.parameters[0]} != ${condition.parameters[1]}`;
  3069. + case 'equal':
  3070. + return `${condition.parameters[0]} = ${condition.parameters[1]}`;
  3071. + case 'ilike':
  3072. + if (
  3073. + driver.options.type === 'postgres' ||
  3074. + driver.options.type === 'cockroachdb'
  3075. + ) {
  3076. + return `${condition.parameters[0]} ILIKE ${condition.parameters[1]}`;
  3077. + }
  3078. + return `UPPER(${condition.parameters[0]}) LIKE UPPER(${condition.parameters[1]})`;
  3079. + case 'like':
  3080. + return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`;
  3081. + case 'between':
  3082. + return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`;
  3083. + case 'in':
  3084. + if (condition.parameters.length <= 1) {
  3085. + return '0=1';
  3086. + }
  3087. + return `${condition.parameters[0]} IN (${condition.parameters
  3088. + .slice(1)
  3089. + .join(', ')})`;
  3090. + case 'any':
  3091. + return `${condition.parameters[0]} = ANY(${condition.parameters[1]})`;
  3092. + case 'isNull':
  3093. + return `${condition.parameters[0]} IS NULL`;
  3094. + case 'not':
  3095. + return `NOT(${this.createWhereConditionExpression(
  3096. + condition.condition
  3097. + )})`;
  3098. + case 'brackets':
  3099. + return `${this.createWhereConditionExpression(
  3100. + condition.condition,
  3101. + true
  3102. + )}`;
  3103. + }
  3104. + throw new TypeError(
  3105. + `Unsupported FindOperator ${FindOperator.constructor.name}`
  3106. + );
  3107. + }
  3108. + createCteExpression() {
  3109. + if (!this.hasCommonTableExpressions()) {
  3110. + return '';
  3111. + }
  3112. + const databaseRequireRecusiveHint =
  3113. + this.connection.driver.cteCapabilities.requiresRecursiveHint;
  3114. + const cteStrings = this.expressionMap.commonTableExpressions.map((cte) => {
  3115. + const cteBodyExpression =
  3116. + typeof cte.queryBuilder === 'string'
  3117. + ? cte.queryBuilder
  3118. + : cte.queryBuilder.getQuery();
  3119. + if (typeof cte.queryBuilder !== 'string') {
  3120. + if (cte.queryBuilder.hasCommonTableExpressions()) {
  3121. + throw new TypeORMError(
  3122. + `Nested CTEs aren't supported (CTE: ${cte.alias})`
  3123. + );
  3124. + }
  3125. + if (
  3126. + !this.connection.driver.cteCapabilities.writable &&
  3127. + !InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
  3128. + ) {
  3129. + throw new TypeORMError(
  3130. + `Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${cte.alias})`
  3131. + );
  3132. + }
  3133. + this.setParameters(cte.queryBuilder.getParameters());
  3134. + }
  3135. + let cteHeader = this.escape(cte.alias);
  3136. + if (cte.options.columnNames) {
  3137. + const escapedColumnNames = cte.options.columnNames.map((column) =>
  3138. + this.escape(column)
  3139. + );
  3140. + if (InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)) {
  3141. + if (
  3142. + cte.queryBuilder.expressionMap.selects.length &&
  3143. + cte.options.columnNames.length !==
  3144. + cte.queryBuilder.expressionMap.selects.length
  3145. + ) {
  3146. + throw new TypeORMError(
  3147. + `cte.options.columnNames length (${cte.options.columnNames.length}) doesn't match subquery select list length ${cte.queryBuilder.expressionMap.selects.length} (CTE: ${cte.alias})`
  3148. + );
  3149. + }
  3150. + }
  3151. + cteHeader += `(${escapedColumnNames.join(', ')})`;
  3152. + }
  3153. + const recursiveClause =
  3154. + cte.options.recursive && databaseRequireRecusiveHint ? 'RECURSIVE' : '';
  3155. + const materializeClause =
  3156. + cte.options.materialized &&
  3157. + this.connection.driver.cteCapabilities.materializedHint
  3158. + ? 'MATERIALIZED'
  3159. + : '';
  3160. + return [
  3161. + recursiveClause,
  3162. + cteHeader,
  3163. + materializeClause,
  3164. + 'AS',
  3165. + `(${cteBodyExpression})`,
  3166. + ]
  3167. + .filter(Boolean)
  3168. + .join(' ');
  3169. + });
  3170. + return 'WITH ' + cteStrings.join(', ') + ' ';
  3171. + }
  3172. + /**
  3173. + * Creates "WHERE" condition for an in-ids condition.
  3174. + */
  3175. + getWhereInIdsCondition(ids) {
  3176. + const metadata = this.expressionMap.mainAlias.metadata;
  3177. + const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
  3178. + metadata.ensureEntityIdMap(id)
  3179. + );
  3180. + // using in(...ids) for single primary key entities
  3181. + if (!metadata.hasMultiplePrimaryKeys) {
  3182. + const primaryColumn = metadata.primaryColumns[0];
  3183. + // getEntityValue will try to transform `In`, it is a bug
  3184. + // todo: remove this transformer check after #2390 is fixed
  3185. + // This also fails for embedded & relation, so until that is fixed skip it.
  3186. + if (
  3187. + !primaryColumn.transformer &&
  3188. + !primaryColumn.relationMetadata &&
  3189. + !primaryColumn.embeddedMetadata
  3190. + ) {
  3191. + return {
  3192. + [primaryColumn.propertyName]: In(
  3193. + normalized.map((id) => primaryColumn.getEntityValue(id, false))
  3194. + ),
  3195. + };
  3196. + }
  3197. + }
  3198. + return new Brackets((qb) => {
  3199. + for (const data of normalized) {
  3200. + qb.orWhere(new Brackets((qb) => qb.where(data)));
  3201. + }
  3202. + });
  3203. + }
  3204. + findColumnsForPropertyPath(propertyPath) {
  3205. + // Make a helper to iterate the entity & relations?
  3206. + // Use that to set the correct alias? Or the other way around?
  3207. + // Start with the main alias with our property paths
  3208. + let alias = this.expressionMap.mainAlias;
  3209. + const root = [];
  3210. + const propertyPathParts = propertyPath.split('.');
  3211. + while (propertyPathParts.length > 1) {
  3212. + const part = propertyPathParts[0];
  3213. + if (!(alias === null || alias === void 0 ? void 0 : alias.hasMetadata)) {
  3214. + // If there's no metadata, we're wasting our time
  3215. + // and can't actually look any of this up.
  3216. + break;
  3217. + }
  3218. + if (alias.metadata.hasEmbeddedWithPropertyPath(part)) {
  3219. + // If this is an embedded then we should combine the two as part of our lookup.
  3220. + // Instead of just breaking, we keep going with this in case there's an embedded/relation
  3221. + // inside an embedded.
  3222. + propertyPathParts.unshift(
  3223. + `${propertyPathParts.shift()}.${propertyPathParts.shift()}`
  3224. + );
  3225. + continue;
  3226. + }
  3227. + if (alias.metadata.hasRelationWithPropertyPath(part)) {
  3228. + // If this is a relation then we should find the aliases
  3229. + // that match the relation & then continue further down
  3230. + // the property path
  3231. + const joinAttr = this.expressionMap.joinAttributes.find(
  3232. + (joinAttr) => joinAttr.relationPropertyPath === part
  3233. + );
  3234. + if (
  3235. + !(joinAttr === null || joinAttr === void 0 ? void 0 : joinAttr.alias)
  3236. + ) {
  3237. + const fullRelationPath =
  3238. + root.length > 0 ? `${root.join('.')}.${part}` : part;
  3239. + throw new Error(
  3240. + `Cannot find alias for relation at ${fullRelationPath}`
  3241. + );
  3242. + }
  3243. + alias = joinAttr.alias;
  3244. + root.push(...part.split('.'));
  3245. + propertyPathParts.shift();
  3246. + continue;
  3247. + }
  3248. + break;
  3249. + }
  3250. + if (!alias) {
  3251. + throw new Error(`Cannot find alias for property ${propertyPath}`);
  3252. + }
  3253. + // Remaining parts are combined back and used to find the actual property path
  3254. + const aliasPropertyPath = propertyPathParts.join('.');
  3255. + const columns =
  3256. + alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath);
  3257. + if (!columns.length) {
  3258. + throw new EntityPropertyNotFoundError(propertyPath, alias.metadata);
  3259. + }
  3260. + return [alias, root, columns];
  3261. + }
  3262. + /**
  3263. + * Creates a property paths for a given ObjectLiteral.
  3264. + */
  3265. + createPropertyPath(metadata, entity, prefix = '') {
  3266. + const paths = [];
  3267. + for (const key of Object.keys(entity)) {
  3268. + const path = prefix ? `${prefix}.${key}` : key;
  3269. + // There's times where we don't actually want to traverse deeper.
  3270. + // If the value is a `FindOperator`, or null, or not an object, then we don't, for example.
  3271. + if (
  3272. + entity[key] === null ||
  3273. + typeof entity[key] !== 'object' ||
  3274. + InstanceChecker.isFindOperator(entity[key])
  3275. + ) {
  3276. + paths.push(path);
  3277. + continue;
  3278. + }
  3279. + if (metadata.hasEmbeddedWithPropertyPath(path)) {
  3280. + const subPaths = this.createPropertyPath(metadata, entity[key], path);
  3281. + paths.push(...subPaths);
  3282. + continue;
  3283. + }
  3284. + if (metadata.hasRelationWithPropertyPath(path)) {
  3285. + const relation = metadata.findRelationWithPropertyPath(path);
  3286. + // There's also cases where we don't want to return back all of the properties.
  3287. + // These handles the situation where someone passes the model & we don't need to make
  3288. + // a HUGE `where` to uniquely look up the entity.
  3289. + // In the case of a *-to-one, there's only ever one possible entity on the other side
  3290. + // so if the join columns are all defined we can return just the relation itself
  3291. + // because it will fetch only the join columns and do the lookup.
  3292. + if (
  3293. + relation.relationType === 'one-to-one' ||
  3294. + relation.relationType === 'many-to-one'
  3295. + ) {
  3296. + const joinColumns = relation.joinColumns
  3297. + .map((j) => j.referencedColumn)
  3298. + .filter((j) => !!j);
  3299. + const hasAllJoinColumns =
  3300. + joinColumns.length > 0 &&
  3301. + joinColumns.every((column) =>
  3302. + column.getEntityValue(entity[key], false)
  3303. + );
  3304. + if (hasAllJoinColumns) {
  3305. + paths.push(path);
  3306. + continue;
  3307. + }
  3308. + }
  3309. + if (
  3310. + relation.relationType === 'one-to-many' ||
  3311. + relation.relationType === 'many-to-many'
  3312. + ) {
  3313. + throw new Error(
  3314. + `Cannot query across ${relation.relationType} for property ${path}`
  3315. + );
  3316. + }
  3317. + // For any other case, if the `entity[key]` contains all of the primary keys we can do a
  3318. + // lookup via these. We don't need to look up via any other values 'cause these are
  3319. + // the unique primary keys.
  3320. + // This handles the situation where someone passes the model & we don't need to make
  3321. + // a HUGE where.
  3322. + const primaryColumns = relation.inverseEntityMetadata.primaryColumns;
  3323. + const hasAllPrimaryKeys =
  3324. + primaryColumns.length > 0 &&
  3325. + primaryColumns.every((column) =>
  3326. + column.getEntityValue(entity[key], false)
  3327. + );
  3328. + if (hasAllPrimaryKeys) {
  3329. + const subPaths = primaryColumns.map(
  3330. + (column) => `${path}.${column.propertyPath}`
  3331. + );
  3332. + paths.push(...subPaths);
  3333. + continue;
  3334. + }
  3335. + // If nothing else, just return every property that's being passed to us.
  3336. + const subPaths = this.createPropertyPath(
  3337. + relation.inverseEntityMetadata,
  3338. + entity[key]
  3339. + ).map((p) => `${path}.${p}`);
  3340. + paths.push(...subPaths);
  3341. + continue;
  3342. + }
  3343. + paths.push(path);
  3344. + }
  3345. + return paths;
  3346. + }
  3347. + *getPredicates(where) {
  3348. + if (this.expressionMap.mainAlias.hasMetadata) {
  3349. + const propertyPaths = this.createPropertyPath(
  3350. + this.expressionMap.mainAlias.metadata,
  3351. + where
  3352. + );
  3353. + for (const propertyPath of propertyPaths) {
  3354. + const [alias, aliasPropertyPath, columns] =
  3355. + this.findColumnsForPropertyPath(propertyPath);
  3356. + for (const column of columns) {
  3357. + let containedWhere = where;
  3358. + for (const part of aliasPropertyPath) {
  3359. + if (!containedWhere || !(part in containedWhere)) {
  3360. + containedWhere = {};
  3361. + break;
  3362. + }
  3363. + containedWhere = containedWhere[part];
  3364. + }
  3365. + // Use the correct alias & the property path from the column
  3366. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  3367. + ? `${alias.name}.${column.propertyPath}`
  3368. + : column.propertyPath;
  3369. + const parameterValue = column.getEntityValue(containedWhere, true);
  3370. + yield [aliasPath, parameterValue];
  3371. + }
  3372. + }
  3373. + } else {
  3374. + for (const key of Object.keys(where)) {
  3375. + const parameterValue = where[key];
  3376. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  3377. + ? `${this.alias}.${key}`
  3378. + : key;
  3379. + yield [aliasPath, parameterValue];
  3380. + }
  3381. + }
  3382. + }
  3383. + getWherePredicateCondition(aliasPath, parameterValue) {
  3384. + if (InstanceChecker.isFindOperator(parameterValue)) {
  3385. + let parameters = [];
  3386. + if (parameterValue.useParameter) {
  3387. + if (parameterValue.objectLiteralParameters) {
  3388. + this.setParameters(parameterValue.objectLiteralParameters);
  3389. + } else if (parameterValue.multipleParameters) {
  3390. + for (const v of parameterValue.value) {
  3391. + parameters.push(this.createParameter(v));
  3392. + }
  3393. + } else {
  3394. + parameters.push(this.createParameter(parameterValue.value));
  3395. + }
  3396. + }
  3397. + if (parameterValue.type === 'raw') {
  3398. + if (parameterValue.getSql) {
  3399. + return parameterValue.getSql(aliasPath);
  3400. + } else {
  3401. + return {
  3402. + operator: 'equal',
  3403. + parameters: [aliasPath, parameterValue.value],
  3404. + };
  3405. + }
  3406. + } else if (parameterValue.type === 'not') {
  3407. + if (parameterValue.child) {
  3408. + return {
  3409. + operator: parameterValue.type,
  3410. + condition: this.getWherePredicateCondition(
  3411. + aliasPath,
  3412. + parameterValue.child
  3413. + ),
  3414. + };
  3415. + } else {
  3416. + return {
  3417. + operator: 'notEqual',
  3418. + parameters: [aliasPath, ...parameters],
  3419. + };
  3420. + }
  3421. + } else {
  3422. + return {
  3423. + operator: parameterValue.type,
  3424. + parameters: [aliasPath, ...parameters],
  3425. + };
  3426. + }
  3427. + // } else if (parameterValue === null) {
  3428. + // return {
  3429. + // operator: "isNull",
  3430. + // parameters: [
  3431. + // aliasPath,
  3432. + // ]
  3433. + // };
  3434. + } else {
  3435. + return {
  3436. + operator: 'equal',
  3437. + parameters: [aliasPath, this.createParameter(parameterValue)],
  3438. + };
  3439. + }
  3440. + }
  3441. + getWhereCondition(where) {
  3442. + if (typeof where === 'string') {
  3443. + return where;
  3444. + }
  3445. + if (InstanceChecker.isBrackets(where)) {
  3446. + const whereQueryBuilder = this.createQueryBuilder();
  3447. + whereQueryBuilder.parentQueryBuilder = this;
  3448. + whereQueryBuilder.expressionMap.mainAlias = this.expressionMap.mainAlias;
  3449. + whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
  3450. + this.expressionMap.aliasNamePrefixingEnabled;
  3451. + whereQueryBuilder.expressionMap.parameters =
  3452. + this.expressionMap.parameters;
  3453. + whereQueryBuilder.expressionMap.nativeParameters =
  3454. + this.expressionMap.nativeParameters;
  3455. + whereQueryBuilder.expressionMap.wheres = [];
  3456. + where.whereFactory(whereQueryBuilder);
  3457. + return {
  3458. + operator: InstanceChecker.isNotBrackets(where) ? 'not' : 'brackets',
  3459. + condition: whereQueryBuilder.expressionMap.wheres,
  3460. + };
  3461. + }
  3462. + if (typeof where === 'function') {
  3463. + return where(this);
  3464. + }
  3465. + const wheres = Array.isArray(where) ? where : [where];
  3466. + const clauses = [];
  3467. + for (const where of wheres) {
  3468. + const conditions = [];
  3469. + // Filter the conditions and set up the parameter values
  3470. + for (const [aliasPath, parameterValue] of this.getPredicates(where)) {
  3471. + conditions.push({
  3472. + type: 'and',
  3473. + condition: this.getWherePredicateCondition(aliasPath, parameterValue),
  3474. + });
  3475. + }
  3476. + clauses.push({ type: 'or', condition: conditions });
  3477. + }
  3478. + if (clauses.length === 1) {
  3479. + return clauses[0].condition;
  3480. + }
  3481. + return clauses;
  3482. + }
  3483. + /**
  3484. + * Creates a query builder used to execute sql queries inside this query builder.
  3485. + */
  3486. + obtainQueryRunner() {
  3487. + return this.queryRunner || this.connection.createQueryRunner();
  3488. + }
  3489. + hasCommonTableExpressions() {
  3490. + return this.expressionMap.commonTableExpressions.length > 0;
  3491. + }
  3492. +}
  3493. +
  3494. +//# sourceMappingURL=QueryBuilder.js.map
  3495. diff --git a/node_modules/typeorm/browser/query-builder/SelectQueryBuilder.js b/node_modules/typeorm/browser/query-builder/SelectQueryBuilder.js
  3496. index 137e0fe..76537a2 100644
  3497. --- a/node_modules/typeorm/browser/query-builder/SelectQueryBuilder.js
  3498. +++ b/node_modules/typeorm/browser/query-builder/SelectQueryBuilder.js
  3499. @@ -10,7 +10,6 @@ import { RelationIdLoader } from "./relation-id/RelationIdLoader";
  3500. import { RelationIdMetadataToAttributeTransformer } from "./relation-id/RelationIdMetadataToAttributeTransformer";
  3501. import { RelationCountLoader } from "./relation-count/RelationCountLoader";
  3502. import { RelationCountMetadataToAttributeTransformer } from "./relation-count/RelationCountMetadataToAttributeTransformer";
  3503. -import { QueryBuilder } from "./QueryBuilder";
  3504. import { LockNotSupportedOnGivenDriverError } from "../error/LockNotSupportedOnGivenDriverError";
  3505. import { OffsetWithoutLimitNotSupportedError } from "../error/OffsetWithoutLimitNotSupportedError";
  3506. import { ObjectUtils } from "../util/ObjectUtils";
  3507. @@ -22,10 +21,11 @@ import { ApplyValueTransformers } from "../util/ApplyValueTransformers";
  3508. import { OrmUtils } from "../util/OrmUtils";
  3509. import { EntityPropertyNotFoundError } from "../error/EntityPropertyNotFoundError";
  3510. import { InstanceChecker } from "../util/InstanceChecker";
  3511. +import { SelectQueryBuilderBase } from "./SelectQueryBuilderBase";
  3512. /**
  3513. * Allows to build complex sql queries in a fashion way and execute those queries.
  3514. */
  3515. -export class SelectQueryBuilder extends QueryBuilder {
  3516. +export class SelectQueryBuilder extends SelectQueryBuilderBase {
  3517. constructor() {
  3518. super(...arguments);
  3519. this["@instanceof"] = Symbol.for("SelectQueryBuilder");
  3520. diff --git a/node_modules/typeorm/browser/query-builder/SelectQueryBuilderBase.js b/node_modules/typeorm/browser/query-builder/SelectQueryBuilderBase.js
  3521. new file mode 100644
  3522. index 0000000..1c5ae25
  3523. --- /dev/null
  3524. +++ b/node_modules/typeorm/browser/query-builder/SelectQueryBuilderBase.js
  3525. @@ -0,0 +1,1133 @@
  3526. +import { QueryExpressionMap } from './QueryExpressionMap';
  3527. +import { Brackets } from './Brackets';
  3528. +import { FindOperator } from '../find-options/FindOperator';
  3529. +import { In } from '../find-options/operator/In';
  3530. +import { TypeORMError } from '../error';
  3531. +import { EntityPropertyNotFoundError } from '../error/EntityPropertyNotFoundError';
  3532. +import { InstanceChecker } from '../util/InstanceChecker';
  3533. +import { escapeRegExp } from '../util/escapeRegExp';
  3534. +// todo: completely cover query builder with tests
  3535. +// todo: entityOrProperty can be target name. implement proper behaviour if it is.
  3536. +// todo: check in persistment if id exist on object and throw exception (can be in partial selection?)
  3537. +// todo: fix problem with long aliases eg getMaxIdentifierLength
  3538. +// todo: fix replacing in .select("COUNT(post.id) AS cnt") statement
  3539. +// todo: implement joinAlways in relations and relationId
  3540. +// todo: finish partial selection
  3541. +// todo: sugar methods like: .addCount and .selectCount, selectCountAndMap, selectSum, selectSumAndMap, ...
  3542. +// todo: implement @Select decorator
  3543. +// todo: add select and map functions
  3544. +// todo: implement relation/entity loading and setting them into properties within a separate query
  3545. +// .loadAndMap("post.categories", "post.categories", qb => ...)
  3546. +// .loadAndMap("post.categories", Category, qb => ...)
  3547. +/**
  3548. + * Allows to build complex sql queries in a fashion way and execute those queries.
  3549. + */
  3550. +export class SelectQueryBuilderBase {
  3551. + /**
  3552. + * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
  3553. + */
  3554. + constructor(connectionOrQueryBuilder, queryRunner) {
  3555. + this['@instanceof'] = Symbol.for('QueryBuilder');
  3556. + /**
  3557. + * Memo to help keep place of current parameter index for `createParameter`
  3558. + */
  3559. + this.parameterIndex = 0;
  3560. + if (InstanceChecker.isQueryBuilder(connectionOrQueryBuilder)) {
  3561. + this.connection = connectionOrQueryBuilder.connection;
  3562. + this.queryRunner = connectionOrQueryBuilder.queryRunner;
  3563. + this.expressionMap = connectionOrQueryBuilder.expressionMap.clone();
  3564. + } else {
  3565. + this.connection = connectionOrQueryBuilder;
  3566. + this.queryRunner = queryRunner;
  3567. + this.expressionMap = new QueryExpressionMap(this.connection);
  3568. + }
  3569. + }
  3570. + // -------------------------------------------------------------------------
  3571. + // Accessors
  3572. + // -------------------------------------------------------------------------
  3573. + /**
  3574. + * Gets the main alias string used in this query builder.
  3575. + */
  3576. + get alias() {
  3577. + if (!this.expressionMap.mainAlias)
  3578. + throw new TypeORMError(`Main alias is not set`); // todo: better exception
  3579. + return this.expressionMap.mainAlias.name;
  3580. + }
  3581. + /**
  3582. + * Creates SELECT query and selects given data.
  3583. + * Replaces all previous selections if they exist.
  3584. + */
  3585. + select(selection, selectionAliasName) {
  3586. + this.expressionMap.queryType = 'select';
  3587. + if (Array.isArray(selection)) {
  3588. + this.expressionMap.selects = selection.map((selection) => ({
  3589. + selection: selection,
  3590. + }));
  3591. + } else if (selection) {
  3592. + this.expressionMap.selects = [
  3593. + { selection: selection, aliasName: selectionAliasName },
  3594. + ];
  3595. + }
  3596. + // loading it dynamically because of circular issue
  3597. + const SelectQueryBuilderCls =
  3598. + require('typeorm/browser/query-builder/SelectQueryBuilder').SelectQueryBuilder;
  3599. + if (InstanceChecker.isSelectQueryBuilder(this)) return this;
  3600. + return new SelectQueryBuilderCls(this);
  3601. + }
  3602. + /**
  3603. + * Creates INSERT query.
  3604. + */
  3605. + insert() {
  3606. + this.expressionMap.queryType = 'insert';
  3607. + // loading it dynamically because of circular issue
  3608. + const InsertQueryBuilderCls =
  3609. + require('typeorm/browser/query-builder/InsertQueryBuilder').InsertQueryBuilder;
  3610. + if (InstanceChecker.isInsertQueryBuilder(this)) return this;
  3611. + return new InsertQueryBuilderCls(this);
  3612. + }
  3613. + /**
  3614. + * Creates UPDATE query and applies given update values.
  3615. + */
  3616. + update(entityOrTableNameUpdateSet, maybeUpdateSet) {
  3617. + const updateSet = maybeUpdateSet
  3618. + ? maybeUpdateSet
  3619. + : entityOrTableNameUpdateSet;
  3620. + entityOrTableNameUpdateSet = InstanceChecker.isEntitySchema(
  3621. + entityOrTableNameUpdateSet
  3622. + )
  3623. + ? entityOrTableNameUpdateSet.options.name
  3624. + : entityOrTableNameUpdateSet;
  3625. + if (
  3626. + typeof entityOrTableNameUpdateSet === 'function' ||
  3627. + typeof entityOrTableNameUpdateSet === 'string'
  3628. + ) {
  3629. + const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet);
  3630. + this.expressionMap.setMainAlias(mainAlias);
  3631. + }
  3632. + this.expressionMap.queryType = 'update';
  3633. + this.expressionMap.valuesSet = updateSet;
  3634. + // loading it dynamically because of circular issue
  3635. + const UpdateQueryBuilderCls =
  3636. + require('typeorm/browser/query-builder/UpdateQueryBuilder').UpdateQueryBuilder;
  3637. + if (InstanceChecker.isUpdateQueryBuilder(this)) return this;
  3638. + return new UpdateQueryBuilderCls(this);
  3639. + }
  3640. + /**
  3641. + * Creates DELETE query.
  3642. + */
  3643. + delete() {
  3644. + this.expressionMap.queryType = 'delete';
  3645. + // loading it dynamically because of circular issue
  3646. + const DeleteQueryBuilderCls =
  3647. + require('typeorm/browser/query-builder/DeleteQueryBuilder').DeleteQueryBuilder;
  3648. + if (InstanceChecker.isDeleteQueryBuilder(this)) return this;
  3649. + return new DeleteQueryBuilderCls(this);
  3650. + }
  3651. + softDelete() {
  3652. + this.expressionMap.queryType = 'soft-delete';
  3653. + // loading it dynamically because of circular issue
  3654. + const SoftDeleteQueryBuilderCls =
  3655. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  3656. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  3657. + return new SoftDeleteQueryBuilderCls(this);
  3658. + }
  3659. + restore() {
  3660. + this.expressionMap.queryType = 'restore';
  3661. + // loading it dynamically because of circular issue
  3662. + const SoftDeleteQueryBuilderCls =
  3663. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  3664. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  3665. + return new SoftDeleteQueryBuilderCls(this);
  3666. + }
  3667. + /**
  3668. + * Sets entity's relation with which this query builder gonna work.
  3669. + */
  3670. + relation(entityTargetOrPropertyPath, maybePropertyPath) {
  3671. + const entityTarget =
  3672. + arguments.length === 2 ? entityTargetOrPropertyPath : undefined;
  3673. + const propertyPath =
  3674. + arguments.length === 2 ? maybePropertyPath : entityTargetOrPropertyPath;
  3675. + this.expressionMap.queryType = 'relation';
  3676. + this.expressionMap.relationPropertyPath = propertyPath;
  3677. + if (entityTarget) {
  3678. + const mainAlias = this.createFromAlias(entityTarget);
  3679. + this.expressionMap.setMainAlias(mainAlias);
  3680. + }
  3681. + // loading it dynamically because of circular issue
  3682. + const RelationQueryBuilderCls =
  3683. + require('typeorm/browser/query-builder/RelationQueryBuilder').RelationQueryBuilder;
  3684. + if (InstanceChecker.isRelationQueryBuilder(this)) return this;
  3685. + return new RelationQueryBuilderCls(this);
  3686. + }
  3687. + /**
  3688. + * Checks if given relation or relations exist in the entity.
  3689. + * Returns true if relation exists, false otherwise.
  3690. + *
  3691. + * todo: move this method to manager? or create a shortcut?
  3692. + */
  3693. + hasRelation(target, relation) {
  3694. + const entityMetadata = this.connection.getMetadata(target);
  3695. + const relations = Array.isArray(relation) ? relation : [relation];
  3696. + return relations.every((relation) => {
  3697. + return !!entityMetadata.findRelationWithPropertyPath(relation);
  3698. + });
  3699. + }
  3700. + /**
  3701. + * Check the existence of a parameter for this query builder.
  3702. + */
  3703. + hasParameter(key) {
  3704. + var _a;
  3705. + return (
  3706. + ((_a = this.parentQueryBuilder) === null || _a === void 0
  3707. + ? void 0
  3708. + : _a.hasParameter(key)) || key in this.expressionMap.parameters
  3709. + );
  3710. + }
  3711. + /**
  3712. + * Sets parameter name and its value.
  3713. + *
  3714. + * The key for this parameter may contain numbers, letters, underscores, or periods.
  3715. + */
  3716. + setParameter(key, value) {
  3717. + if (typeof value === 'function') {
  3718. + throw new TypeORMError(
  3719. + `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`
  3720. + );
  3721. + }
  3722. + if (!key.match(/^([A-Za-z0-9_.]+)$/)) {
  3723. + throw new TypeORMError(
  3724. + 'QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.'
  3725. + );
  3726. + }
  3727. + if (this.parentQueryBuilder) {
  3728. + this.parentQueryBuilder.setParameter(key, value);
  3729. + }
  3730. + this.expressionMap.parameters[key] = value;
  3731. + return this;
  3732. + }
  3733. + /**
  3734. + * Adds all parameters from the given object.
  3735. + */
  3736. + setParameters(parameters) {
  3737. + for (const [key, value] of Object.entries(parameters)) {
  3738. + this.setParameter(key, value);
  3739. + }
  3740. + return this;
  3741. + }
  3742. + createParameter(value) {
  3743. + let parameterName;
  3744. + do {
  3745. + parameterName = `orm_param_${this.parameterIndex++}`;
  3746. + } while (this.hasParameter(parameterName));
  3747. + this.setParameter(parameterName, value);
  3748. + return `:${parameterName}`;
  3749. + }
  3750. + /**
  3751. + * Adds native parameters from the given object.
  3752. + *
  3753. + * @deprecated Use `setParameters` instead
  3754. + */
  3755. + setNativeParameters(parameters) {
  3756. + // set parent query builder parameters as well in sub-query mode
  3757. + if (this.parentQueryBuilder) {
  3758. + this.parentQueryBuilder.setNativeParameters(parameters);
  3759. + }
  3760. + Object.keys(parameters).forEach((key) => {
  3761. + this.expressionMap.nativeParameters[key] = parameters[key];
  3762. + });
  3763. + return this;
  3764. + }
  3765. + /**
  3766. + * Gets all parameters.
  3767. + */
  3768. + getParameters() {
  3769. + const parameters = Object.assign({}, this.expressionMap.parameters);
  3770. + // add discriminator column parameter if it exist
  3771. + if (
  3772. + this.expressionMap.mainAlias &&
  3773. + this.expressionMap.mainAlias.hasMetadata
  3774. + ) {
  3775. + const metadata = this.expressionMap.mainAlias.metadata;
  3776. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  3777. + const values = metadata.childEntityMetadatas
  3778. + .filter((childMetadata) => childMetadata.discriminatorColumn)
  3779. + .map((childMetadata) => childMetadata.discriminatorValue);
  3780. + values.push(metadata.discriminatorValue);
  3781. + parameters['discriminatorColumnValues'] = values;
  3782. + }
  3783. + }
  3784. + return parameters;
  3785. + }
  3786. + /**
  3787. + * Prints sql to stdout using console.log.
  3788. + */
  3789. + printSql() {
  3790. + // TODO rename to logSql()
  3791. + const [query, parameters] = this.getQueryAndParameters();
  3792. + this.connection.logger.logQuery(query, parameters);
  3793. + return this;
  3794. + }
  3795. + /**
  3796. + * Gets generated sql that will be executed.
  3797. + * Parameters in the query are escaped for the currently used driver.
  3798. + */
  3799. + getSql() {
  3800. + return this.getQueryAndParameters()[0];
  3801. + }
  3802. + /**
  3803. + * Gets query to be executed with all parameters used in it.
  3804. + */
  3805. + getQueryAndParameters() {
  3806. + // this execution order is important because getQuery method generates this.expressionMap.nativeParameters values
  3807. + const query = this.getQuery();
  3808. + const parameters = this.getParameters();
  3809. + return this.connection.driver.escapeQueryWithParameters(
  3810. + query,
  3811. + parameters,
  3812. + this.expressionMap.nativeParameters
  3813. + );
  3814. + }
  3815. + /**
  3816. + * Executes sql generated by query builder and returns raw database results.
  3817. + */
  3818. + async execute() {
  3819. + const [sql, parameters] = this.getQueryAndParameters();
  3820. + const queryRunner = this.obtainQueryRunner();
  3821. + try {
  3822. + return await queryRunner.query(sql, parameters); // await is needed here because we are using finally
  3823. + } finally {
  3824. + if (queryRunner !== this.queryRunner) {
  3825. + // means we created our own query runner
  3826. + await queryRunner.release();
  3827. + }
  3828. + }
  3829. + }
  3830. + /**
  3831. + * Creates a completely new query builder.
  3832. + * Uses same query runner as current QueryBuilder.
  3833. + */
  3834. + createQueryBuilder() {
  3835. + return new this.constructor(this.connection, this.queryRunner);
  3836. + }
  3837. + /**
  3838. + * Clones query builder as it is.
  3839. + * Note: it uses new query runner, if you want query builder that uses exactly same query runner,
  3840. + * you can create query builder using its constructor, for example new SelectQueryBuilder(queryBuilder)
  3841. + * where queryBuilder is cloned QueryBuilder.
  3842. + */
  3843. + clone() {
  3844. + return new this.constructor(this);
  3845. + }
  3846. + /**
  3847. + * Includes a Query comment in the query builder. This is helpful for debugging purposes,
  3848. + * such as finding a specific query in the database server's logs, or for categorization using
  3849. + * an APM product.
  3850. + */
  3851. + comment(comment) {
  3852. + this.expressionMap.comment = comment;
  3853. + return this;
  3854. + }
  3855. + /**
  3856. + * Disables escaping.
  3857. + */
  3858. + disableEscaping() {
  3859. + this.expressionMap.disableEscaping = false;
  3860. + return this;
  3861. + }
  3862. + /**
  3863. + * Escapes table name, column name or alias name using current database's escaping character.
  3864. + */
  3865. + escape(name) {
  3866. + if (!this.expressionMap.disableEscaping) return name;
  3867. + return this.connection.driver.escape(name);
  3868. + }
  3869. + /**
  3870. + * Sets or overrides query builder's QueryRunner.
  3871. + */
  3872. + setQueryRunner(queryRunner) {
  3873. + this.queryRunner = queryRunner;
  3874. + return this;
  3875. + }
  3876. + /**
  3877. + * Indicates if listeners and subscribers must be called before and after query execution.
  3878. + * Enabled by default.
  3879. + */
  3880. + callListeners(enabled) {
  3881. + this.expressionMap.callListeners = enabled;
  3882. + return this;
  3883. + }
  3884. + /**
  3885. + * If set to true the query will be wrapped into a transaction.
  3886. + */
  3887. + useTransaction(enabled) {
  3888. + this.expressionMap.useTransaction = enabled;
  3889. + return this;
  3890. + }
  3891. + /**
  3892. + * Adds CTE to query
  3893. + */
  3894. + addCommonTableExpression(queryBuilder, alias, options) {
  3895. + this.expressionMap.commonTableExpressions.push({
  3896. + queryBuilder,
  3897. + alias,
  3898. + options: options || {},
  3899. + });
  3900. + return this;
  3901. + }
  3902. + // -------------------------------------------------------------------------
  3903. + // Protected Methods
  3904. + // -------------------------------------------------------------------------
  3905. + /**
  3906. + * Gets escaped table name with schema name if SqlServer driver used with custom
  3907. + * schema name, otherwise returns escaped table name.
  3908. + */
  3909. + getTableName(tablePath) {
  3910. + return tablePath
  3911. + .split('.')
  3912. + .map((i) => {
  3913. + // this condition need because in SQL Server driver when custom database name was specified and schema name was not, we got `dbName..tableName` string, and doesn't need to escape middle empty string
  3914. + if (i === '') return i;
  3915. + return this.escape(i);
  3916. + })
  3917. + .join('.');
  3918. + }
  3919. + /**
  3920. + * Gets name of the table where insert should be performed.
  3921. + */
  3922. + getMainTableName() {
  3923. + if (!this.expressionMap.mainAlias)
  3924. + throw new TypeORMError(
  3925. + `Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.`
  3926. + );
  3927. + if (this.expressionMap.mainAlias.hasMetadata)
  3928. + return this.expressionMap.mainAlias.metadata.tablePath;
  3929. + return this.expressionMap.mainAlias.tablePath;
  3930. + }
  3931. + /**
  3932. + * Specifies FROM which entity's table select/update/delete will be executed.
  3933. + * Also sets a main string alias of the selection data.
  3934. + */
  3935. + createFromAlias(entityTarget, aliasName) {
  3936. + // if table has a metadata then find it to properly escape its properties
  3937. + // const metadata = this.connection.entityMetadatas.find(metadata => metadata.tableName === tableName);
  3938. + if (this.connection.hasMetadata(entityTarget)) {
  3939. + const metadata = this.connection.getMetadata(entityTarget);
  3940. + return this.expressionMap.createAlias({
  3941. + type: 'from',
  3942. + name: aliasName,
  3943. + metadata: this.connection.getMetadata(entityTarget),
  3944. + tablePath: metadata.tablePath,
  3945. + });
  3946. + } else {
  3947. + if (typeof entityTarget === 'string') {
  3948. + const isSubquery =
  3949. + entityTarget.substr(0, 1) === '(' && entityTarget.substr(-1) === ')';
  3950. + return this.expressionMap.createAlias({
  3951. + type: 'from',
  3952. + name: aliasName,
  3953. + tablePath: !isSubquery ? entityTarget : undefined,
  3954. + subQuery: isSubquery ? entityTarget : undefined,
  3955. + });
  3956. + }
  3957. + const subQueryBuilder = entityTarget(this.subQuery());
  3958. + this.setParameters(subQueryBuilder.getParameters());
  3959. + const subquery = subQueryBuilder.getQuery();
  3960. + return this.expressionMap.createAlias({
  3961. + type: 'from',
  3962. + name: aliasName,
  3963. + subQuery: subquery,
  3964. + });
  3965. + }
  3966. + }
  3967. + /**
  3968. + * Replaces all entity's propertyName to name in the given statement.
  3969. + */
  3970. + replacePropertyNames(statement) {
  3971. + for (const alias of this.expressionMap.aliases) {
  3972. + if (!alias.hasMetadata) continue;
  3973. + const replaceAliasNamePrefix = this.expressionMap
  3974. + .aliasNamePrefixingEnabled
  3975. + ? `${alias.name}.`
  3976. + : '';
  3977. + const replacementAliasNamePrefix = this.expressionMap
  3978. + .aliasNamePrefixingEnabled
  3979. + ? `${this.escape(alias.name)}.`
  3980. + : '';
  3981. + const replacements = {};
  3982. + // Insert & overwrite the replacements from least to most relevant in our replacements object.
  3983. + // To do this we iterate and overwrite in the order of relevance.
  3984. + // Least to Most Relevant:
  3985. + // * Relation Property Path to first join column key
  3986. + // * Relation Property Path + Column Path
  3987. + // * Column Database Name
  3988. + // * Column Property Name
  3989. + // * Column Property Path
  3990. + for (const relation of alias.metadata.relations) {
  3991. + if (relation.joinColumns.length > 0)
  3992. + replacements[relation.propertyPath] =
  3993. + relation.joinColumns[0].databaseName;
  3994. + }
  3995. + for (const relation of alias.metadata.relations) {
  3996. + for (const joinColumn of [
  3997. + ...relation.joinColumns,
  3998. + ...relation.inverseJoinColumns,
  3999. + ]) {
  4000. + const propertyKey = `${relation.propertyPath}.${joinColumn.referencedColumn.propertyPath}`;
  4001. + replacements[propertyKey] = joinColumn.databaseName;
  4002. + }
  4003. + }
  4004. + for (const column of alias.metadata.columns) {
  4005. + replacements[column.databaseName] = column.databaseName;
  4006. + }
  4007. + for (const column of alias.metadata.columns) {
  4008. + replacements[column.propertyName] = column.databaseName;
  4009. + }
  4010. + for (const column of alias.metadata.columns) {
  4011. + replacements[column.propertyPath] = column.databaseName;
  4012. + }
  4013. + statement = statement.replace(
  4014. + new RegExp(
  4015. + // Avoid a lookbehind here since it's not well supported
  4016. + `([ =\(]|^.{0})` + // any of ' =(' or start of line
  4017. + // followed by our prefix, e.g. 'tablename.' or ''
  4018. + `${escapeRegExp(replaceAliasNamePrefix)}([^ =\(\)\,]+)` + // a possible property name: sequence of anything but ' =(),'
  4019. + // terminated by ' =),' or end of line
  4020. + `(?=[ =\)\,]|.{0}$)`,
  4021. + 'gm'
  4022. + ),
  4023. + (match, pre, p) => {
  4024. + if (replacements[p]) {
  4025. + return `${pre}${replacementAliasNamePrefix}${this.escape(
  4026. + replacements[p]
  4027. + )}`;
  4028. + }
  4029. + return match;
  4030. + }
  4031. + );
  4032. + }
  4033. + return statement;
  4034. + }
  4035. + createComment() {
  4036. + if (!this.expressionMap.comment) {
  4037. + return '';
  4038. + }
  4039. + // ANSI SQL 2003 support C style comments - comments that start with `/*` and end with `*/`
  4040. + // In some dialects query nesting is available - but not all. Because of this, we'll need
  4041. + // to scrub "ending" characters from the SQL but otherwise we can leave everything else
  4042. + // as-is and it should be valid.
  4043. + return `/* ${this.expressionMap.comment.replace('*/', '')} */ `;
  4044. + }
  4045. + /**
  4046. + * Creates "WHERE" expression.
  4047. + */
  4048. + createWhereExpression() {
  4049. + const conditionsArray = [];
  4050. + const whereExpression = this.createWhereClausesExpression(
  4051. + this.expressionMap.wheres
  4052. + );
  4053. + if (whereExpression.length > 0 && whereExpression !== '1=1') {
  4054. + conditionsArray.push(this.replacePropertyNames(whereExpression));
  4055. + }
  4056. + if (this.expressionMap.mainAlias.hasMetadata) {
  4057. + const metadata = this.expressionMap.mainAlias.metadata;
  4058. + // Adds the global condition of "non-deleted" for the entity with delete date columns in select query.
  4059. + if (
  4060. + this.expressionMap.queryType === 'select' &&
  4061. + !this.expressionMap.withDeleted &&
  4062. + metadata.deleteDateColumn
  4063. + ) {
  4064. + const column = this.expressionMap.aliasNamePrefixingEnabled
  4065. + ? this.expressionMap.mainAlias.name +
  4066. + '.' +
  4067. + metadata.deleteDateColumn.propertyName
  4068. + : metadata.deleteDateColumn.propertyName;
  4069. + const condition = `${this.replacePropertyNames(column)} IS NULL`;
  4070. + conditionsArray.push(condition);
  4071. + }
  4072. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  4073. + const column = this.expressionMap.aliasNamePrefixingEnabled
  4074. + ? this.expressionMap.mainAlias.name +
  4075. + '.' +
  4076. + metadata.discriminatorColumn.databaseName
  4077. + : metadata.discriminatorColumn.databaseName;
  4078. + const condition = `${this.replacePropertyNames(
  4079. + column
  4080. + )} IN (:...discriminatorColumnValues)`;
  4081. + conditionsArray.push(condition);
  4082. + }
  4083. + }
  4084. + if (this.expressionMap.extraAppendedAndWhereCondition) {
  4085. + const condition = this.replacePropertyNames(
  4086. + this.expressionMap.extraAppendedAndWhereCondition
  4087. + );
  4088. + conditionsArray.push(condition);
  4089. + }
  4090. + if (!conditionsArray.length) {
  4091. + return '';
  4092. + } else if (conditionsArray.length === 1) {
  4093. + return ` WHERE ${conditionsArray[0]}`;
  4094. + } else {
  4095. + return ` WHERE ( ${conditionsArray.join(' ) AND ( ')} )`;
  4096. + }
  4097. + }
  4098. + /**
  4099. + * Creates "RETURNING" / "OUTPUT" expression.
  4100. + */
  4101. + createReturningExpression(returningType) {
  4102. + const columns = this.getReturningColumns();
  4103. + const driver = this.connection.driver;
  4104. + // also add columns we must auto-return to perform entity updation
  4105. + // if user gave his own returning
  4106. + if (
  4107. + typeof this.expressionMap.returning !== 'string' &&
  4108. + this.expressionMap.extraReturningColumns.length > 0 &&
  4109. + driver.isReturningSqlSupported(returningType)
  4110. + ) {
  4111. + columns.push(
  4112. + ...this.expressionMap.extraReturningColumns.filter((column) => {
  4113. + return columns.indexOf(column) === -1;
  4114. + })
  4115. + );
  4116. + }
  4117. + if (columns.length) {
  4118. + let columnsExpression = columns
  4119. + .map((column) => {
  4120. + const name = this.escape(column.databaseName);
  4121. + if (driver.options.type === 'mssql') {
  4122. + if (
  4123. + this.expressionMap.queryType === 'insert' ||
  4124. + this.expressionMap.queryType === 'update' ||
  4125. + this.expressionMap.queryType === 'soft-delete' ||
  4126. + this.expressionMap.queryType === 'restore'
  4127. + ) {
  4128. + return 'INSERTED.' + name;
  4129. + } else {
  4130. + return this.escape(this.getMainTableName()) + '.' + name;
  4131. + }
  4132. + } else {
  4133. + return name;
  4134. + }
  4135. + })
  4136. + .join(', ');
  4137. + if (driver.options.type === 'oracle') {
  4138. + columnsExpression +=
  4139. + ' INTO ' +
  4140. + columns
  4141. + .map((column) => {
  4142. + return this.createParameter({
  4143. + type: driver.columnTypeToNativeParameter(column.type),
  4144. + dir: driver.oracle.BIND_OUT,
  4145. + });
  4146. + })
  4147. + .join(', ');
  4148. + }
  4149. + if (driver.options.type === 'mssql') {
  4150. + if (
  4151. + this.expressionMap.queryType === 'insert' ||
  4152. + this.expressionMap.queryType === 'update'
  4153. + ) {
  4154. + columnsExpression += ' INTO @OutputTable';
  4155. + }
  4156. + }
  4157. + return columnsExpression;
  4158. + } else if (typeof this.expressionMap.returning === 'string') {
  4159. + return this.expressionMap.returning;
  4160. + }
  4161. + return '';
  4162. + }
  4163. + /**
  4164. + * If returning / output cause is set to array of column names,
  4165. + * then this method will return all column metadatas of those column names.
  4166. + */
  4167. + getReturningColumns() {
  4168. + const columns = [];
  4169. + if (Array.isArray(this.expressionMap.returning)) {
  4170. + this.expressionMap.returning.forEach((columnName) => {
  4171. + if (this.expressionMap.mainAlias.hasMetadata) {
  4172. + columns.push(
  4173. + ...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(
  4174. + columnName
  4175. + )
  4176. + );
  4177. + }
  4178. + });
  4179. + }
  4180. + return columns;
  4181. + }
  4182. + createWhereClausesExpression(clauses) {
  4183. + return clauses
  4184. + .map((clause, index) => {
  4185. + const expression = this.createWhereConditionExpression(
  4186. + clause.condition
  4187. + );
  4188. + switch (clause.type) {
  4189. + case 'and':
  4190. + return (index > 0 ? 'AND ' : '') + expression;
  4191. + case 'or':
  4192. + return (index > 0 ? 'OR ' : '') + expression;
  4193. + }
  4194. + return expression;
  4195. + })
  4196. + .join(' ')
  4197. + .trim();
  4198. + }
  4199. + /**
  4200. + * Computes given where argument - transforms to a where string all forms it can take.
  4201. + */
  4202. + createWhereConditionExpression(condition, alwaysWrap = false) {
  4203. + if (typeof condition === 'string') return condition;
  4204. + if (Array.isArray(condition)) {
  4205. + if (condition.length === 0) {
  4206. + return '1=1';
  4207. + }
  4208. + // In the future we should probably remove this entire condition
  4209. + // but for now to prevent any breaking changes it exists.
  4210. + if (condition.length === 1 && !alwaysWrap) {
  4211. + return this.createWhereClausesExpression(condition);
  4212. + }
  4213. + return '(' + this.createWhereClausesExpression(condition) + ')';
  4214. + }
  4215. + const { driver } = this.connection;
  4216. + switch (condition.operator) {
  4217. + case 'lessThan':
  4218. + return `${condition.parameters[0]} < ${condition.parameters[1]}`;
  4219. + case 'lessThanOrEqual':
  4220. + return `${condition.parameters[0]} <= ${condition.parameters[1]}`;
  4221. + case 'arrayContains':
  4222. + return `${condition.parameters[0]} @> ${condition.parameters[1]}`;
  4223. + case 'arrayContainedBy':
  4224. + return `${condition.parameters[0]} <@ ${condition.parameters[1]}`;
  4225. + case 'arrayOverlap':
  4226. + return `${condition.parameters[0]} && ${condition.parameters[1]}`;
  4227. + case 'moreThan':
  4228. + return `${condition.parameters[0]} > ${condition.parameters[1]}`;
  4229. + case 'moreThanOrEqual':
  4230. + return `${condition.parameters[0]} >= ${condition.parameters[1]}`;
  4231. + case 'notEqual':
  4232. + return `${condition.parameters[0]} != ${condition.parameters[1]}`;
  4233. + case 'equal':
  4234. + return `${condition.parameters[0]} = ${condition.parameters[1]}`;
  4235. + case 'ilike':
  4236. + if (
  4237. + driver.options.type === 'postgres' ||
  4238. + driver.options.type === 'cockroachdb'
  4239. + ) {
  4240. + return `${condition.parameters[0]} ILIKE ${condition.parameters[1]}`;
  4241. + }
  4242. + return `UPPER(${condition.parameters[0]}) LIKE UPPER(${condition.parameters[1]})`;
  4243. + case 'like':
  4244. + return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`;
  4245. + case 'between':
  4246. + return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`;
  4247. + case 'in':
  4248. + if (condition.parameters.length <= 1) {
  4249. + return '0=1';
  4250. + }
  4251. + return `${condition.parameters[0]} IN (${condition.parameters
  4252. + .slice(1)
  4253. + .join(', ')})`;
  4254. + case 'any':
  4255. + return `${condition.parameters[0]} = ANY(${condition.parameters[1]})`;
  4256. + case 'isNull':
  4257. + return `${condition.parameters[0]} IS NULL`;
  4258. + case 'not':
  4259. + return `NOT(${this.createWhereConditionExpression(
  4260. + condition.condition
  4261. + )})`;
  4262. + case 'brackets':
  4263. + return `${this.createWhereConditionExpression(
  4264. + condition.condition,
  4265. + true
  4266. + )}`;
  4267. + }
  4268. + throw new TypeError(
  4269. + `Unsupported FindOperator ${FindOperator.constructor.name}`
  4270. + );
  4271. + }
  4272. + createCteExpression() {
  4273. + if (!this.hasCommonTableExpressions()) {
  4274. + return '';
  4275. + }
  4276. + const databaseRequireRecusiveHint =
  4277. + this.connection.driver.cteCapabilities.requiresRecursiveHint;
  4278. + const cteStrings = this.expressionMap.commonTableExpressions.map((cte) => {
  4279. + const cteBodyExpression =
  4280. + typeof cte.queryBuilder === 'string'
  4281. + ? cte.queryBuilder
  4282. + : cte.queryBuilder.getQuery();
  4283. + if (typeof cte.queryBuilder !== 'string') {
  4284. + if (cte.queryBuilder.hasCommonTableExpressions()) {
  4285. + throw new TypeORMError(
  4286. + `Nested CTEs aren't supported (CTE: ${cte.alias})`
  4287. + );
  4288. + }
  4289. + if (
  4290. + !this.connection.driver.cteCapabilities.writable &&
  4291. + !InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
  4292. + ) {
  4293. + throw new TypeORMError(
  4294. + `Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${cte.alias})`
  4295. + );
  4296. + }
  4297. + this.setParameters(cte.queryBuilder.getParameters());
  4298. + }
  4299. + let cteHeader = this.escape(cte.alias);
  4300. + if (cte.options.columnNames) {
  4301. + const escapedColumnNames = cte.options.columnNames.map((column) =>
  4302. + this.escape(column)
  4303. + );
  4304. + if (InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)) {
  4305. + if (
  4306. + cte.queryBuilder.expressionMap.selects.length &&
  4307. + cte.options.columnNames.length !==
  4308. + cte.queryBuilder.expressionMap.selects.length
  4309. + ) {
  4310. + throw new TypeORMError(
  4311. + `cte.options.columnNames length (${cte.options.columnNames.length}) doesn't match subquery select list length ${cte.queryBuilder.expressionMap.selects.length} (CTE: ${cte.alias})`
  4312. + );
  4313. + }
  4314. + }
  4315. + cteHeader += `(${escapedColumnNames.join(', ')})`;
  4316. + }
  4317. + const recursiveClause =
  4318. + cte.options.recursive && databaseRequireRecusiveHint ? 'RECURSIVE' : '';
  4319. + const materializeClause =
  4320. + cte.options.materialized &&
  4321. + this.connection.driver.cteCapabilities.materializedHint
  4322. + ? 'MATERIALIZED'
  4323. + : '';
  4324. + return [
  4325. + recursiveClause,
  4326. + cteHeader,
  4327. + materializeClause,
  4328. + 'AS',
  4329. + `(${cteBodyExpression})`,
  4330. + ]
  4331. + .filter(Boolean)
  4332. + .join(' ');
  4333. + });
  4334. + return 'WITH ' + cteStrings.join(', ') + ' ';
  4335. + }
  4336. + /**
  4337. + * Creates "WHERE" condition for an in-ids condition.
  4338. + */
  4339. + getWhereInIdsCondition(ids) {
  4340. + const metadata = this.expressionMap.mainAlias.metadata;
  4341. + const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
  4342. + metadata.ensureEntityIdMap(id)
  4343. + );
  4344. + // using in(...ids) for single primary key entities
  4345. + if (!metadata.hasMultiplePrimaryKeys) {
  4346. + const primaryColumn = metadata.primaryColumns[0];
  4347. + // getEntityValue will try to transform `In`, it is a bug
  4348. + // todo: remove this transformer check after #2390 is fixed
  4349. + // This also fails for embedded & relation, so until that is fixed skip it.
  4350. + if (
  4351. + !primaryColumn.transformer &&
  4352. + !primaryColumn.relationMetadata &&
  4353. + !primaryColumn.embeddedMetadata
  4354. + ) {
  4355. + return {
  4356. + [primaryColumn.propertyName]: In(
  4357. + normalized.map((id) => primaryColumn.getEntityValue(id, false))
  4358. + ),
  4359. + };
  4360. + }
  4361. + }
  4362. + return new Brackets((qb) => {
  4363. + for (const data of normalized) {
  4364. + qb.orWhere(new Brackets((qb) => qb.where(data)));
  4365. + }
  4366. + });
  4367. + }
  4368. + findColumnsForPropertyPath(propertyPath) {
  4369. + // Make a helper to iterate the entity & relations?
  4370. + // Use that to set the correct alias? Or the other way around?
  4371. + // Start with the main alias with our property paths
  4372. + let alias = this.expressionMap.mainAlias;
  4373. + const root = [];
  4374. + const propertyPathParts = propertyPath.split('.');
  4375. + while (propertyPathParts.length > 1) {
  4376. + const part = propertyPathParts[0];
  4377. + if (!(alias === null || alias === void 0 ? void 0 : alias.hasMetadata)) {
  4378. + // If there's no metadata, we're wasting our time
  4379. + // and can't actually look any of this up.
  4380. + break;
  4381. + }
  4382. + if (alias.metadata.hasEmbeddedWithPropertyPath(part)) {
  4383. + // If this is an embedded then we should combine the two as part of our lookup.
  4384. + // Instead of just breaking, we keep going with this in case there's an embedded/relation
  4385. + // inside an embedded.
  4386. + propertyPathParts.unshift(
  4387. + `${propertyPathParts.shift()}.${propertyPathParts.shift()}`
  4388. + );
  4389. + continue;
  4390. + }
  4391. + if (alias.metadata.hasRelationWithPropertyPath(part)) {
  4392. + // If this is a relation then we should find the aliases
  4393. + // that match the relation & then continue further down
  4394. + // the property path
  4395. + const joinAttr = this.expressionMap.joinAttributes.find(
  4396. + (joinAttr) => joinAttr.relationPropertyPath === part
  4397. + );
  4398. + if (
  4399. + !(joinAttr === null || joinAttr === void 0 ? void 0 : joinAttr.alias)
  4400. + ) {
  4401. + const fullRelationPath =
  4402. + root.length > 0 ? `${root.join('.')}.${part}` : part;
  4403. + throw new Error(
  4404. + `Cannot find alias for relation at ${fullRelationPath}`
  4405. + );
  4406. + }
  4407. + alias = joinAttr.alias;
  4408. + root.push(...part.split('.'));
  4409. + propertyPathParts.shift();
  4410. + continue;
  4411. + }
  4412. + break;
  4413. + }
  4414. + if (!alias) {
  4415. + throw new Error(`Cannot find alias for property ${propertyPath}`);
  4416. + }
  4417. + // Remaining parts are combined back and used to find the actual property path
  4418. + const aliasPropertyPath = propertyPathParts.join('.');
  4419. + const columns =
  4420. + alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath);
  4421. + if (!columns.length) {
  4422. + throw new EntityPropertyNotFoundError(propertyPath, alias.metadata);
  4423. + }
  4424. + return [alias, root, columns];
  4425. + }
  4426. + /**
  4427. + * Creates a property paths for a given ObjectLiteral.
  4428. + */
  4429. + createPropertyPath(metadata, entity, prefix = '') {
  4430. + const paths = [];
  4431. + for (const key of Object.keys(entity)) {
  4432. + const path = prefix ? `${prefix}.${key}` : key;
  4433. + // There's times where we don't actually want to traverse deeper.
  4434. + // If the value is a `FindOperator`, or null, or not an object, then we don't, for example.
  4435. + if (
  4436. + entity[key] === null ||
  4437. + typeof entity[key] !== 'object' ||
  4438. + InstanceChecker.isFindOperator(entity[key])
  4439. + ) {
  4440. + paths.push(path);
  4441. + continue;
  4442. + }
  4443. + if (metadata.hasEmbeddedWithPropertyPath(path)) {
  4444. + const subPaths = this.createPropertyPath(metadata, entity[key], path);
  4445. + paths.push(...subPaths);
  4446. + continue;
  4447. + }
  4448. + if (metadata.hasRelationWithPropertyPath(path)) {
  4449. + const relation = metadata.findRelationWithPropertyPath(path);
  4450. + // There's also cases where we don't want to return back all of the properties.
  4451. + // These handles the situation where someone passes the model & we don't need to make
  4452. + // a HUGE `where` to uniquely look up the entity.
  4453. + // In the case of a *-to-one, there's only ever one possible entity on the other side
  4454. + // so if the join columns are all defined we can return just the relation itself
  4455. + // because it will fetch only the join columns and do the lookup.
  4456. + if (
  4457. + relation.relationType === 'one-to-one' ||
  4458. + relation.relationType === 'many-to-one'
  4459. + ) {
  4460. + const joinColumns = relation.joinColumns
  4461. + .map((j) => j.referencedColumn)
  4462. + .filter((j) => !!j);
  4463. + const hasAllJoinColumns =
  4464. + joinColumns.length > 0 &&
  4465. + joinColumns.every((column) =>
  4466. + column.getEntityValue(entity[key], false)
  4467. + );
  4468. + if (hasAllJoinColumns) {
  4469. + paths.push(path);
  4470. + continue;
  4471. + }
  4472. + }
  4473. + if (
  4474. + relation.relationType === 'one-to-many' ||
  4475. + relation.relationType === 'many-to-many'
  4476. + ) {
  4477. + throw new Error(
  4478. + `Cannot query across ${relation.relationType} for property ${path}`
  4479. + );
  4480. + }
  4481. + // For any other case, if the `entity[key]` contains all of the primary keys we can do a
  4482. + // lookup via these. We don't need to look up via any other values 'cause these are
  4483. + // the unique primary keys.
  4484. + // This handles the situation where someone passes the model & we don't need to make
  4485. + // a HUGE where.
  4486. + const primaryColumns = relation.inverseEntityMetadata.primaryColumns;
  4487. + const hasAllPrimaryKeys =
  4488. + primaryColumns.length > 0 &&
  4489. + primaryColumns.every((column) =>
  4490. + column.getEntityValue(entity[key], false)
  4491. + );
  4492. + if (hasAllPrimaryKeys) {
  4493. + const subPaths = primaryColumns.map(
  4494. + (column) => `${path}.${column.propertyPath}`
  4495. + );
  4496. + paths.push(...subPaths);
  4497. + continue;
  4498. + }
  4499. + // If nothing else, just return every property that's being passed to us.
  4500. + const subPaths = this.createPropertyPath(
  4501. + relation.inverseEntityMetadata,
  4502. + entity[key]
  4503. + ).map((p) => `${path}.${p}`);
  4504. + paths.push(...subPaths);
  4505. + continue;
  4506. + }
  4507. + paths.push(path);
  4508. + }
  4509. + return paths;
  4510. + }
  4511. + *getPredicates(where) {
  4512. + if (this.expressionMap.mainAlias.hasMetadata) {
  4513. + const propertyPaths = this.createPropertyPath(
  4514. + this.expressionMap.mainAlias.metadata,
  4515. + where
  4516. + );
  4517. + for (const propertyPath of propertyPaths) {
  4518. + const [alias, aliasPropertyPath, columns] =
  4519. + this.findColumnsForPropertyPath(propertyPath);
  4520. + for (const column of columns) {
  4521. + let containedWhere = where;
  4522. + for (const part of aliasPropertyPath) {
  4523. + if (!containedWhere || !(part in containedWhere)) {
  4524. + containedWhere = {};
  4525. + break;
  4526. + }
  4527. + containedWhere = containedWhere[part];
  4528. + }
  4529. + // Use the correct alias & the property path from the column
  4530. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  4531. + ? `${alias.name}.${column.propertyPath}`
  4532. + : column.propertyPath;
  4533. + const parameterValue = column.getEntityValue(containedWhere, true);
  4534. + yield [aliasPath, parameterValue];
  4535. + }
  4536. + }
  4537. + } else {
  4538. + for (const key of Object.keys(where)) {
  4539. + const parameterValue = where[key];
  4540. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  4541. + ? `${this.alias}.${key}`
  4542. + : key;
  4543. + yield [aliasPath, parameterValue];
  4544. + }
  4545. + }
  4546. + }
  4547. + getWherePredicateCondition(aliasPath, parameterValue) {
  4548. + if (InstanceChecker.isFindOperator(parameterValue)) {
  4549. + let parameters = [];
  4550. + if (parameterValue.useParameter) {
  4551. + if (parameterValue.objectLiteralParameters) {
  4552. + this.setParameters(parameterValue.objectLiteralParameters);
  4553. + } else if (parameterValue.multipleParameters) {
  4554. + for (const v of parameterValue.value) {
  4555. + parameters.push(this.createParameter(v));
  4556. + }
  4557. + } else {
  4558. + parameters.push(this.createParameter(parameterValue.value));
  4559. + }
  4560. + }
  4561. + if (parameterValue.type === 'raw') {
  4562. + if (parameterValue.getSql) {
  4563. + return parameterValue.getSql(aliasPath);
  4564. + } else {
  4565. + return {
  4566. + operator: 'equal',
  4567. + parameters: [aliasPath, parameterValue.value],
  4568. + };
  4569. + }
  4570. + } else if (parameterValue.type === 'not') {
  4571. + if (parameterValue.child) {
  4572. + return {
  4573. + operator: parameterValue.type,
  4574. + condition: this.getWherePredicateCondition(
  4575. + aliasPath,
  4576. + parameterValue.child
  4577. + ),
  4578. + };
  4579. + } else {
  4580. + return {
  4581. + operator: 'notEqual',
  4582. + parameters: [aliasPath, ...parameters],
  4583. + };
  4584. + }
  4585. + } else {
  4586. + return {
  4587. + operator: parameterValue.type,
  4588. + parameters: [aliasPath, ...parameters],
  4589. + };
  4590. + }
  4591. + // } else if (parameterValue === null) {
  4592. + // return {
  4593. + // operator: "isNull",
  4594. + // parameters: [
  4595. + // aliasPath,
  4596. + // ]
  4597. + // };
  4598. + } else {
  4599. + return {
  4600. + operator: 'equal',
  4601. + parameters: [aliasPath, this.createParameter(parameterValue)],
  4602. + };
  4603. + }
  4604. + }
  4605. + getWhereCondition(where) {
  4606. + if (typeof where === 'string') {
  4607. + return where;
  4608. + }
  4609. + if (InstanceChecker.isBrackets(where)) {
  4610. + const whereQueryBuilder = this.createQueryBuilder();
  4611. + whereQueryBuilder.parentQueryBuilder = this;
  4612. + whereQueryBuilder.expressionMap.mainAlias = this.expressionMap.mainAlias;
  4613. + whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
  4614. + this.expressionMap.aliasNamePrefixingEnabled;
  4615. + whereQueryBuilder.expressionMap.parameters =
  4616. + this.expressionMap.parameters;
  4617. + whereQueryBuilder.expressionMap.nativeParameters =
  4618. + this.expressionMap.nativeParameters;
  4619. + whereQueryBuilder.expressionMap.wheres = [];
  4620. + where.whereFactory(whereQueryBuilder);
  4621. + return {
  4622. + operator: InstanceChecker.isNotBrackets(where) ? 'not' : 'brackets',
  4623. + condition: whereQueryBuilder.expressionMap.wheres,
  4624. + };
  4625. + }
  4626. + if (typeof where === 'function') {
  4627. + return where(this);
  4628. + }
  4629. + const wheres = Array.isArray(where) ? where : [where];
  4630. + const clauses = [];
  4631. + for (const where of wheres) {
  4632. + const conditions = [];
  4633. + // Filter the conditions and set up the parameter values
  4634. + for (const [aliasPath, parameterValue] of this.getPredicates(where)) {
  4635. + conditions.push({
  4636. + type: 'and',
  4637. + condition: this.getWherePredicateCondition(aliasPath, parameterValue),
  4638. + });
  4639. + }
  4640. + clauses.push({ type: 'or', condition: conditions });
  4641. + }
  4642. + if (clauses.length === 1) {
  4643. + return clauses[0].condition;
  4644. + }
  4645. + return clauses;
  4646. + }
  4647. + /**
  4648. + * Creates a query builder used to execute sql queries inside this query builder.
  4649. + */
  4650. + obtainQueryRunner() {
  4651. + return this.queryRunner || this.connection.createQueryRunner();
  4652. + }
  4653. + hasCommonTableExpressions() {
  4654. + return this.expressionMap.commonTableExpressions.length > 0;
  4655. + }
  4656. +}
  4657. +
  4658. +//# sourceMappingURL=QueryBuilder.js.map
  4659. diff --git a/node_modules/typeorm/browser/query-builder/SoftDeleteQueryBuilder.js b/node_modules/typeorm/browser/query-builder/SoftDeleteQueryBuilder.js
  4660. index ef033f8..ca8f690 100644
  4661. --- a/node_modules/typeorm/browser/query-builder/SoftDeleteQueryBuilder.js
  4662. +++ b/node_modules/typeorm/browser/query-builder/SoftDeleteQueryBuilder.js
  4663. @@ -1,4 +1,3 @@
  4664. -import { QueryBuilder } from "./QueryBuilder";
  4665. import { UpdateResult } from "./result/UpdateResult";
  4666. import { ReturningStatementNotSupportedError } from "../error/ReturningStatementNotSupportedError";
  4667. import { ReturningResultsEntityUpdator } from "./ReturningResultsEntityUpdator";
  4668. @@ -8,10 +7,11 @@ import { UpdateValuesMissingError } from "../error/UpdateValuesMissingError";
  4669. import { TypeORMError } from "../error";
  4670. import { DriverUtils } from "../driver/DriverUtils";
  4671. import { InstanceChecker } from "../util/InstanceChecker";
  4672. +import { SoftDeleteQueryBuilderBase } from "./SoftDeleteQueryBuilderBase";
  4673. /**
  4674. * Allows to build complex sql queries in a fashion way and execute those queries.
  4675. */
  4676. -export class SoftDeleteQueryBuilder extends QueryBuilder {
  4677. +export class SoftDeleteQueryBuilder extends SoftDeleteQueryBuilderBase {
  4678. // -------------------------------------------------------------------------
  4679. // Constructor
  4680. // -------------------------------------------------------------------------
  4681. diff --git a/node_modules/typeorm/browser/query-builder/SoftDeleteQueryBuilderBase.js b/node_modules/typeorm/browser/query-builder/SoftDeleteQueryBuilderBase.js
  4682. new file mode 100644
  4683. index 0000000..269306c
  4684. --- /dev/null
  4685. +++ b/node_modules/typeorm/browser/query-builder/SoftDeleteQueryBuilderBase.js
  4686. @@ -0,0 +1,1133 @@
  4687. +import { QueryExpressionMap } from './QueryExpressionMap';
  4688. +import { Brackets } from './Brackets';
  4689. +import { FindOperator } from '../find-options/FindOperator';
  4690. +import { In } from '../find-options/operator/In';
  4691. +import { TypeORMError } from '../error';
  4692. +import { EntityPropertyNotFoundError } from '../error/EntityPropertyNotFoundError';
  4693. +import { InstanceChecker } from '../util/InstanceChecker';
  4694. +import { escapeRegExp } from '../util/escapeRegExp';
  4695. +// todo: completely cover query builder with tests
  4696. +// todo: entityOrProperty can be target name. implement proper behaviour if it is.
  4697. +// todo: check in persistment if id exist on object and throw exception (can be in partial selection?)
  4698. +// todo: fix problem with long aliases eg getMaxIdentifierLength
  4699. +// todo: fix replacing in .select("COUNT(post.id) AS cnt") statement
  4700. +// todo: implement joinAlways in relations and relationId
  4701. +// todo: finish partial selection
  4702. +// todo: sugar methods like: .addCount and .selectCount, selectCountAndMap, selectSum, selectSumAndMap, ...
  4703. +// todo: implement @Select decorator
  4704. +// todo: add select and map functions
  4705. +// todo: implement relation/entity loading and setting them into properties within a separate query
  4706. +// .loadAndMap("post.categories", "post.categories", qb => ...)
  4707. +// .loadAndMap("post.categories", Category, qb => ...)
  4708. +/**
  4709. + * Allows to build complex sql queries in a fashion way and execute those queries.
  4710. + */
  4711. +export class SoftDeleteQueryBuilderBase {
  4712. + /**
  4713. + * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
  4714. + */
  4715. + constructor(connectionOrQueryBuilder, queryRunner) {
  4716. + this['@instanceof'] = Symbol.for('QueryBuilder');
  4717. + /**
  4718. + * Memo to help keep place of current parameter index for `createParameter`
  4719. + */
  4720. + this.parameterIndex = 0;
  4721. + if (InstanceChecker.isQueryBuilder(connectionOrQueryBuilder)) {
  4722. + this.connection = connectionOrQueryBuilder.connection;
  4723. + this.queryRunner = connectionOrQueryBuilder.queryRunner;
  4724. + this.expressionMap = connectionOrQueryBuilder.expressionMap.clone();
  4725. + } else {
  4726. + this.connection = connectionOrQueryBuilder;
  4727. + this.queryRunner = queryRunner;
  4728. + this.expressionMap = new QueryExpressionMap(this.connection);
  4729. + }
  4730. + }
  4731. + // -------------------------------------------------------------------------
  4732. + // Accessors
  4733. + // -------------------------------------------------------------------------
  4734. + /**
  4735. + * Gets the main alias string used in this query builder.
  4736. + */
  4737. + get alias() {
  4738. + if (!this.expressionMap.mainAlias)
  4739. + throw new TypeORMError(`Main alias is not set`); // todo: better exception
  4740. + return this.expressionMap.mainAlias.name;
  4741. + }
  4742. + /**
  4743. + * Creates SELECT query and selects given data.
  4744. + * Replaces all previous selections if they exist.
  4745. + */
  4746. + select(selection, selectionAliasName) {
  4747. + this.expressionMap.queryType = 'select';
  4748. + if (Array.isArray(selection)) {
  4749. + this.expressionMap.selects = selection.map((selection) => ({
  4750. + selection: selection,
  4751. + }));
  4752. + } else if (selection) {
  4753. + this.expressionMap.selects = [
  4754. + { selection: selection, aliasName: selectionAliasName },
  4755. + ];
  4756. + }
  4757. + // loading it dynamically because of circular issue
  4758. + const SelectQueryBuilderCls =
  4759. + require('typeorm/browser/query-builder/SelectQueryBuilder').SelectQueryBuilder;
  4760. + if (InstanceChecker.isSelectQueryBuilder(this)) return this;
  4761. + return new SelectQueryBuilderCls(this);
  4762. + }
  4763. + /**
  4764. + * Creates INSERT query.
  4765. + */
  4766. + insert() {
  4767. + this.expressionMap.queryType = 'insert';
  4768. + // loading it dynamically because of circular issue
  4769. + const InsertQueryBuilderCls =
  4770. + require('typeorm/browser/query-builder/InsertQueryBuilder').InsertQueryBuilder;
  4771. + if (InstanceChecker.isInsertQueryBuilder(this)) return this;
  4772. + return new InsertQueryBuilderCls(this);
  4773. + }
  4774. + /**
  4775. + * Creates UPDATE query and applies given update values.
  4776. + */
  4777. + update(entityOrTableNameUpdateSet, maybeUpdateSet) {
  4778. + const updateSet = maybeUpdateSet
  4779. + ? maybeUpdateSet
  4780. + : entityOrTableNameUpdateSet;
  4781. + entityOrTableNameUpdateSet = InstanceChecker.isEntitySchema(
  4782. + entityOrTableNameUpdateSet
  4783. + )
  4784. + ? entityOrTableNameUpdateSet.options.name
  4785. + : entityOrTableNameUpdateSet;
  4786. + if (
  4787. + typeof entityOrTableNameUpdateSet === 'function' ||
  4788. + typeof entityOrTableNameUpdateSet === 'string'
  4789. + ) {
  4790. + const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet);
  4791. + this.expressionMap.setMainAlias(mainAlias);
  4792. + }
  4793. + this.expressionMap.queryType = 'update';
  4794. + this.expressionMap.valuesSet = updateSet;
  4795. + // loading it dynamically because of circular issue
  4796. + const UpdateQueryBuilderCls =
  4797. + require('typeorm/browser/query-builder/UpdateQueryBuilder').UpdateQueryBuilder;
  4798. + if (InstanceChecker.isUpdateQueryBuilder(this)) return this;
  4799. + return new UpdateQueryBuilderCls(this);
  4800. + }
  4801. + /**
  4802. + * Creates DELETE query.
  4803. + */
  4804. + delete() {
  4805. + this.expressionMap.queryType = 'delete';
  4806. + // loading it dynamically because of circular issue
  4807. + const DeleteQueryBuilderCls =
  4808. + require('typeorm/browser/query-builder/DeleteQueryBuilder').DeleteQueryBuilder;
  4809. + if (InstanceChecker.isDeleteQueryBuilder(this)) return this;
  4810. + return new DeleteQueryBuilderCls(this);
  4811. + }
  4812. + softDelete() {
  4813. + this.expressionMap.queryType = 'soft-delete';
  4814. + // loading it dynamically because of circular issue
  4815. + const SoftDeleteQueryBuilderCls =
  4816. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  4817. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  4818. + return new SoftDeleteQueryBuilderCls(this);
  4819. + }
  4820. + restore() {
  4821. + this.expressionMap.queryType = 'restore';
  4822. + // loading it dynamically because of circular issue
  4823. + const SoftDeleteQueryBuilderCls =
  4824. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  4825. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  4826. + return new SoftDeleteQueryBuilderCls(this);
  4827. + }
  4828. + /**
  4829. + * Sets entity's relation with which this query builder gonna work.
  4830. + */
  4831. + relation(entityTargetOrPropertyPath, maybePropertyPath) {
  4832. + const entityTarget =
  4833. + arguments.length === 2 ? entityTargetOrPropertyPath : undefined;
  4834. + const propertyPath =
  4835. + arguments.length === 2 ? maybePropertyPath : entityTargetOrPropertyPath;
  4836. + this.expressionMap.queryType = 'relation';
  4837. + this.expressionMap.relationPropertyPath = propertyPath;
  4838. + if (entityTarget) {
  4839. + const mainAlias = this.createFromAlias(entityTarget);
  4840. + this.expressionMap.setMainAlias(mainAlias);
  4841. + }
  4842. + // loading it dynamically because of circular issue
  4843. + const RelationQueryBuilderCls =
  4844. + require('typeorm/browser/query-builder/RelationQueryBuilder').RelationQueryBuilder;
  4845. + if (InstanceChecker.isRelationQueryBuilder(this)) return this;
  4846. + return new RelationQueryBuilderCls(this);
  4847. + }
  4848. + /**
  4849. + * Checks if given relation or relations exist in the entity.
  4850. + * Returns true if relation exists, false otherwise.
  4851. + *
  4852. + * todo: move this method to manager? or create a shortcut?
  4853. + */
  4854. + hasRelation(target, relation) {
  4855. + const entityMetadata = this.connection.getMetadata(target);
  4856. + const relations = Array.isArray(relation) ? relation : [relation];
  4857. + return relations.every((relation) => {
  4858. + return !!entityMetadata.findRelationWithPropertyPath(relation);
  4859. + });
  4860. + }
  4861. + /**
  4862. + * Check the existence of a parameter for this query builder.
  4863. + */
  4864. + hasParameter(key) {
  4865. + var _a;
  4866. + return (
  4867. + ((_a = this.parentQueryBuilder) === null || _a === void 0
  4868. + ? void 0
  4869. + : _a.hasParameter(key)) || key in this.expressionMap.parameters
  4870. + );
  4871. + }
  4872. + /**
  4873. + * Sets parameter name and its value.
  4874. + *
  4875. + * The key for this parameter may contain numbers, letters, underscores, or periods.
  4876. + */
  4877. + setParameter(key, value) {
  4878. + if (typeof value === 'function') {
  4879. + throw new TypeORMError(
  4880. + `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`
  4881. + );
  4882. + }
  4883. + if (!key.match(/^([A-Za-z0-9_.]+)$/)) {
  4884. + throw new TypeORMError(
  4885. + 'QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.'
  4886. + );
  4887. + }
  4888. + if (this.parentQueryBuilder) {
  4889. + this.parentQueryBuilder.setParameter(key, value);
  4890. + }
  4891. + this.expressionMap.parameters[key] = value;
  4892. + return this;
  4893. + }
  4894. + /**
  4895. + * Adds all parameters from the given object.
  4896. + */
  4897. + setParameters(parameters) {
  4898. + for (const [key, value] of Object.entries(parameters)) {
  4899. + this.setParameter(key, value);
  4900. + }
  4901. + return this;
  4902. + }
  4903. + createParameter(value) {
  4904. + let parameterName;
  4905. + do {
  4906. + parameterName = `orm_param_${this.parameterIndex++}`;
  4907. + } while (this.hasParameter(parameterName));
  4908. + this.setParameter(parameterName, value);
  4909. + return `:${parameterName}`;
  4910. + }
  4911. + /**
  4912. + * Adds native parameters from the given object.
  4913. + *
  4914. + * @deprecated Use `setParameters` instead
  4915. + */
  4916. + setNativeParameters(parameters) {
  4917. + // set parent query builder parameters as well in sub-query mode
  4918. + if (this.parentQueryBuilder) {
  4919. + this.parentQueryBuilder.setNativeParameters(parameters);
  4920. + }
  4921. + Object.keys(parameters).forEach((key) => {
  4922. + this.expressionMap.nativeParameters[key] = parameters[key];
  4923. + });
  4924. + return this;
  4925. + }
  4926. + /**
  4927. + * Gets all parameters.
  4928. + */
  4929. + getParameters() {
  4930. + const parameters = Object.assign({}, this.expressionMap.parameters);
  4931. + // add discriminator column parameter if it exist
  4932. + if (
  4933. + this.expressionMap.mainAlias &&
  4934. + this.expressionMap.mainAlias.hasMetadata
  4935. + ) {
  4936. + const metadata = this.expressionMap.mainAlias.metadata;
  4937. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  4938. + const values = metadata.childEntityMetadatas
  4939. + .filter((childMetadata) => childMetadata.discriminatorColumn)
  4940. + .map((childMetadata) => childMetadata.discriminatorValue);
  4941. + values.push(metadata.discriminatorValue);
  4942. + parameters['discriminatorColumnValues'] = values;
  4943. + }
  4944. + }
  4945. + return parameters;
  4946. + }
  4947. + /**
  4948. + * Prints sql to stdout using console.log.
  4949. + */
  4950. + printSql() {
  4951. + // TODO rename to logSql()
  4952. + const [query, parameters] = this.getQueryAndParameters();
  4953. + this.connection.logger.logQuery(query, parameters);
  4954. + return this;
  4955. + }
  4956. + /**
  4957. + * Gets generated sql that will be executed.
  4958. + * Parameters in the query are escaped for the currently used driver.
  4959. + */
  4960. + getSql() {
  4961. + return this.getQueryAndParameters()[0];
  4962. + }
  4963. + /**
  4964. + * Gets query to be executed with all parameters used in it.
  4965. + */
  4966. + getQueryAndParameters() {
  4967. + // this execution order is important because getQuery method generates this.expressionMap.nativeParameters values
  4968. + const query = this.getQuery();
  4969. + const parameters = this.getParameters();
  4970. + return this.connection.driver.escapeQueryWithParameters(
  4971. + query,
  4972. + parameters,
  4973. + this.expressionMap.nativeParameters
  4974. + );
  4975. + }
  4976. + /**
  4977. + * Executes sql generated by query builder and returns raw database results.
  4978. + */
  4979. + async execute() {
  4980. + const [sql, parameters] = this.getQueryAndParameters();
  4981. + const queryRunner = this.obtainQueryRunner();
  4982. + try {
  4983. + return await queryRunner.query(sql, parameters); // await is needed here because we are using finally
  4984. + } finally {
  4985. + if (queryRunner !== this.queryRunner) {
  4986. + // means we created our own query runner
  4987. + await queryRunner.release();
  4988. + }
  4989. + }
  4990. + }
  4991. + /**
  4992. + * Creates a completely new query builder.
  4993. + * Uses same query runner as current QueryBuilder.
  4994. + */
  4995. + createQueryBuilder() {
  4996. + return new this.constructor(this.connection, this.queryRunner);
  4997. + }
  4998. + /**
  4999. + * Clones query builder as it is.
  5000. + * Note: it uses new query runner, if you want query builder that uses exactly same query runner,
  5001. + * you can create query builder using its constructor, for example new SelectQueryBuilder(queryBuilder)
  5002. + * where queryBuilder is cloned QueryBuilder.
  5003. + */
  5004. + clone() {
  5005. + return new this.constructor(this);
  5006. + }
  5007. + /**
  5008. + * Includes a Query comment in the query builder. This is helpful for debugging purposes,
  5009. + * such as finding a specific query in the database server's logs, or for categorization using
  5010. + * an APM product.
  5011. + */
  5012. + comment(comment) {
  5013. + this.expressionMap.comment = comment;
  5014. + return this;
  5015. + }
  5016. + /**
  5017. + * Disables escaping.
  5018. + */
  5019. + disableEscaping() {
  5020. + this.expressionMap.disableEscaping = false;
  5021. + return this;
  5022. + }
  5023. + /**
  5024. + * Escapes table name, column name or alias name using current database's escaping character.
  5025. + */
  5026. + escape(name) {
  5027. + if (!this.expressionMap.disableEscaping) return name;
  5028. + return this.connection.driver.escape(name);
  5029. + }
  5030. + /**
  5031. + * Sets or overrides query builder's QueryRunner.
  5032. + */
  5033. + setQueryRunner(queryRunner) {
  5034. + this.queryRunner = queryRunner;
  5035. + return this;
  5036. + }
  5037. + /**
  5038. + * Indicates if listeners and subscribers must be called before and after query execution.
  5039. + * Enabled by default.
  5040. + */
  5041. + callListeners(enabled) {
  5042. + this.expressionMap.callListeners = enabled;
  5043. + return this;
  5044. + }
  5045. + /**
  5046. + * If set to true the query will be wrapped into a transaction.
  5047. + */
  5048. + useTransaction(enabled) {
  5049. + this.expressionMap.useTransaction = enabled;
  5050. + return this;
  5051. + }
  5052. + /**
  5053. + * Adds CTE to query
  5054. + */
  5055. + addCommonTableExpression(queryBuilder, alias, options) {
  5056. + this.expressionMap.commonTableExpressions.push({
  5057. + queryBuilder,
  5058. + alias,
  5059. + options: options || {},
  5060. + });
  5061. + return this;
  5062. + }
  5063. + // -------------------------------------------------------------------------
  5064. + // Protected Methods
  5065. + // -------------------------------------------------------------------------
  5066. + /**
  5067. + * Gets escaped table name with schema name if SqlServer driver used with custom
  5068. + * schema name, otherwise returns escaped table name.
  5069. + */
  5070. + getTableName(tablePath) {
  5071. + return tablePath
  5072. + .split('.')
  5073. + .map((i) => {
  5074. + // this condition need because in SQL Server driver when custom database name was specified and schema name was not, we got `dbName..tableName` string, and doesn't need to escape middle empty string
  5075. + if (i === '') return i;
  5076. + return this.escape(i);
  5077. + })
  5078. + .join('.');
  5079. + }
  5080. + /**
  5081. + * Gets name of the table where insert should be performed.
  5082. + */
  5083. + getMainTableName() {
  5084. + if (!this.expressionMap.mainAlias)
  5085. + throw new TypeORMError(
  5086. + `Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.`
  5087. + );
  5088. + if (this.expressionMap.mainAlias.hasMetadata)
  5089. + return this.expressionMap.mainAlias.metadata.tablePath;
  5090. + return this.expressionMap.mainAlias.tablePath;
  5091. + }
  5092. + /**
  5093. + * Specifies FROM which entity's table select/update/delete will be executed.
  5094. + * Also sets a main string alias of the selection data.
  5095. + */
  5096. + createFromAlias(entityTarget, aliasName) {
  5097. + // if table has a metadata then find it to properly escape its properties
  5098. + // const metadata = this.connection.entityMetadatas.find(metadata => metadata.tableName === tableName);
  5099. + if (this.connection.hasMetadata(entityTarget)) {
  5100. + const metadata = this.connection.getMetadata(entityTarget);
  5101. + return this.expressionMap.createAlias({
  5102. + type: 'from',
  5103. + name: aliasName,
  5104. + metadata: this.connection.getMetadata(entityTarget),
  5105. + tablePath: metadata.tablePath,
  5106. + });
  5107. + } else {
  5108. + if (typeof entityTarget === 'string') {
  5109. + const isSubquery =
  5110. + entityTarget.substr(0, 1) === '(' && entityTarget.substr(-1) === ')';
  5111. + return this.expressionMap.createAlias({
  5112. + type: 'from',
  5113. + name: aliasName,
  5114. + tablePath: !isSubquery ? entityTarget : undefined,
  5115. + subQuery: isSubquery ? entityTarget : undefined,
  5116. + });
  5117. + }
  5118. + const subQueryBuilder = entityTarget(this.subQuery());
  5119. + this.setParameters(subQueryBuilder.getParameters());
  5120. + const subquery = subQueryBuilder.getQuery();
  5121. + return this.expressionMap.createAlias({
  5122. + type: 'from',
  5123. + name: aliasName,
  5124. + subQuery: subquery,
  5125. + });
  5126. + }
  5127. + }
  5128. + /**
  5129. + * Replaces all entity's propertyName to name in the given statement.
  5130. + */
  5131. + replacePropertyNames(statement) {
  5132. + for (const alias of this.expressionMap.aliases) {
  5133. + if (!alias.hasMetadata) continue;
  5134. + const replaceAliasNamePrefix = this.expressionMap
  5135. + .aliasNamePrefixingEnabled
  5136. + ? `${alias.name}.`
  5137. + : '';
  5138. + const replacementAliasNamePrefix = this.expressionMap
  5139. + .aliasNamePrefixingEnabled
  5140. + ? `${this.escape(alias.name)}.`
  5141. + : '';
  5142. + const replacements = {};
  5143. + // Insert & overwrite the replacements from least to most relevant in our replacements object.
  5144. + // To do this we iterate and overwrite in the order of relevance.
  5145. + // Least to Most Relevant:
  5146. + // * Relation Property Path to first join column key
  5147. + // * Relation Property Path + Column Path
  5148. + // * Column Database Name
  5149. + // * Column Property Name
  5150. + // * Column Property Path
  5151. + for (const relation of alias.metadata.relations) {
  5152. + if (relation.joinColumns.length > 0)
  5153. + replacements[relation.propertyPath] =
  5154. + relation.joinColumns[0].databaseName;
  5155. + }
  5156. + for (const relation of alias.metadata.relations) {
  5157. + for (const joinColumn of [
  5158. + ...relation.joinColumns,
  5159. + ...relation.inverseJoinColumns,
  5160. + ]) {
  5161. + const propertyKey = `${relation.propertyPath}.${joinColumn.referencedColumn.propertyPath}`;
  5162. + replacements[propertyKey] = joinColumn.databaseName;
  5163. + }
  5164. + }
  5165. + for (const column of alias.metadata.columns) {
  5166. + replacements[column.databaseName] = column.databaseName;
  5167. + }
  5168. + for (const column of alias.metadata.columns) {
  5169. + replacements[column.propertyName] = column.databaseName;
  5170. + }
  5171. + for (const column of alias.metadata.columns) {
  5172. + replacements[column.propertyPath] = column.databaseName;
  5173. + }
  5174. + statement = statement.replace(
  5175. + new RegExp(
  5176. + // Avoid a lookbehind here since it's not well supported
  5177. + `([ =\(]|^.{0})` + // any of ' =(' or start of line
  5178. + // followed by our prefix, e.g. 'tablename.' or ''
  5179. + `${escapeRegExp(replaceAliasNamePrefix)}([^ =\(\)\,]+)` + // a possible property name: sequence of anything but ' =(),'
  5180. + // terminated by ' =),' or end of line
  5181. + `(?=[ =\)\,]|.{0}$)`,
  5182. + 'gm'
  5183. + ),
  5184. + (match, pre, p) => {
  5185. + if (replacements[p]) {
  5186. + return `${pre}${replacementAliasNamePrefix}${this.escape(
  5187. + replacements[p]
  5188. + )}`;
  5189. + }
  5190. + return match;
  5191. + }
  5192. + );
  5193. + }
  5194. + return statement;
  5195. + }
  5196. + createComment() {
  5197. + if (!this.expressionMap.comment) {
  5198. + return '';
  5199. + }
  5200. + // ANSI SQL 2003 support C style comments - comments that start with `/*` and end with `*/`
  5201. + // In some dialects query nesting is available - but not all. Because of this, we'll need
  5202. + // to scrub "ending" characters from the SQL but otherwise we can leave everything else
  5203. + // as-is and it should be valid.
  5204. + return `/* ${this.expressionMap.comment.replace('*/', '')} */ `;
  5205. + }
  5206. + /**
  5207. + * Creates "WHERE" expression.
  5208. + */
  5209. + createWhereExpression() {
  5210. + const conditionsArray = [];
  5211. + const whereExpression = this.createWhereClausesExpression(
  5212. + this.expressionMap.wheres
  5213. + );
  5214. + if (whereExpression.length > 0 && whereExpression !== '1=1') {
  5215. + conditionsArray.push(this.replacePropertyNames(whereExpression));
  5216. + }
  5217. + if (this.expressionMap.mainAlias.hasMetadata) {
  5218. + const metadata = this.expressionMap.mainAlias.metadata;
  5219. + // Adds the global condition of "non-deleted" for the entity with delete date columns in select query.
  5220. + if (
  5221. + this.expressionMap.queryType === 'select' &&
  5222. + !this.expressionMap.withDeleted &&
  5223. + metadata.deleteDateColumn
  5224. + ) {
  5225. + const column = this.expressionMap.aliasNamePrefixingEnabled
  5226. + ? this.expressionMap.mainAlias.name +
  5227. + '.' +
  5228. + metadata.deleteDateColumn.propertyName
  5229. + : metadata.deleteDateColumn.propertyName;
  5230. + const condition = `${this.replacePropertyNames(column)} IS NULL`;
  5231. + conditionsArray.push(condition);
  5232. + }
  5233. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  5234. + const column = this.expressionMap.aliasNamePrefixingEnabled
  5235. + ? this.expressionMap.mainAlias.name +
  5236. + '.' +
  5237. + metadata.discriminatorColumn.databaseName
  5238. + : metadata.discriminatorColumn.databaseName;
  5239. + const condition = `${this.replacePropertyNames(
  5240. + column
  5241. + )} IN (:...discriminatorColumnValues)`;
  5242. + conditionsArray.push(condition);
  5243. + }
  5244. + }
  5245. + if (this.expressionMap.extraAppendedAndWhereCondition) {
  5246. + const condition = this.replacePropertyNames(
  5247. + this.expressionMap.extraAppendedAndWhereCondition
  5248. + );
  5249. + conditionsArray.push(condition);
  5250. + }
  5251. + if (!conditionsArray.length) {
  5252. + return '';
  5253. + } else if (conditionsArray.length === 1) {
  5254. + return ` WHERE ${conditionsArray[0]}`;
  5255. + } else {
  5256. + return ` WHERE ( ${conditionsArray.join(' ) AND ( ')} )`;
  5257. + }
  5258. + }
  5259. + /**
  5260. + * Creates "RETURNING" / "OUTPUT" expression.
  5261. + */
  5262. + createReturningExpression(returningType) {
  5263. + const columns = this.getReturningColumns();
  5264. + const driver = this.connection.driver;
  5265. + // also add columns we must auto-return to perform entity updation
  5266. + // if user gave his own returning
  5267. + if (
  5268. + typeof this.expressionMap.returning !== 'string' &&
  5269. + this.expressionMap.extraReturningColumns.length > 0 &&
  5270. + driver.isReturningSqlSupported(returningType)
  5271. + ) {
  5272. + columns.push(
  5273. + ...this.expressionMap.extraReturningColumns.filter((column) => {
  5274. + return columns.indexOf(column) === -1;
  5275. + })
  5276. + );
  5277. + }
  5278. + if (columns.length) {
  5279. + let columnsExpression = columns
  5280. + .map((column) => {
  5281. + const name = this.escape(column.databaseName);
  5282. + if (driver.options.type === 'mssql') {
  5283. + if (
  5284. + this.expressionMap.queryType === 'insert' ||
  5285. + this.expressionMap.queryType === 'update' ||
  5286. + this.expressionMap.queryType === 'soft-delete' ||
  5287. + this.expressionMap.queryType === 'restore'
  5288. + ) {
  5289. + return 'INSERTED.' + name;
  5290. + } else {
  5291. + return this.escape(this.getMainTableName()) + '.' + name;
  5292. + }
  5293. + } else {
  5294. + return name;
  5295. + }
  5296. + })
  5297. + .join(', ');
  5298. + if (driver.options.type === 'oracle') {
  5299. + columnsExpression +=
  5300. + ' INTO ' +
  5301. + columns
  5302. + .map((column) => {
  5303. + return this.createParameter({
  5304. + type: driver.columnTypeToNativeParameter(column.type),
  5305. + dir: driver.oracle.BIND_OUT,
  5306. + });
  5307. + })
  5308. + .join(', ');
  5309. + }
  5310. + if (driver.options.type === 'mssql') {
  5311. + if (
  5312. + this.expressionMap.queryType === 'insert' ||
  5313. + this.expressionMap.queryType === 'update'
  5314. + ) {
  5315. + columnsExpression += ' INTO @OutputTable';
  5316. + }
  5317. + }
  5318. + return columnsExpression;
  5319. + } else if (typeof this.expressionMap.returning === 'string') {
  5320. + return this.expressionMap.returning;
  5321. + }
  5322. + return '';
  5323. + }
  5324. + /**
  5325. + * If returning / output cause is set to array of column names,
  5326. + * then this method will return all column metadatas of those column names.
  5327. + */
  5328. + getReturningColumns() {
  5329. + const columns = [];
  5330. + if (Array.isArray(this.expressionMap.returning)) {
  5331. + this.expressionMap.returning.forEach((columnName) => {
  5332. + if (this.expressionMap.mainAlias.hasMetadata) {
  5333. + columns.push(
  5334. + ...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(
  5335. + columnName
  5336. + )
  5337. + );
  5338. + }
  5339. + });
  5340. + }
  5341. + return columns;
  5342. + }
  5343. + createWhereClausesExpression(clauses) {
  5344. + return clauses
  5345. + .map((clause, index) => {
  5346. + const expression = this.createWhereConditionExpression(
  5347. + clause.condition
  5348. + );
  5349. + switch (clause.type) {
  5350. + case 'and':
  5351. + return (index > 0 ? 'AND ' : '') + expression;
  5352. + case 'or':
  5353. + return (index > 0 ? 'OR ' : '') + expression;
  5354. + }
  5355. + return expression;
  5356. + })
  5357. + .join(' ')
  5358. + .trim();
  5359. + }
  5360. + /**
  5361. + * Computes given where argument - transforms to a where string all forms it can take.
  5362. + */
  5363. + createWhereConditionExpression(condition, alwaysWrap = false) {
  5364. + if (typeof condition === 'string') return condition;
  5365. + if (Array.isArray(condition)) {
  5366. + if (condition.length === 0) {
  5367. + return '1=1';
  5368. + }
  5369. + // In the future we should probably remove this entire condition
  5370. + // but for now to prevent any breaking changes it exists.
  5371. + if (condition.length === 1 && !alwaysWrap) {
  5372. + return this.createWhereClausesExpression(condition);
  5373. + }
  5374. + return '(' + this.createWhereClausesExpression(condition) + ')';
  5375. + }
  5376. + const { driver } = this.connection;
  5377. + switch (condition.operator) {
  5378. + case 'lessThan':
  5379. + return `${condition.parameters[0]} < ${condition.parameters[1]}`;
  5380. + case 'lessThanOrEqual':
  5381. + return `${condition.parameters[0]} <= ${condition.parameters[1]}`;
  5382. + case 'arrayContains':
  5383. + return `${condition.parameters[0]} @> ${condition.parameters[1]}`;
  5384. + case 'arrayContainedBy':
  5385. + return `${condition.parameters[0]} <@ ${condition.parameters[1]}`;
  5386. + case 'arrayOverlap':
  5387. + return `${condition.parameters[0]} && ${condition.parameters[1]}`;
  5388. + case 'moreThan':
  5389. + return `${condition.parameters[0]} > ${condition.parameters[1]}`;
  5390. + case 'moreThanOrEqual':
  5391. + return `${condition.parameters[0]} >= ${condition.parameters[1]}`;
  5392. + case 'notEqual':
  5393. + return `${condition.parameters[0]} != ${condition.parameters[1]}`;
  5394. + case 'equal':
  5395. + return `${condition.parameters[0]} = ${condition.parameters[1]}`;
  5396. + case 'ilike':
  5397. + if (
  5398. + driver.options.type === 'postgres' ||
  5399. + driver.options.type === 'cockroachdb'
  5400. + ) {
  5401. + return `${condition.parameters[0]} ILIKE ${condition.parameters[1]}`;
  5402. + }
  5403. + return `UPPER(${condition.parameters[0]}) LIKE UPPER(${condition.parameters[1]})`;
  5404. + case 'like':
  5405. + return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`;
  5406. + case 'between':
  5407. + return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`;
  5408. + case 'in':
  5409. + if (condition.parameters.length <= 1) {
  5410. + return '0=1';
  5411. + }
  5412. + return `${condition.parameters[0]} IN (${condition.parameters
  5413. + .slice(1)
  5414. + .join(', ')})`;
  5415. + case 'any':
  5416. + return `${condition.parameters[0]} = ANY(${condition.parameters[1]})`;
  5417. + case 'isNull':
  5418. + return `${condition.parameters[0]} IS NULL`;
  5419. + case 'not':
  5420. + return `NOT(${this.createWhereConditionExpression(
  5421. + condition.condition
  5422. + )})`;
  5423. + case 'brackets':
  5424. + return `${this.createWhereConditionExpression(
  5425. + condition.condition,
  5426. + true
  5427. + )}`;
  5428. + }
  5429. + throw new TypeError(
  5430. + `Unsupported FindOperator ${FindOperator.constructor.name}`
  5431. + );
  5432. + }
  5433. + createCteExpression() {
  5434. + if (!this.hasCommonTableExpressions()) {
  5435. + return '';
  5436. + }
  5437. + const databaseRequireRecusiveHint =
  5438. + this.connection.driver.cteCapabilities.requiresRecursiveHint;
  5439. + const cteStrings = this.expressionMap.commonTableExpressions.map((cte) => {
  5440. + const cteBodyExpression =
  5441. + typeof cte.queryBuilder === 'string'
  5442. + ? cte.queryBuilder
  5443. + : cte.queryBuilder.getQuery();
  5444. + if (typeof cte.queryBuilder !== 'string') {
  5445. + if (cte.queryBuilder.hasCommonTableExpressions()) {
  5446. + throw new TypeORMError(
  5447. + `Nested CTEs aren't supported (CTE: ${cte.alias})`
  5448. + );
  5449. + }
  5450. + if (
  5451. + !this.connection.driver.cteCapabilities.writable &&
  5452. + !InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
  5453. + ) {
  5454. + throw new TypeORMError(
  5455. + `Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${cte.alias})`
  5456. + );
  5457. + }
  5458. + this.setParameters(cte.queryBuilder.getParameters());
  5459. + }
  5460. + let cteHeader = this.escape(cte.alias);
  5461. + if (cte.options.columnNames) {
  5462. + const escapedColumnNames = cte.options.columnNames.map((column) =>
  5463. + this.escape(column)
  5464. + );
  5465. + if (InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)) {
  5466. + if (
  5467. + cte.queryBuilder.expressionMap.selects.length &&
  5468. + cte.options.columnNames.length !==
  5469. + cte.queryBuilder.expressionMap.selects.length
  5470. + ) {
  5471. + throw new TypeORMError(
  5472. + `cte.options.columnNames length (${cte.options.columnNames.length}) doesn't match subquery select list length ${cte.queryBuilder.expressionMap.selects.length} (CTE: ${cte.alias})`
  5473. + );
  5474. + }
  5475. + }
  5476. + cteHeader += `(${escapedColumnNames.join(', ')})`;
  5477. + }
  5478. + const recursiveClause =
  5479. + cte.options.recursive && databaseRequireRecusiveHint ? 'RECURSIVE' : '';
  5480. + const materializeClause =
  5481. + cte.options.materialized &&
  5482. + this.connection.driver.cteCapabilities.materializedHint
  5483. + ? 'MATERIALIZED'
  5484. + : '';
  5485. + return [
  5486. + recursiveClause,
  5487. + cteHeader,
  5488. + materializeClause,
  5489. + 'AS',
  5490. + `(${cteBodyExpression})`,
  5491. + ]
  5492. + .filter(Boolean)
  5493. + .join(' ');
  5494. + });
  5495. + return 'WITH ' + cteStrings.join(', ') + ' ';
  5496. + }
  5497. + /**
  5498. + * Creates "WHERE" condition for an in-ids condition.
  5499. + */
  5500. + getWhereInIdsCondition(ids) {
  5501. + const metadata = this.expressionMap.mainAlias.metadata;
  5502. + const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
  5503. + metadata.ensureEntityIdMap(id)
  5504. + );
  5505. + // using in(...ids) for single primary key entities
  5506. + if (!metadata.hasMultiplePrimaryKeys) {
  5507. + const primaryColumn = metadata.primaryColumns[0];
  5508. + // getEntityValue will try to transform `In`, it is a bug
  5509. + // todo: remove this transformer check after #2390 is fixed
  5510. + // This also fails for embedded & relation, so until that is fixed skip it.
  5511. + if (
  5512. + !primaryColumn.transformer &&
  5513. + !primaryColumn.relationMetadata &&
  5514. + !primaryColumn.embeddedMetadata
  5515. + ) {
  5516. + return {
  5517. + [primaryColumn.propertyName]: In(
  5518. + normalized.map((id) => primaryColumn.getEntityValue(id, false))
  5519. + ),
  5520. + };
  5521. + }
  5522. + }
  5523. + return new Brackets((qb) => {
  5524. + for (const data of normalized) {
  5525. + qb.orWhere(new Brackets((qb) => qb.where(data)));
  5526. + }
  5527. + });
  5528. + }
  5529. + findColumnsForPropertyPath(propertyPath) {
  5530. + // Make a helper to iterate the entity & relations?
  5531. + // Use that to set the correct alias? Or the other way around?
  5532. + // Start with the main alias with our property paths
  5533. + let alias = this.expressionMap.mainAlias;
  5534. + const root = [];
  5535. + const propertyPathParts = propertyPath.split('.');
  5536. + while (propertyPathParts.length > 1) {
  5537. + const part = propertyPathParts[0];
  5538. + if (!(alias === null || alias === void 0 ? void 0 : alias.hasMetadata)) {
  5539. + // If there's no metadata, we're wasting our time
  5540. + // and can't actually look any of this up.
  5541. + break;
  5542. + }
  5543. + if (alias.metadata.hasEmbeddedWithPropertyPath(part)) {
  5544. + // If this is an embedded then we should combine the two as part of our lookup.
  5545. + // Instead of just breaking, we keep going with this in case there's an embedded/relation
  5546. + // inside an embedded.
  5547. + propertyPathParts.unshift(
  5548. + `${propertyPathParts.shift()}.${propertyPathParts.shift()}`
  5549. + );
  5550. + continue;
  5551. + }
  5552. + if (alias.metadata.hasRelationWithPropertyPath(part)) {
  5553. + // If this is a relation then we should find the aliases
  5554. + // that match the relation & then continue further down
  5555. + // the property path
  5556. + const joinAttr = this.expressionMap.joinAttributes.find(
  5557. + (joinAttr) => joinAttr.relationPropertyPath === part
  5558. + );
  5559. + if (
  5560. + !(joinAttr === null || joinAttr === void 0 ? void 0 : joinAttr.alias)
  5561. + ) {
  5562. + const fullRelationPath =
  5563. + root.length > 0 ? `${root.join('.')}.${part}` : part;
  5564. + throw new Error(
  5565. + `Cannot find alias for relation at ${fullRelationPath}`
  5566. + );
  5567. + }
  5568. + alias = joinAttr.alias;
  5569. + root.push(...part.split('.'));
  5570. + propertyPathParts.shift();
  5571. + continue;
  5572. + }
  5573. + break;
  5574. + }
  5575. + if (!alias) {
  5576. + throw new Error(`Cannot find alias for property ${propertyPath}`);
  5577. + }
  5578. + // Remaining parts are combined back and used to find the actual property path
  5579. + const aliasPropertyPath = propertyPathParts.join('.');
  5580. + const columns =
  5581. + alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath);
  5582. + if (!columns.length) {
  5583. + throw new EntityPropertyNotFoundError(propertyPath, alias.metadata);
  5584. + }
  5585. + return [alias, root, columns];
  5586. + }
  5587. + /**
  5588. + * Creates a property paths for a given ObjectLiteral.
  5589. + */
  5590. + createPropertyPath(metadata, entity, prefix = '') {
  5591. + const paths = [];
  5592. + for (const key of Object.keys(entity)) {
  5593. + const path = prefix ? `${prefix}.${key}` : key;
  5594. + // There's times where we don't actually want to traverse deeper.
  5595. + // If the value is a `FindOperator`, or null, or not an object, then we don't, for example.
  5596. + if (
  5597. + entity[key] === null ||
  5598. + typeof entity[key] !== 'object' ||
  5599. + InstanceChecker.isFindOperator(entity[key])
  5600. + ) {
  5601. + paths.push(path);
  5602. + continue;
  5603. + }
  5604. + if (metadata.hasEmbeddedWithPropertyPath(path)) {
  5605. + const subPaths = this.createPropertyPath(metadata, entity[key], path);
  5606. + paths.push(...subPaths);
  5607. + continue;
  5608. + }
  5609. + if (metadata.hasRelationWithPropertyPath(path)) {
  5610. + const relation = metadata.findRelationWithPropertyPath(path);
  5611. + // There's also cases where we don't want to return back all of the properties.
  5612. + // These handles the situation where someone passes the model & we don't need to make
  5613. + // a HUGE `where` to uniquely look up the entity.
  5614. + // In the case of a *-to-one, there's only ever one possible entity on the other side
  5615. + // so if the join columns are all defined we can return just the relation itself
  5616. + // because it will fetch only the join columns and do the lookup.
  5617. + if (
  5618. + relation.relationType === 'one-to-one' ||
  5619. + relation.relationType === 'many-to-one'
  5620. + ) {
  5621. + const joinColumns = relation.joinColumns
  5622. + .map((j) => j.referencedColumn)
  5623. + .filter((j) => !!j);
  5624. + const hasAllJoinColumns =
  5625. + joinColumns.length > 0 &&
  5626. + joinColumns.every((column) =>
  5627. + column.getEntityValue(entity[key], false)
  5628. + );
  5629. + if (hasAllJoinColumns) {
  5630. + paths.push(path);
  5631. + continue;
  5632. + }
  5633. + }
  5634. + if (
  5635. + relation.relationType === 'one-to-many' ||
  5636. + relation.relationType === 'many-to-many'
  5637. + ) {
  5638. + throw new Error(
  5639. + `Cannot query across ${relation.relationType} for property ${path}`
  5640. + );
  5641. + }
  5642. + // For any other case, if the `entity[key]` contains all of the primary keys we can do a
  5643. + // lookup via these. We don't need to look up via any other values 'cause these are
  5644. + // the unique primary keys.
  5645. + // This handles the situation where someone passes the model & we don't need to make
  5646. + // a HUGE where.
  5647. + const primaryColumns = relation.inverseEntityMetadata.primaryColumns;
  5648. + const hasAllPrimaryKeys =
  5649. + primaryColumns.length > 0 &&
  5650. + primaryColumns.every((column) =>
  5651. + column.getEntityValue(entity[key], false)
  5652. + );
  5653. + if (hasAllPrimaryKeys) {
  5654. + const subPaths = primaryColumns.map(
  5655. + (column) => `${path}.${column.propertyPath}`
  5656. + );
  5657. + paths.push(...subPaths);
  5658. + continue;
  5659. + }
  5660. + // If nothing else, just return every property that's being passed to us.
  5661. + const subPaths = this.createPropertyPath(
  5662. + relation.inverseEntityMetadata,
  5663. + entity[key]
  5664. + ).map((p) => `${path}.${p}`);
  5665. + paths.push(...subPaths);
  5666. + continue;
  5667. + }
  5668. + paths.push(path);
  5669. + }
  5670. + return paths;
  5671. + }
  5672. + *getPredicates(where) {
  5673. + if (this.expressionMap.mainAlias.hasMetadata) {
  5674. + const propertyPaths = this.createPropertyPath(
  5675. + this.expressionMap.mainAlias.metadata,
  5676. + where
  5677. + );
  5678. + for (const propertyPath of propertyPaths) {
  5679. + const [alias, aliasPropertyPath, columns] =
  5680. + this.findColumnsForPropertyPath(propertyPath);
  5681. + for (const column of columns) {
  5682. + let containedWhere = where;
  5683. + for (const part of aliasPropertyPath) {
  5684. + if (!containedWhere || !(part in containedWhere)) {
  5685. + containedWhere = {};
  5686. + break;
  5687. + }
  5688. + containedWhere = containedWhere[part];
  5689. + }
  5690. + // Use the correct alias & the property path from the column
  5691. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  5692. + ? `${alias.name}.${column.propertyPath}`
  5693. + : column.propertyPath;
  5694. + const parameterValue = column.getEntityValue(containedWhere, true);
  5695. + yield [aliasPath, parameterValue];
  5696. + }
  5697. + }
  5698. + } else {
  5699. + for (const key of Object.keys(where)) {
  5700. + const parameterValue = where[key];
  5701. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  5702. + ? `${this.alias}.${key}`
  5703. + : key;
  5704. + yield [aliasPath, parameterValue];
  5705. + }
  5706. + }
  5707. + }
  5708. + getWherePredicateCondition(aliasPath, parameterValue) {
  5709. + if (InstanceChecker.isFindOperator(parameterValue)) {
  5710. + let parameters = [];
  5711. + if (parameterValue.useParameter) {
  5712. + if (parameterValue.objectLiteralParameters) {
  5713. + this.setParameters(parameterValue.objectLiteralParameters);
  5714. + } else if (parameterValue.multipleParameters) {
  5715. + for (const v of parameterValue.value) {
  5716. + parameters.push(this.createParameter(v));
  5717. + }
  5718. + } else {
  5719. + parameters.push(this.createParameter(parameterValue.value));
  5720. + }
  5721. + }
  5722. + if (parameterValue.type === 'raw') {
  5723. + if (parameterValue.getSql) {
  5724. + return parameterValue.getSql(aliasPath);
  5725. + } else {
  5726. + return {
  5727. + operator: 'equal',
  5728. + parameters: [aliasPath, parameterValue.value],
  5729. + };
  5730. + }
  5731. + } else if (parameterValue.type === 'not') {
  5732. + if (parameterValue.child) {
  5733. + return {
  5734. + operator: parameterValue.type,
  5735. + condition: this.getWherePredicateCondition(
  5736. + aliasPath,
  5737. + parameterValue.child
  5738. + ),
  5739. + };
  5740. + } else {
  5741. + return {
  5742. + operator: 'notEqual',
  5743. + parameters: [aliasPath, ...parameters],
  5744. + };
  5745. + }
  5746. + } else {
  5747. + return {
  5748. + operator: parameterValue.type,
  5749. + parameters: [aliasPath, ...parameters],
  5750. + };
  5751. + }
  5752. + // } else if (parameterValue === null) {
  5753. + // return {
  5754. + // operator: "isNull",
  5755. + // parameters: [
  5756. + // aliasPath,
  5757. + // ]
  5758. + // };
  5759. + } else {
  5760. + return {
  5761. + operator: 'equal',
  5762. + parameters: [aliasPath, this.createParameter(parameterValue)],
  5763. + };
  5764. + }
  5765. + }
  5766. + getWhereCondition(where) {
  5767. + if (typeof where === 'string') {
  5768. + return where;
  5769. + }
  5770. + if (InstanceChecker.isBrackets(where)) {
  5771. + const whereQueryBuilder = this.createQueryBuilder();
  5772. + whereQueryBuilder.parentQueryBuilder = this;
  5773. + whereQueryBuilder.expressionMap.mainAlias = this.expressionMap.mainAlias;
  5774. + whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
  5775. + this.expressionMap.aliasNamePrefixingEnabled;
  5776. + whereQueryBuilder.expressionMap.parameters =
  5777. + this.expressionMap.parameters;
  5778. + whereQueryBuilder.expressionMap.nativeParameters =
  5779. + this.expressionMap.nativeParameters;
  5780. + whereQueryBuilder.expressionMap.wheres = [];
  5781. + where.whereFactory(whereQueryBuilder);
  5782. + return {
  5783. + operator: InstanceChecker.isNotBrackets(where) ? 'not' : 'brackets',
  5784. + condition: whereQueryBuilder.expressionMap.wheres,
  5785. + };
  5786. + }
  5787. + if (typeof where === 'function') {
  5788. + return where(this);
  5789. + }
  5790. + const wheres = Array.isArray(where) ? where : [where];
  5791. + const clauses = [];
  5792. + for (const where of wheres) {
  5793. + const conditions = [];
  5794. + // Filter the conditions and set up the parameter values
  5795. + for (const [aliasPath, parameterValue] of this.getPredicates(where)) {
  5796. + conditions.push({
  5797. + type: 'and',
  5798. + condition: this.getWherePredicateCondition(aliasPath, parameterValue),
  5799. + });
  5800. + }
  5801. + clauses.push({ type: 'or', condition: conditions });
  5802. + }
  5803. + if (clauses.length === 1) {
  5804. + return clauses[0].condition;
  5805. + }
  5806. + return clauses;
  5807. + }
  5808. + /**
  5809. + * Creates a query builder used to execute sql queries inside this query builder.
  5810. + */
  5811. + obtainQueryRunner() {
  5812. + return this.queryRunner || this.connection.createQueryRunner();
  5813. + }
  5814. + hasCommonTableExpressions() {
  5815. + return this.expressionMap.commonTableExpressions.length > 0;
  5816. + }
  5817. +}
  5818. +
  5819. +//# sourceMappingURL=QueryBuilder.js.map
  5820. diff --git a/node_modules/typeorm/browser/query-builder/UpdateQueryBuilder.js b/node_modules/typeorm/browser/query-builder/UpdateQueryBuilder.js
  5821. index 146434a..0704251 100644
  5822. --- a/node_modules/typeorm/browser/query-builder/UpdateQueryBuilder.js
  5823. +++ b/node_modules/typeorm/browser/query-builder/UpdateQueryBuilder.js
  5824. @@ -1,4 +1,3 @@
  5825. -import { QueryBuilder } from "./QueryBuilder";
  5826. import { UpdateResult } from "./result/UpdateResult";
  5827. import { ReturningStatementNotSupportedError } from "../error/ReturningStatementNotSupportedError";
  5828. import { ReturningResultsEntityUpdator } from "./ReturningResultsEntityUpdator";
  5829. @@ -7,10 +6,11 @@ import { UpdateValuesMissingError } from "../error/UpdateValuesMissingError";
  5830. import { TypeORMError } from "../error";
  5831. import { EntityPropertyNotFoundError } from "../error/EntityPropertyNotFoundError";
  5832. import { DriverUtils } from "../driver/DriverUtils";
  5833. +import { UpdateQueryBuilderBase } from "./UpdateQueryBuilderBase";
  5834. /**
  5835. * Allows to build complex sql queries in a fashion way and execute those queries.
  5836. */
  5837. -export class UpdateQueryBuilder extends QueryBuilder {
  5838. +export class UpdateQueryBuilder extends UpdateQueryBuilderBase {
  5839. // -------------------------------------------------------------------------
  5840. // Constructor
  5841. // -------------------------------------------------------------------------
  5842. diff --git a/node_modules/typeorm/browser/query-builder/UpdateQueryBuilderBase.js b/node_modules/typeorm/browser/query-builder/UpdateQueryBuilderBase.js
  5843. new file mode 100644
  5844. index 0000000..2162f0b
  5845. --- /dev/null
  5846. +++ b/node_modules/typeorm/browser/query-builder/UpdateQueryBuilderBase.js
  5847. @@ -0,0 +1,1133 @@
  5848. +import { QueryExpressionMap } from './QueryExpressionMap';
  5849. +import { Brackets } from './Brackets';
  5850. +import { FindOperator } from '../find-options/FindOperator';
  5851. +import { In } from '../find-options/operator/In';
  5852. +import { TypeORMError } from '../error';
  5853. +import { EntityPropertyNotFoundError } from '../error/EntityPropertyNotFoundError';
  5854. +import { InstanceChecker } from '../util/InstanceChecker';
  5855. +import { escapeRegExp } from '../util/escapeRegExp';
  5856. +// todo: completely cover query builder with tests
  5857. +// todo: entityOrProperty can be target name. implement proper behaviour if it is.
  5858. +// todo: check in persistment if id exist on object and throw exception (can be in partial selection?)
  5859. +// todo: fix problem with long aliases eg getMaxIdentifierLength
  5860. +// todo: fix replacing in .select("COUNT(post.id) AS cnt") statement
  5861. +// todo: implement joinAlways in relations and relationId
  5862. +// todo: finish partial selection
  5863. +// todo: sugar methods like: .addCount and .selectCount, selectCountAndMap, selectSum, selectSumAndMap, ...
  5864. +// todo: implement @Select decorator
  5865. +// todo: add select and map functions
  5866. +// todo: implement relation/entity loading and setting them into properties within a separate query
  5867. +// .loadAndMap("post.categories", "post.categories", qb => ...)
  5868. +// .loadAndMap("post.categories", Category, qb => ...)
  5869. +/**
  5870. + * Allows to build complex sql queries in a fashion way and execute those queries.
  5871. + */
  5872. +export class UpdateQueryBuilderBase {
  5873. + /**
  5874. + * QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
  5875. + */
  5876. + constructor(connectionOrQueryBuilder, queryRunner) {
  5877. + this['@instanceof'] = Symbol.for('QueryBuilder');
  5878. + /**
  5879. + * Memo to help keep place of current parameter index for `createParameter`
  5880. + */
  5881. + this.parameterIndex = 0;
  5882. + if (InstanceChecker.isQueryBuilder(connectionOrQueryBuilder)) {
  5883. + this.connection = connectionOrQueryBuilder.connection;
  5884. + this.queryRunner = connectionOrQueryBuilder.queryRunner;
  5885. + this.expressionMap = connectionOrQueryBuilder.expressionMap.clone();
  5886. + } else {
  5887. + this.connection = connectionOrQueryBuilder;
  5888. + this.queryRunner = queryRunner;
  5889. + this.expressionMap = new QueryExpressionMap(this.connection);
  5890. + }
  5891. + }
  5892. + // -------------------------------------------------------------------------
  5893. + // Accessors
  5894. + // -------------------------------------------------------------------------
  5895. + /**
  5896. + * Gets the main alias string used in this query builder.
  5897. + */
  5898. + get alias() {
  5899. + if (!this.expressionMap.mainAlias)
  5900. + throw new TypeORMError(`Main alias is not set`); // todo: better exception
  5901. + return this.expressionMap.mainAlias.name;
  5902. + }
  5903. + /**
  5904. + * Creates SELECT query and selects given data.
  5905. + * Replaces all previous selections if they exist.
  5906. + */
  5907. + select(selection, selectionAliasName) {
  5908. + this.expressionMap.queryType = 'select';
  5909. + if (Array.isArray(selection)) {
  5910. + this.expressionMap.selects = selection.map((selection) => ({
  5911. + selection: selection,
  5912. + }));
  5913. + } else if (selection) {
  5914. + this.expressionMap.selects = [
  5915. + { selection: selection, aliasName: selectionAliasName },
  5916. + ];
  5917. + }
  5918. + // loading it dynamically because of circular issue
  5919. + const SelectQueryBuilderCls =
  5920. + require('typeorm/browser/query-builder/SelectQueryBuilder').SelectQueryBuilder;
  5921. + if (InstanceChecker.isSelectQueryBuilder(this)) return this;
  5922. + return new SelectQueryBuilderCls(this);
  5923. + }
  5924. + /**
  5925. + * Creates INSERT query.
  5926. + */
  5927. + insert() {
  5928. + this.expressionMap.queryType = 'insert';
  5929. + // loading it dynamically because of circular issue
  5930. + const InsertQueryBuilderCls =
  5931. + require('typeorm/browser/query-builder/InsertQueryBuilder').InsertQueryBuilder;
  5932. + if (InstanceChecker.isInsertQueryBuilder(this)) return this;
  5933. + return new InsertQueryBuilderCls(this);
  5934. + }
  5935. + /**
  5936. + * Creates UPDATE query and applies given update values.
  5937. + */
  5938. + update(entityOrTableNameUpdateSet, maybeUpdateSet) {
  5939. + const updateSet = maybeUpdateSet
  5940. + ? maybeUpdateSet
  5941. + : entityOrTableNameUpdateSet;
  5942. + entityOrTableNameUpdateSet = InstanceChecker.isEntitySchema(
  5943. + entityOrTableNameUpdateSet
  5944. + )
  5945. + ? entityOrTableNameUpdateSet.options.name
  5946. + : entityOrTableNameUpdateSet;
  5947. + if (
  5948. + typeof entityOrTableNameUpdateSet === 'function' ||
  5949. + typeof entityOrTableNameUpdateSet === 'string'
  5950. + ) {
  5951. + const mainAlias = this.createFromAlias(entityOrTableNameUpdateSet);
  5952. + this.expressionMap.setMainAlias(mainAlias);
  5953. + }
  5954. + this.expressionMap.queryType = 'update';
  5955. + this.expressionMap.valuesSet = updateSet;
  5956. + // loading it dynamically because of circular issue
  5957. + const UpdateQueryBuilderCls =
  5958. + require('typeorm/browser/query-builder/UpdateQueryBuilder').UpdateQueryBuilder;
  5959. + if (InstanceChecker.isUpdateQueryBuilder(this)) return this;
  5960. + return new UpdateQueryBuilderCls(this);
  5961. + }
  5962. + /**
  5963. + * Creates DELETE query.
  5964. + */
  5965. + delete() {
  5966. + this.expressionMap.queryType = 'delete';
  5967. + // loading it dynamically because of circular issue
  5968. + const DeleteQueryBuilderCls =
  5969. + require('typeorm/browser/query-builder/DeleteQueryBuilder').DeleteQueryBuilder;
  5970. + if (InstanceChecker.isDeleteQueryBuilder(this)) return this;
  5971. + return new DeleteQueryBuilderCls(this);
  5972. + }
  5973. + softDelete() {
  5974. + this.expressionMap.queryType = 'soft-delete';
  5975. + // loading it dynamically because of circular issue
  5976. + const SoftDeleteQueryBuilderCls =
  5977. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  5978. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  5979. + return new SoftDeleteQueryBuilderCls(this);
  5980. + }
  5981. + restore() {
  5982. + this.expressionMap.queryType = 'restore';
  5983. + // loading it dynamically because of circular issue
  5984. + const SoftDeleteQueryBuilderCls =
  5985. + require('typeorm/browser/query-builder/SoftDeleteQueryBuilder').SoftDeleteQueryBuilder;
  5986. + if (InstanceChecker.isSoftDeleteQueryBuilder(this)) return this;
  5987. + return new SoftDeleteQueryBuilderCls(this);
  5988. + }
  5989. + /**
  5990. + * Sets entity's relation with which this query builder gonna work.
  5991. + */
  5992. + relation(entityTargetOrPropertyPath, maybePropertyPath) {
  5993. + const entityTarget =
  5994. + arguments.length === 2 ? entityTargetOrPropertyPath : undefined;
  5995. + const propertyPath =
  5996. + arguments.length === 2 ? maybePropertyPath : entityTargetOrPropertyPath;
  5997. + this.expressionMap.queryType = 'relation';
  5998. + this.expressionMap.relationPropertyPath = propertyPath;
  5999. + if (entityTarget) {
  6000. + const mainAlias = this.createFromAlias(entityTarget);
  6001. + this.expressionMap.setMainAlias(mainAlias);
  6002. + }
  6003. + // loading it dynamically because of circular issue
  6004. + const RelationQueryBuilderCls =
  6005. + require('typeorm/browser/query-builder/RelationQueryBuilder').RelationQueryBuilder;
  6006. + if (InstanceChecker.isRelationQueryBuilder(this)) return this;
  6007. + return new RelationQueryBuilderCls(this);
  6008. + }
  6009. + /**
  6010. + * Checks if given relation or relations exist in the entity.
  6011. + * Returns true if relation exists, false otherwise.
  6012. + *
  6013. + * todo: move this method to manager? or create a shortcut?
  6014. + */
  6015. + hasRelation(target, relation) {
  6016. + const entityMetadata = this.connection.getMetadata(target);
  6017. + const relations = Array.isArray(relation) ? relation : [relation];
  6018. + return relations.every((relation) => {
  6019. + return !!entityMetadata.findRelationWithPropertyPath(relation);
  6020. + });
  6021. + }
  6022. + /**
  6023. + * Check the existence of a parameter for this query builder.
  6024. + */
  6025. + hasParameter(key) {
  6026. + var _a;
  6027. + return (
  6028. + ((_a = this.parentQueryBuilder) === null || _a === void 0
  6029. + ? void 0
  6030. + : _a.hasParameter(key)) || key in this.expressionMap.parameters
  6031. + );
  6032. + }
  6033. + /**
  6034. + * Sets parameter name and its value.
  6035. + *
  6036. + * The key for this parameter may contain numbers, letters, underscores, or periods.
  6037. + */
  6038. + setParameter(key, value) {
  6039. + if (typeof value === 'function') {
  6040. + throw new TypeORMError(
  6041. + `Function parameter isn't supported in the parameters. Please check "${key}" parameter.`
  6042. + );
  6043. + }
  6044. + if (!key.match(/^([A-Za-z0-9_.]+)$/)) {
  6045. + throw new TypeORMError(
  6046. + 'QueryBuilder parameter keys may only contain numbers, letters, underscores, or periods.'
  6047. + );
  6048. + }
  6049. + if (this.parentQueryBuilder) {
  6050. + this.parentQueryBuilder.setParameter(key, value);
  6051. + }
  6052. + this.expressionMap.parameters[key] = value;
  6053. + return this;
  6054. + }
  6055. + /**
  6056. + * Adds all parameters from the given object.
  6057. + */
  6058. + setParameters(parameters) {
  6059. + for (const [key, value] of Object.entries(parameters)) {
  6060. + this.setParameter(key, value);
  6061. + }
  6062. + return this;
  6063. + }
  6064. + createParameter(value) {
  6065. + let parameterName;
  6066. + do {
  6067. + parameterName = `orm_param_${this.parameterIndex++}`;
  6068. + } while (this.hasParameter(parameterName));
  6069. + this.setParameter(parameterName, value);
  6070. + return `:${parameterName}`;
  6071. + }
  6072. + /**
  6073. + * Adds native parameters from the given object.
  6074. + *
  6075. + * @deprecated Use `setParameters` instead
  6076. + */
  6077. + setNativeParameters(parameters) {
  6078. + // set parent query builder parameters as well in sub-query mode
  6079. + if (this.parentQueryBuilder) {
  6080. + this.parentQueryBuilder.setNativeParameters(parameters);
  6081. + }
  6082. + Object.keys(parameters).forEach((key) => {
  6083. + this.expressionMap.nativeParameters[key] = parameters[key];
  6084. + });
  6085. + return this;
  6086. + }
  6087. + /**
  6088. + * Gets all parameters.
  6089. + */
  6090. + getParameters() {
  6091. + const parameters = Object.assign({}, this.expressionMap.parameters);
  6092. + // add discriminator column parameter if it exist
  6093. + if (
  6094. + this.expressionMap.mainAlias &&
  6095. + this.expressionMap.mainAlias.hasMetadata
  6096. + ) {
  6097. + const metadata = this.expressionMap.mainAlias.metadata;
  6098. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  6099. + const values = metadata.childEntityMetadatas
  6100. + .filter((childMetadata) => childMetadata.discriminatorColumn)
  6101. + .map((childMetadata) => childMetadata.discriminatorValue);
  6102. + values.push(metadata.discriminatorValue);
  6103. + parameters['discriminatorColumnValues'] = values;
  6104. + }
  6105. + }
  6106. + return parameters;
  6107. + }
  6108. + /**
  6109. + * Prints sql to stdout using console.log.
  6110. + */
  6111. + printSql() {
  6112. + // TODO rename to logSql()
  6113. + const [query, parameters] = this.getQueryAndParameters();
  6114. + this.connection.logger.logQuery(query, parameters);
  6115. + return this;
  6116. + }
  6117. + /**
  6118. + * Gets generated sql that will be executed.
  6119. + * Parameters in the query are escaped for the currently used driver.
  6120. + */
  6121. + getSql() {
  6122. + return this.getQueryAndParameters()[0];
  6123. + }
  6124. + /**
  6125. + * Gets query to be executed with all parameters used in it.
  6126. + */
  6127. + getQueryAndParameters() {
  6128. + // this execution order is important because getQuery method generates this.expressionMap.nativeParameters values
  6129. + const query = this.getQuery();
  6130. + const parameters = this.getParameters();
  6131. + return this.connection.driver.escapeQueryWithParameters(
  6132. + query,
  6133. + parameters,
  6134. + this.expressionMap.nativeParameters
  6135. + );
  6136. + }
  6137. + /**
  6138. + * Executes sql generated by query builder and returns raw database results.
  6139. + */
  6140. + async execute() {
  6141. + const [sql, parameters] = this.getQueryAndParameters();
  6142. + const queryRunner = this.obtainQueryRunner();
  6143. + try {
  6144. + return await queryRunner.query(sql, parameters); // await is needed here because we are using finally
  6145. + } finally {
  6146. + if (queryRunner !== this.queryRunner) {
  6147. + // means we created our own query runner
  6148. + await queryRunner.release();
  6149. + }
  6150. + }
  6151. + }
  6152. + /**
  6153. + * Creates a completely new query builder.
  6154. + * Uses same query runner as current QueryBuilder.
  6155. + */
  6156. + createQueryBuilder() {
  6157. + return new this.constructor(this.connection, this.queryRunner);
  6158. + }
  6159. + /**
  6160. + * Clones query builder as it is.
  6161. + * Note: it uses new query runner, if you want query builder that uses exactly same query runner,
  6162. + * you can create query builder using its constructor, for example new SelectQueryBuilder(queryBuilder)
  6163. + * where queryBuilder is cloned QueryBuilder.
  6164. + */
  6165. + clone() {
  6166. + return new this.constructor(this);
  6167. + }
  6168. + /**
  6169. + * Includes a Query comment in the query builder. This is helpful for debugging purposes,
  6170. + * such as finding a specific query in the database server's logs, or for categorization using
  6171. + * an APM product.
  6172. + */
  6173. + comment(comment) {
  6174. + this.expressionMap.comment = comment;
  6175. + return this;
  6176. + }
  6177. + /**
  6178. + * Disables escaping.
  6179. + */
  6180. + disableEscaping() {
  6181. + this.expressionMap.disableEscaping = false;
  6182. + return this;
  6183. + }
  6184. + /**
  6185. + * Escapes table name, column name or alias name using current database's escaping character.
  6186. + */
  6187. + escape(name) {
  6188. + if (!this.expressionMap.disableEscaping) return name;
  6189. + return this.connection.driver.escape(name);
  6190. + }
  6191. + /**
  6192. + * Sets or overrides query builder's QueryRunner.
  6193. + */
  6194. + setQueryRunner(queryRunner) {
  6195. + this.queryRunner = queryRunner;
  6196. + return this;
  6197. + }
  6198. + /**
  6199. + * Indicates if listeners and subscribers must be called before and after query execution.
  6200. + * Enabled by default.
  6201. + */
  6202. + callListeners(enabled) {
  6203. + this.expressionMap.callListeners = enabled;
  6204. + return this;
  6205. + }
  6206. + /**
  6207. + * If set to true the query will be wrapped into a transaction.
  6208. + */
  6209. + useTransaction(enabled) {
  6210. + this.expressionMap.useTransaction = enabled;
  6211. + return this;
  6212. + }
  6213. + /**
  6214. + * Adds CTE to query
  6215. + */
  6216. + addCommonTableExpression(queryBuilder, alias, options) {
  6217. + this.expressionMap.commonTableExpressions.push({
  6218. + queryBuilder,
  6219. + alias,
  6220. + options: options || {},
  6221. + });
  6222. + return this;
  6223. + }
  6224. + // -------------------------------------------------------------------------
  6225. + // Protected Methods
  6226. + // -------------------------------------------------------------------------
  6227. + /**
  6228. + * Gets escaped table name with schema name if SqlServer driver used with custom
  6229. + * schema name, otherwise returns escaped table name.
  6230. + */
  6231. + getTableName(tablePath) {
  6232. + return tablePath
  6233. + .split('.')
  6234. + .map((i) => {
  6235. + // this condition need because in SQL Server driver when custom database name was specified and schema name was not, we got `dbName..tableName` string, and doesn't need to escape middle empty string
  6236. + if (i === '') return i;
  6237. + return this.escape(i);
  6238. + })
  6239. + .join('.');
  6240. + }
  6241. + /**
  6242. + * Gets name of the table where insert should be performed.
  6243. + */
  6244. + getMainTableName() {
  6245. + if (!this.expressionMap.mainAlias)
  6246. + throw new TypeORMError(
  6247. + `Entity where values should be inserted is not specified. Call "qb.into(entity)" method to specify it.`
  6248. + );
  6249. + if (this.expressionMap.mainAlias.hasMetadata)
  6250. + return this.expressionMap.mainAlias.metadata.tablePath;
  6251. + return this.expressionMap.mainAlias.tablePath;
  6252. + }
  6253. + /**
  6254. + * Specifies FROM which entity's table select/update/delete will be executed.
  6255. + * Also sets a main string alias of the selection data.
  6256. + */
  6257. + createFromAlias(entityTarget, aliasName) {
  6258. + // if table has a metadata then find it to properly escape its properties
  6259. + // const metadata = this.connection.entityMetadatas.find(metadata => metadata.tableName === tableName);
  6260. + if (this.connection.hasMetadata(entityTarget)) {
  6261. + const metadata = this.connection.getMetadata(entityTarget);
  6262. + return this.expressionMap.createAlias({
  6263. + type: 'from',
  6264. + name: aliasName,
  6265. + metadata: this.connection.getMetadata(entityTarget),
  6266. + tablePath: metadata.tablePath,
  6267. + });
  6268. + } else {
  6269. + if (typeof entityTarget === 'string') {
  6270. + const isSubquery =
  6271. + entityTarget.substr(0, 1) === '(' && entityTarget.substr(-1) === ')';
  6272. + return this.expressionMap.createAlias({
  6273. + type: 'from',
  6274. + name: aliasName,
  6275. + tablePath: !isSubquery ? entityTarget : undefined,
  6276. + subQuery: isSubquery ? entityTarget : undefined,
  6277. + });
  6278. + }
  6279. + const subQueryBuilder = entityTarget(this.subQuery());
  6280. + this.setParameters(subQueryBuilder.getParameters());
  6281. + const subquery = subQueryBuilder.getQuery();
  6282. + return this.expressionMap.createAlias({
  6283. + type: 'from',
  6284. + name: aliasName,
  6285. + subQuery: subquery,
  6286. + });
  6287. + }
  6288. + }
  6289. + /**
  6290. + * Replaces all entity's propertyName to name in the given statement.
  6291. + */
  6292. + replacePropertyNames(statement) {
  6293. + for (const alias of this.expressionMap.aliases) {
  6294. + if (!alias.hasMetadata) continue;
  6295. + const replaceAliasNamePrefix = this.expressionMap
  6296. + .aliasNamePrefixingEnabled
  6297. + ? `${alias.name}.`
  6298. + : '';
  6299. + const replacementAliasNamePrefix = this.expressionMap
  6300. + .aliasNamePrefixingEnabled
  6301. + ? `${this.escape(alias.name)}.`
  6302. + : '';
  6303. + const replacements = {};
  6304. + // Insert & overwrite the replacements from least to most relevant in our replacements object.
  6305. + // To do this we iterate and overwrite in the order of relevance.
  6306. + // Least to Most Relevant:
  6307. + // * Relation Property Path to first join column key
  6308. + // * Relation Property Path + Column Path
  6309. + // * Column Database Name
  6310. + // * Column Property Name
  6311. + // * Column Property Path
  6312. + for (const relation of alias.metadata.relations) {
  6313. + if (relation.joinColumns.length > 0)
  6314. + replacements[relation.propertyPath] =
  6315. + relation.joinColumns[0].databaseName;
  6316. + }
  6317. + for (const relation of alias.metadata.relations) {
  6318. + for (const joinColumn of [
  6319. + ...relation.joinColumns,
  6320. + ...relation.inverseJoinColumns,
  6321. + ]) {
  6322. + const propertyKey = `${relation.propertyPath}.${joinColumn.referencedColumn.propertyPath}`;
  6323. + replacements[propertyKey] = joinColumn.databaseName;
  6324. + }
  6325. + }
  6326. + for (const column of alias.metadata.columns) {
  6327. + replacements[column.databaseName] = column.databaseName;
  6328. + }
  6329. + for (const column of alias.metadata.columns) {
  6330. + replacements[column.propertyName] = column.databaseName;
  6331. + }
  6332. + for (const column of alias.metadata.columns) {
  6333. + replacements[column.propertyPath] = column.databaseName;
  6334. + }
  6335. + statement = statement.replace(
  6336. + new RegExp(
  6337. + // Avoid a lookbehind here since it's not well supported
  6338. + `([ =\(]|^.{0})` + // any of ' =(' or start of line
  6339. + // followed by our prefix, e.g. 'tablename.' or ''
  6340. + `${escapeRegExp(replaceAliasNamePrefix)}([^ =\(\)\,]+)` + // a possible property name: sequence of anything but ' =(),'
  6341. + // terminated by ' =),' or end of line
  6342. + `(?=[ =\)\,]|.{0}$)`,
  6343. + 'gm'
  6344. + ),
  6345. + (match, pre, p) => {
  6346. + if (replacements[p]) {
  6347. + return `${pre}${replacementAliasNamePrefix}${this.escape(
  6348. + replacements[p]
  6349. + )}`;
  6350. + }
  6351. + return match;
  6352. + }
  6353. + );
  6354. + }
  6355. + return statement;
  6356. + }
  6357. + createComment() {
  6358. + if (!this.expressionMap.comment) {
  6359. + return '';
  6360. + }
  6361. + // ANSI SQL 2003 support C style comments - comments that start with `/*` and end with `*/`
  6362. + // In some dialects query nesting is available - but not all. Because of this, we'll need
  6363. + // to scrub "ending" characters from the SQL but otherwise we can leave everything else
  6364. + // as-is and it should be valid.
  6365. + return `/* ${this.expressionMap.comment.replace('*/', '')} */ `;
  6366. + }
  6367. + /**
  6368. + * Creates "WHERE" expression.
  6369. + */
  6370. + createWhereExpression() {
  6371. + const conditionsArray = [];
  6372. + const whereExpression = this.createWhereClausesExpression(
  6373. + this.expressionMap.wheres
  6374. + );
  6375. + if (whereExpression.length > 0 && whereExpression !== '1=1') {
  6376. + conditionsArray.push(this.replacePropertyNames(whereExpression));
  6377. + }
  6378. + if (this.expressionMap.mainAlias.hasMetadata) {
  6379. + const metadata = this.expressionMap.mainAlias.metadata;
  6380. + // Adds the global condition of "non-deleted" for the entity with delete date columns in select query.
  6381. + if (
  6382. + this.expressionMap.queryType === 'select' &&
  6383. + !this.expressionMap.withDeleted &&
  6384. + metadata.deleteDateColumn
  6385. + ) {
  6386. + const column = this.expressionMap.aliasNamePrefixingEnabled
  6387. + ? this.expressionMap.mainAlias.name +
  6388. + '.' +
  6389. + metadata.deleteDateColumn.propertyName
  6390. + : metadata.deleteDateColumn.propertyName;
  6391. + const condition = `${this.replacePropertyNames(column)} IS NULL`;
  6392. + conditionsArray.push(condition);
  6393. + }
  6394. + if (metadata.discriminatorColumn && metadata.parentEntityMetadata) {
  6395. + const column = this.expressionMap.aliasNamePrefixingEnabled
  6396. + ? this.expressionMap.mainAlias.name +
  6397. + '.' +
  6398. + metadata.discriminatorColumn.databaseName
  6399. + : metadata.discriminatorColumn.databaseName;
  6400. + const condition = `${this.replacePropertyNames(
  6401. + column
  6402. + )} IN (:...discriminatorColumnValues)`;
  6403. + conditionsArray.push(condition);
  6404. + }
  6405. + }
  6406. + if (this.expressionMap.extraAppendedAndWhereCondition) {
  6407. + const condition = this.replacePropertyNames(
  6408. + this.expressionMap.extraAppendedAndWhereCondition
  6409. + );
  6410. + conditionsArray.push(condition);
  6411. + }
  6412. + if (!conditionsArray.length) {
  6413. + return '';
  6414. + } else if (conditionsArray.length === 1) {
  6415. + return ` WHERE ${conditionsArray[0]}`;
  6416. + } else {
  6417. + return ` WHERE ( ${conditionsArray.join(' ) AND ( ')} )`;
  6418. + }
  6419. + }
  6420. + /**
  6421. + * Creates "RETURNING" / "OUTPUT" expression.
  6422. + */
  6423. + createReturningExpression(returningType) {
  6424. + const columns = this.getReturningColumns();
  6425. + const driver = this.connection.driver;
  6426. + // also add columns we must auto-return to perform entity updation
  6427. + // if user gave his own returning
  6428. + if (
  6429. + typeof this.expressionMap.returning !== 'string' &&
  6430. + this.expressionMap.extraReturningColumns.length > 0 &&
  6431. + driver.isReturningSqlSupported(returningType)
  6432. + ) {
  6433. + columns.push(
  6434. + ...this.expressionMap.extraReturningColumns.filter((column) => {
  6435. + return columns.indexOf(column) === -1;
  6436. + })
  6437. + );
  6438. + }
  6439. + if (columns.length) {
  6440. + let columnsExpression = columns
  6441. + .map((column) => {
  6442. + const name = this.escape(column.databaseName);
  6443. + if (driver.options.type === 'mssql') {
  6444. + if (
  6445. + this.expressionMap.queryType === 'insert' ||
  6446. + this.expressionMap.queryType === 'update' ||
  6447. + this.expressionMap.queryType === 'soft-delete' ||
  6448. + this.expressionMap.queryType === 'restore'
  6449. + ) {
  6450. + return 'INSERTED.' + name;
  6451. + } else {
  6452. + return this.escape(this.getMainTableName()) + '.' + name;
  6453. + }
  6454. + } else {
  6455. + return name;
  6456. + }
  6457. + })
  6458. + .join(', ');
  6459. + if (driver.options.type === 'oracle') {
  6460. + columnsExpression +=
  6461. + ' INTO ' +
  6462. + columns
  6463. + .map((column) => {
  6464. + return this.createParameter({
  6465. + type: driver.columnTypeToNativeParameter(column.type),
  6466. + dir: driver.oracle.BIND_OUT,
  6467. + });
  6468. + })
  6469. + .join(', ');
  6470. + }
  6471. + if (driver.options.type === 'mssql') {
  6472. + if (
  6473. + this.expressionMap.queryType === 'insert' ||
  6474. + this.expressionMap.queryType === 'update'
  6475. + ) {
  6476. + columnsExpression += ' INTO @OutputTable';
  6477. + }
  6478. + }
  6479. + return columnsExpression;
  6480. + } else if (typeof this.expressionMap.returning === 'string') {
  6481. + return this.expressionMap.returning;
  6482. + }
  6483. + return '';
  6484. + }
  6485. + /**
  6486. + * If returning / output cause is set to array of column names,
  6487. + * then this method will return all column metadatas of those column names.
  6488. + */
  6489. + getReturningColumns() {
  6490. + const columns = [];
  6491. + if (Array.isArray(this.expressionMap.returning)) {
  6492. + this.expressionMap.returning.forEach((columnName) => {
  6493. + if (this.expressionMap.mainAlias.hasMetadata) {
  6494. + columns.push(
  6495. + ...this.expressionMap.mainAlias.metadata.findColumnsWithPropertyPath(
  6496. + columnName
  6497. + )
  6498. + );
  6499. + }
  6500. + });
  6501. + }
  6502. + return columns;
  6503. + }
  6504. + createWhereClausesExpression(clauses) {
  6505. + return clauses
  6506. + .map((clause, index) => {
  6507. + const expression = this.createWhereConditionExpression(
  6508. + clause.condition
  6509. + );
  6510. + switch (clause.type) {
  6511. + case 'and':
  6512. + return (index > 0 ? 'AND ' : '') + expression;
  6513. + case 'or':
  6514. + return (index > 0 ? 'OR ' : '') + expression;
  6515. + }
  6516. + return expression;
  6517. + })
  6518. + .join(' ')
  6519. + .trim();
  6520. + }
  6521. + /**
  6522. + * Computes given where argument - transforms to a where string all forms it can take.
  6523. + */
  6524. + createWhereConditionExpression(condition, alwaysWrap = false) {
  6525. + if (typeof condition === 'string') return condition;
  6526. + if (Array.isArray(condition)) {
  6527. + if (condition.length === 0) {
  6528. + return '1=1';
  6529. + }
  6530. + // In the future we should probably remove this entire condition
  6531. + // but for now to prevent any breaking changes it exists.
  6532. + if (condition.length === 1 && !alwaysWrap) {
  6533. + return this.createWhereClausesExpression(condition);
  6534. + }
  6535. + return '(' + this.createWhereClausesExpression(condition) + ')';
  6536. + }
  6537. + const { driver } = this.connection;
  6538. + switch (condition.operator) {
  6539. + case 'lessThan':
  6540. + return `${condition.parameters[0]} < ${condition.parameters[1]}`;
  6541. + case 'lessThanOrEqual':
  6542. + return `${condition.parameters[0]} <= ${condition.parameters[1]}`;
  6543. + case 'arrayContains':
  6544. + return `${condition.parameters[0]} @> ${condition.parameters[1]}`;
  6545. + case 'arrayContainedBy':
  6546. + return `${condition.parameters[0]} <@ ${condition.parameters[1]}`;
  6547. + case 'arrayOverlap':
  6548. + return `${condition.parameters[0]} && ${condition.parameters[1]}`;
  6549. + case 'moreThan':
  6550. + return `${condition.parameters[0]} > ${condition.parameters[1]}`;
  6551. + case 'moreThanOrEqual':
  6552. + return `${condition.parameters[0]} >= ${condition.parameters[1]}`;
  6553. + case 'notEqual':
  6554. + return `${condition.parameters[0]} != ${condition.parameters[1]}`;
  6555. + case 'equal':
  6556. + return `${condition.parameters[0]} = ${condition.parameters[1]}`;
  6557. + case 'ilike':
  6558. + if (
  6559. + driver.options.type === 'postgres' ||
  6560. + driver.options.type === 'cockroachdb'
  6561. + ) {
  6562. + return `${condition.parameters[0]} ILIKE ${condition.parameters[1]}`;
  6563. + }
  6564. + return `UPPER(${condition.parameters[0]}) LIKE UPPER(${condition.parameters[1]})`;
  6565. + case 'like':
  6566. + return `${condition.parameters[0]} LIKE ${condition.parameters[1]}`;
  6567. + case 'between':
  6568. + return `${condition.parameters[0]} BETWEEN ${condition.parameters[1]} AND ${condition.parameters[2]}`;
  6569. + case 'in':
  6570. + if (condition.parameters.length <= 1) {
  6571. + return '0=1';
  6572. + }
  6573. + return `${condition.parameters[0]} IN (${condition.parameters
  6574. + .slice(1)
  6575. + .join(', ')})`;
  6576. + case 'any':
  6577. + return `${condition.parameters[0]} = ANY(${condition.parameters[1]})`;
  6578. + case 'isNull':
  6579. + return `${condition.parameters[0]} IS NULL`;
  6580. + case 'not':
  6581. + return `NOT(${this.createWhereConditionExpression(
  6582. + condition.condition
  6583. + )})`;
  6584. + case 'brackets':
  6585. + return `${this.createWhereConditionExpression(
  6586. + condition.condition,
  6587. + true
  6588. + )}`;
  6589. + }
  6590. + throw new TypeError(
  6591. + `Unsupported FindOperator ${FindOperator.constructor.name}`
  6592. + );
  6593. + }
  6594. + createCteExpression() {
  6595. + if (!this.hasCommonTableExpressions()) {
  6596. + return '';
  6597. + }
  6598. + const databaseRequireRecusiveHint =
  6599. + this.connection.driver.cteCapabilities.requiresRecursiveHint;
  6600. + const cteStrings = this.expressionMap.commonTableExpressions.map((cte) => {
  6601. + const cteBodyExpression =
  6602. + typeof cte.queryBuilder === 'string'
  6603. + ? cte.queryBuilder
  6604. + : cte.queryBuilder.getQuery();
  6605. + if (typeof cte.queryBuilder !== 'string') {
  6606. + if (cte.queryBuilder.hasCommonTableExpressions()) {
  6607. + throw new TypeORMError(
  6608. + `Nested CTEs aren't supported (CTE: ${cte.alias})`
  6609. + );
  6610. + }
  6611. + if (
  6612. + !this.connection.driver.cteCapabilities.writable &&
  6613. + !InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)
  6614. + ) {
  6615. + throw new TypeORMError(
  6616. + `Only select queries are supported in CTEs in ${this.connection.options.type} (CTE: ${cte.alias})`
  6617. + );
  6618. + }
  6619. + this.setParameters(cte.queryBuilder.getParameters());
  6620. + }
  6621. + let cteHeader = this.escape(cte.alias);
  6622. + if (cte.options.columnNames) {
  6623. + const escapedColumnNames = cte.options.columnNames.map((column) =>
  6624. + this.escape(column)
  6625. + );
  6626. + if (InstanceChecker.isSelectQueryBuilder(cte.queryBuilder)) {
  6627. + if (
  6628. + cte.queryBuilder.expressionMap.selects.length &&
  6629. + cte.options.columnNames.length !==
  6630. + cte.queryBuilder.expressionMap.selects.length
  6631. + ) {
  6632. + throw new TypeORMError(
  6633. + `cte.options.columnNames length (${cte.options.columnNames.length}) doesn't match subquery select list length ${cte.queryBuilder.expressionMap.selects.length} (CTE: ${cte.alias})`
  6634. + );
  6635. + }
  6636. + }
  6637. + cteHeader += `(${escapedColumnNames.join(', ')})`;
  6638. + }
  6639. + const recursiveClause =
  6640. + cte.options.recursive && databaseRequireRecusiveHint ? 'RECURSIVE' : '';
  6641. + const materializeClause =
  6642. + cte.options.materialized &&
  6643. + this.connection.driver.cteCapabilities.materializedHint
  6644. + ? 'MATERIALIZED'
  6645. + : '';
  6646. + return [
  6647. + recursiveClause,
  6648. + cteHeader,
  6649. + materializeClause,
  6650. + 'AS',
  6651. + `(${cteBodyExpression})`,
  6652. + ]
  6653. + .filter(Boolean)
  6654. + .join(' ');
  6655. + });
  6656. + return 'WITH ' + cteStrings.join(', ') + ' ';
  6657. + }
  6658. + /**
  6659. + * Creates "WHERE" condition for an in-ids condition.
  6660. + */
  6661. + getWhereInIdsCondition(ids) {
  6662. + const metadata = this.expressionMap.mainAlias.metadata;
  6663. + const normalized = (Array.isArray(ids) ? ids : [ids]).map((id) =>
  6664. + metadata.ensureEntityIdMap(id)
  6665. + );
  6666. + // using in(...ids) for single primary key entities
  6667. + if (!metadata.hasMultiplePrimaryKeys) {
  6668. + const primaryColumn = metadata.primaryColumns[0];
  6669. + // getEntityValue will try to transform `In`, it is a bug
  6670. + // todo: remove this transformer check after #2390 is fixed
  6671. + // This also fails for embedded & relation, so until that is fixed skip it.
  6672. + if (
  6673. + !primaryColumn.transformer &&
  6674. + !primaryColumn.relationMetadata &&
  6675. + !primaryColumn.embeddedMetadata
  6676. + ) {
  6677. + return {
  6678. + [primaryColumn.propertyName]: In(
  6679. + normalized.map((id) => primaryColumn.getEntityValue(id, false))
  6680. + ),
  6681. + };
  6682. + }
  6683. + }
  6684. + return new Brackets((qb) => {
  6685. + for (const data of normalized) {
  6686. + qb.orWhere(new Brackets((qb) => qb.where(data)));
  6687. + }
  6688. + });
  6689. + }
  6690. + findColumnsForPropertyPath(propertyPath) {
  6691. + // Make a helper to iterate the entity & relations?
  6692. + // Use that to set the correct alias? Or the other way around?
  6693. + // Start with the main alias with our property paths
  6694. + let alias = this.expressionMap.mainAlias;
  6695. + const root = [];
  6696. + const propertyPathParts = propertyPath.split('.');
  6697. + while (propertyPathParts.length > 1) {
  6698. + const part = propertyPathParts[0];
  6699. + if (!(alias === null || alias === void 0 ? void 0 : alias.hasMetadata)) {
  6700. + // If there's no metadata, we're wasting our time
  6701. + // and can't actually look any of this up.
  6702. + break;
  6703. + }
  6704. + if (alias.metadata.hasEmbeddedWithPropertyPath(part)) {
  6705. + // If this is an embedded then we should combine the two as part of our lookup.
  6706. + // Instead of just breaking, we keep going with this in case there's an embedded/relation
  6707. + // inside an embedded.
  6708. + propertyPathParts.unshift(
  6709. + `${propertyPathParts.shift()}.${propertyPathParts.shift()}`
  6710. + );
  6711. + continue;
  6712. + }
  6713. + if (alias.metadata.hasRelationWithPropertyPath(part)) {
  6714. + // If this is a relation then we should find the aliases
  6715. + // that match the relation & then continue further down
  6716. + // the property path
  6717. + const joinAttr = this.expressionMap.joinAttributes.find(
  6718. + (joinAttr) => joinAttr.relationPropertyPath === part
  6719. + );
  6720. + if (
  6721. + !(joinAttr === null || joinAttr === void 0 ? void 0 : joinAttr.alias)
  6722. + ) {
  6723. + const fullRelationPath =
  6724. + root.length > 0 ? `${root.join('.')}.${part}` : part;
  6725. + throw new Error(
  6726. + `Cannot find alias for relation at ${fullRelationPath}`
  6727. + );
  6728. + }
  6729. + alias = joinAttr.alias;
  6730. + root.push(...part.split('.'));
  6731. + propertyPathParts.shift();
  6732. + continue;
  6733. + }
  6734. + break;
  6735. + }
  6736. + if (!alias) {
  6737. + throw new Error(`Cannot find alias for property ${propertyPath}`);
  6738. + }
  6739. + // Remaining parts are combined back and used to find the actual property path
  6740. + const aliasPropertyPath = propertyPathParts.join('.');
  6741. + const columns =
  6742. + alias.metadata.findColumnsWithPropertyPath(aliasPropertyPath);
  6743. + if (!columns.length) {
  6744. + throw new EntityPropertyNotFoundError(propertyPath, alias.metadata);
  6745. + }
  6746. + return [alias, root, columns];
  6747. + }
  6748. + /**
  6749. + * Creates a property paths for a given ObjectLiteral.
  6750. + */
  6751. + createPropertyPath(metadata, entity, prefix = '') {
  6752. + const paths = [];
  6753. + for (const key of Object.keys(entity)) {
  6754. + const path = prefix ? `${prefix}.${key}` : key;
  6755. + // There's times where we don't actually want to traverse deeper.
  6756. + // If the value is a `FindOperator`, or null, or not an object, then we don't, for example.
  6757. + if (
  6758. + entity[key] === null ||
  6759. + typeof entity[key] !== 'object' ||
  6760. + InstanceChecker.isFindOperator(entity[key])
  6761. + ) {
  6762. + paths.push(path);
  6763. + continue;
  6764. + }
  6765. + if (metadata.hasEmbeddedWithPropertyPath(path)) {
  6766. + const subPaths = this.createPropertyPath(metadata, entity[key], path);
  6767. + paths.push(...subPaths);
  6768. + continue;
  6769. + }
  6770. + if (metadata.hasRelationWithPropertyPath(path)) {
  6771. + const relation = metadata.findRelationWithPropertyPath(path);
  6772. + // There's also cases where we don't want to return back all of the properties.
  6773. + // These handles the situation where someone passes the model & we don't need to make
  6774. + // a HUGE `where` to uniquely look up the entity.
  6775. + // In the case of a *-to-one, there's only ever one possible entity on the other side
  6776. + // so if the join columns are all defined we can return just the relation itself
  6777. + // because it will fetch only the join columns and do the lookup.
  6778. + if (
  6779. + relation.relationType === 'one-to-one' ||
  6780. + relation.relationType === 'many-to-one'
  6781. + ) {
  6782. + const joinColumns = relation.joinColumns
  6783. + .map((j) => j.referencedColumn)
  6784. + .filter((j) => !!j);
  6785. + const hasAllJoinColumns =
  6786. + joinColumns.length > 0 &&
  6787. + joinColumns.every((column) =>
  6788. + column.getEntityValue(entity[key], false)
  6789. + );
  6790. + if (hasAllJoinColumns) {
  6791. + paths.push(path);
  6792. + continue;
  6793. + }
  6794. + }
  6795. + if (
  6796. + relation.relationType === 'one-to-many' ||
  6797. + relation.relationType === 'many-to-many'
  6798. + ) {
  6799. + throw new Error(
  6800. + `Cannot query across ${relation.relationType} for property ${path}`
  6801. + );
  6802. + }
  6803. + // For any other case, if the `entity[key]` contains all of the primary keys we can do a
  6804. + // lookup via these. We don't need to look up via any other values 'cause these are
  6805. + // the unique primary keys.
  6806. + // This handles the situation where someone passes the model & we don't need to make
  6807. + // a HUGE where.
  6808. + const primaryColumns = relation.inverseEntityMetadata.primaryColumns;
  6809. + const hasAllPrimaryKeys =
  6810. + primaryColumns.length > 0 &&
  6811. + primaryColumns.every((column) =>
  6812. + column.getEntityValue(entity[key], false)
  6813. + );
  6814. + if (hasAllPrimaryKeys) {
  6815. + const subPaths = primaryColumns.map(
  6816. + (column) => `${path}.${column.propertyPath}`
  6817. + );
  6818. + paths.push(...subPaths);
  6819. + continue;
  6820. + }
  6821. + // If nothing else, just return every property that's being passed to us.
  6822. + const subPaths = this.createPropertyPath(
  6823. + relation.inverseEntityMetadata,
  6824. + entity[key]
  6825. + ).map((p) => `${path}.${p}`);
  6826. + paths.push(...subPaths);
  6827. + continue;
  6828. + }
  6829. + paths.push(path);
  6830. + }
  6831. + return paths;
  6832. + }
  6833. + *getPredicates(where) {
  6834. + if (this.expressionMap.mainAlias.hasMetadata) {
  6835. + const propertyPaths = this.createPropertyPath(
  6836. + this.expressionMap.mainAlias.metadata,
  6837. + where
  6838. + );
  6839. + for (const propertyPath of propertyPaths) {
  6840. + const [alias, aliasPropertyPath, columns] =
  6841. + this.findColumnsForPropertyPath(propertyPath);
  6842. + for (const column of columns) {
  6843. + let containedWhere = where;
  6844. + for (const part of aliasPropertyPath) {
  6845. + if (!containedWhere || !(part in containedWhere)) {
  6846. + containedWhere = {};
  6847. + break;
  6848. + }
  6849. + containedWhere = containedWhere[part];
  6850. + }
  6851. + // Use the correct alias & the property path from the column
  6852. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  6853. + ? `${alias.name}.${column.propertyPath}`
  6854. + : column.propertyPath;
  6855. + const parameterValue = column.getEntityValue(containedWhere, true);
  6856. + yield [aliasPath, parameterValue];
  6857. + }
  6858. + }
  6859. + } else {
  6860. + for (const key of Object.keys(where)) {
  6861. + const parameterValue = where[key];
  6862. + const aliasPath = this.expressionMap.aliasNamePrefixingEnabled
  6863. + ? `${this.alias}.${key}`
  6864. + : key;
  6865. + yield [aliasPath, parameterValue];
  6866. + }
  6867. + }
  6868. + }
  6869. + getWherePredicateCondition(aliasPath, parameterValue) {
  6870. + if (InstanceChecker.isFindOperator(parameterValue)) {
  6871. + let parameters = [];
  6872. + if (parameterValue.useParameter) {
  6873. + if (parameterValue.objectLiteralParameters) {
  6874. + this.setParameters(parameterValue.objectLiteralParameters);
  6875. + } else if (parameterValue.multipleParameters) {
  6876. + for (const v of parameterValue.value) {
  6877. + parameters.push(this.createParameter(v));
  6878. + }
  6879. + } else {
  6880. + parameters.push(this.createParameter(parameterValue.value));
  6881. + }
  6882. + }
  6883. + if (parameterValue.type === 'raw') {
  6884. + if (parameterValue.getSql) {
  6885. + return parameterValue.getSql(aliasPath);
  6886. + } else {
  6887. + return {
  6888. + operator: 'equal',
  6889. + parameters: [aliasPath, parameterValue.value],
  6890. + };
  6891. + }
  6892. + } else if (parameterValue.type === 'not') {
  6893. + if (parameterValue.child) {
  6894. + return {
  6895. + operator: parameterValue.type,
  6896. + condition: this.getWherePredicateCondition(
  6897. + aliasPath,
  6898. + parameterValue.child
  6899. + ),
  6900. + };
  6901. + } else {
  6902. + return {
  6903. + operator: 'notEqual',
  6904. + parameters: [aliasPath, ...parameters],
  6905. + };
  6906. + }
  6907. + } else {
  6908. + return {
  6909. + operator: parameterValue.type,
  6910. + parameters: [aliasPath, ...parameters],
  6911. + };
  6912. + }
  6913. + // } else if (parameterValue === null) {
  6914. + // return {
  6915. + // operator: "isNull",
  6916. + // parameters: [
  6917. + // aliasPath,
  6918. + // ]
  6919. + // };
  6920. + } else {
  6921. + return {
  6922. + operator: 'equal',
  6923. + parameters: [aliasPath, this.createParameter(parameterValue)],
  6924. + };
  6925. + }
  6926. + }
  6927. + getWhereCondition(where) {
  6928. + if (typeof where === 'string') {
  6929. + return where;
  6930. + }
  6931. + if (InstanceChecker.isBrackets(where)) {
  6932. + const whereQueryBuilder = this.createQueryBuilder();
  6933. + whereQueryBuilder.parentQueryBuilder = this;
  6934. + whereQueryBuilder.expressionMap.mainAlias = this.expressionMap.mainAlias;
  6935. + whereQueryBuilder.expressionMap.aliasNamePrefixingEnabled =
  6936. + this.expressionMap.aliasNamePrefixingEnabled;
  6937. + whereQueryBuilder.expressionMap.parameters =
  6938. + this.expressionMap.parameters;
  6939. + whereQueryBuilder.expressionMap.nativeParameters =
  6940. + this.expressionMap.nativeParameters;
  6941. + whereQueryBuilder.expressionMap.wheres = [];
  6942. + where.whereFactory(whereQueryBuilder);
  6943. + return {
  6944. + operator: InstanceChecker.isNotBrackets(where) ? 'not' : 'brackets',
  6945. + condition: whereQueryBuilder.expressionMap.wheres,
  6946. + };
  6947. + }
  6948. + if (typeof where === 'function') {
  6949. + return where(this);
  6950. + }
  6951. + const wheres = Array.isArray(where) ? where : [where];
  6952. + const clauses = [];
  6953. + for (const where of wheres) {
  6954. + const conditions = [];
  6955. + // Filter the conditions and set up the parameter values
  6956. + for (const [aliasPath, parameterValue] of this.getPredicates(where)) {
  6957. + conditions.push({
  6958. + type: 'and',
  6959. + condition: this.getWherePredicateCondition(aliasPath, parameterValue),
  6960. + });
  6961. + }
  6962. + clauses.push({ type: 'or', condition: conditions });
  6963. + }
  6964. + if (clauses.length === 1) {
  6965. + return clauses[0].condition;
  6966. + }
  6967. + return clauses;
  6968. + }
  6969. + /**
  6970. + * Creates a query builder used to execute sql queries inside this query builder.
  6971. + */
  6972. + obtainQueryRunner() {
  6973. + return this.queryRunner || this.connection.createQueryRunner();
  6974. + }
  6975. + hasCommonTableExpressions() {
  6976. + return this.expressionMap.commonTableExpressions.length > 0;
  6977. + }
  6978. +}
  6979. +
  6980. +//# sourceMappingURL=QueryBuilder.js.map
  6981.  
Advertisement
Add Comment
Please, Sign In to add comment