New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

typeorm

Package Overview
Dependencies
Maintainers
2
Versions
858
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

typeorm - npm Package Compare versions

Comparing version 0.0.2-alpha.35 to 0.0.2-alpha.36

decorator/relations/RelationCount.d.ts

2

columns.d.ts

@@ -5,2 +5,2 @@ export * from "./decorator/columns/Column";

export * from "./decorator/columns/UpdateDateColumn";
export * from "./decorator/columns/RelationsCountColumn";
export * from "./decorator/relations/RelationCount";

@@ -9,3 +9,3 @@ "use strict";

__export(require("./decorator/columns/UpdateDateColumn"));
__export(require("./decorator/columns/RelationsCountColumn"));
__export(require("./decorator/relations/RelationCount"));
//# sourceMappingURL=columns.js.map

@@ -8,2 +8,3 @@ import { Connection } from "../connection/Connection";

import { TreeRepository } from "../repository/TreeRepository";
import { ObjectLiteral } from "../common/ObjectLiteral";
/**

@@ -68,3 +69,3 @@ * Entity manager supposed to work with any entity, automatically find its repository and call its methods, whatever

*/
merge<Entity>(entity1: Entity, entity2: Entity): Entity;
merge<Entity>(entityClass: ConstructorFunction<Entity> | Function, ...objects: ObjectLiteral[]): Entity;
/**

@@ -71,0 +72,0 @@ * Persists (saves) a given entity in the database.

@@ -77,4 +77,4 @@ "use strict";

*/
merge(entity1, entity2) {
return this.getRepository(entity1).merge(entity1, entity2);
merge(entityClass, ...objects) {
return this.getRepository(entityClass).merge(...objects);
}

@@ -81,0 +81,0 @@ persist(targetOrEntity, maybeEntity) {

@@ -9,2 +9,3 @@ import * as Rx from "rxjs/Rx";

import { ReactiveTreeRepository } from "../repository/ReactiveTreeRepository";
import { ObjectLiteral } from "../common/ObjectLiteral";
/**

@@ -57,3 +58,3 @@ * Entity manager supposed to work with any entity, automatically find its repository and call its method, whatever

*/
merge<Entity>(entity1: Entity, entity2: Entity): Entity;
merge<Entity>(entityClass: ConstructorFunction<Entity> | Function, ...objects: ObjectLiteral[]): Entity;
/**

@@ -60,0 +61,0 @@ * Persists (saves) a given entity in the database.

@@ -71,4 +71,4 @@ "use strict";

*/
merge(entity1, entity2) {
return this.getReactiveRepository(entity1).merge(entity1, entity2);
merge(entityClass, ...objects) {
return this.getRepository(entityClass).merge(...objects);
}

@@ -75,0 +75,0 @@ persist(targetOrEntity, maybeEntity) {

@@ -5,3 +5,3 @@ import { TargetMetadataArgsCollection } from "./collection/TargetMetadataArgsCollection";

import { ColumnMetadataArgs } from "./ColumnMetadataArgs";
import { RelationsCountMetadataArgs } from "./RelationsCountMetadataArgs";
import { RelationCountMetadataArgs } from "./RelationCountMetadataArgs";
import { IndexMetadataArgs } from "./IndexMetadataArgs";

@@ -15,2 +15,3 @@ import { EntityListenerMetadataArgs } from "./EntityListenerMetadataArgs";

import { EntitySubscriberMetadataArgs } from "./EntitySubscriberMetadataArgs";
import { RelationIdMetadataArgs } from "./RelationIdMetadataArgs";
/**

@@ -30,3 +31,4 @@ * Storage all metadatas of all available types: tables, fields, subscribers, relations, etc.

readonly entityListeners: PropertyMetadataArgsCollection<EntityListenerMetadataArgs>;
readonly relationCounts: PropertyMetadataArgsCollection<RelationsCountMetadataArgs>;
readonly relationCounts: PropertyMetadataArgsCollection<RelationCountMetadataArgs>;
readonly relationIds: PropertyMetadataArgsCollection<RelationIdMetadataArgs>;
readonly embeddeds: PropertyMetadataArgsCollection<EmbeddedMetadataArgs>;

@@ -44,3 +46,4 @@ /**

entityListeners: PropertyMetadataArgsCollection<EntityListenerMetadataArgs>;
relationCounts: PropertyMetadataArgsCollection<RelationsCountMetadataArgs>;
relationCounts: PropertyMetadataArgsCollection<RelationCountMetadataArgs>;
relationIds: PropertyMetadataArgsCollection<RelationIdMetadataArgs>;
embeddeds: PropertyMetadataArgsCollection<EmbeddedMetadataArgs>;

@@ -47,0 +50,0 @@ }[];

@@ -27,2 +27,3 @@ "use strict";

this.relationCounts = new PropertyMetadataArgsCollection_1.PropertyMetadataArgsCollection();
this.relationIds = new PropertyMetadataArgsCollection_1.PropertyMetadataArgsCollection();
this.embeddeds = new PropertyMetadataArgsCollection_1.PropertyMetadataArgsCollection();

@@ -66,2 +67,3 @@ }

const relationCounts = this.relationCounts.filterByTarget(tableMetadata.target);
const relationIds = this.relationIds.filterByTarget(tableMetadata.target);
const embeddeds = this.embeddeds.filterByTarget(tableMetadata.target);

@@ -96,2 +98,5 @@ allTableMetadatas

.forEach(metadata => relationCounts.push(metadata));
metadatasFromAbstract.relationIds
.filterRepeatedMetadatas(relationIds)
.forEach(metadata => relationIds.push(metadata));
metadatasFromAbstract.embeddeds

@@ -110,2 +115,3 @@ .filterRepeatedMetadatas(embeddeds)

relationCounts: relationCounts,
relationIds: relationIds,
embeddeds: embeddeds

@@ -112,0 +118,0 @@ };

@@ -212,2 +212,25 @@ "use strict";

});
// save relation id-s data
entityMetadata.relations.forEach(relation => {
const relationIdMetadata = mergedArgs.relationIds.find(relationId => {
if (relationId.relation instanceof Function)
return relation.propertyName === relationId.relation(entityMetadata.createPropertiesMap());
return relation.propertyName === relationId.relation;
});
if (relationIdMetadata) {
if (relation.isOneToOneNotOwner || relation.isOneToMany)
throw new Error(`RelationId cannot be used for the one-to-one without join column or one-to-many relations.`);
relation.idField = relationIdMetadata.propertyName;
}
});
// save relation counter-s data
entityMetadata.relations.forEach(relation => {
const relationCountMetadata = mergedArgs.relationCounts.find(relationCount => {
if (relationCount.relation instanceof Function)
return relation.propertyName === relationCount.relation(entityMetadata.createPropertiesMap());
return relation.propertyName === relationCount.relation;
});
if (relationCountMetadata)
relation.countField = relationCountMetadata.propertyName;
});
return entityMetadata;

@@ -214,0 +237,0 @@ });

@@ -199,2 +199,4 @@ import { TableMetadata } from "./TableMetadata";

extractNonEmptyMultiValueRelations(object: ObjectLiteral): RelationMetadata[];
extractExistSingleValueRelations(object: ObjectLiteral): RelationMetadata[];
extractExistMultiValueRelations(object: ObjectLiteral): RelationMetadata[];
}

@@ -324,4 +324,16 @@ "use strict";

}
extractExistSingleValueRelations(object) {
return this.relations.filter(relation => {
return (relation.relationType === RelationTypes_1.RelationTypes.ONE_TO_ONE || relation.relationType === RelationTypes_1.RelationTypes.MANY_TO_ONE)
&& object.hasOwnProperty(relation.propertyName);
});
}
extractExistMultiValueRelations(object) {
return this.relations.filter(relation => {
return (relation.relationType === RelationTypes_1.RelationTypes.MANY_TO_MANY || relation.relationType === RelationTypes_1.RelationTypes.ONE_TO_MANY)
&& object.hasOwnProperty(relation.propertyName);
});
}
}
exports.EntityMetadata = EntityMetadata;
//# sourceMappingURL=EntityMetadata.js.map

@@ -41,2 +41,13 @@ import { PropertyMetadata } from "./PropertyMetadata";

/**
* The name of the field that will contain id or ids of this relation. This is used in the case if user
* wants to save relation without having to load related object, or in the cases if user wants to have id
* of the object it relates with, but don't want to load that object because of it. Also its used in the
* cases when user wants to add / remove / load in the many-to-many junction tables.
*/
idField: string | undefined;
/**
* The name of the field that will contain count of the rows of the relation.
*/
countField: string | undefined;
/**
* Indicates if this is a parent (can be only many-to-one relation) relation in the tree tables.

@@ -90,2 +101,3 @@ */

constructor(args: RelationMetadataArgs);
readonly target: Function | string;
/**

@@ -92,0 +104,0 @@ * Gets the name of column in the database.

@@ -12,3 +12,3 @@ "use strict";

constructor(args) {
super(args.target, args.propertyName);
super(undefined, args.propertyName);
// ---------------------------------------------------------------------

@@ -56,2 +56,5 @@ // Readonly Properties

// ---------------------------------------------------------------------
get target() {
return this.entityMetadata.target;
}
/**

@@ -58,0 +61,0 @@ * Gets the name of column in the database.

{
"name": "typeorm",
"private": false,
"version": "0.0.2-alpha.35",
"version": "0.0.2-alpha.36",
"description": "Data-mapper ORM for Typescript",

@@ -6,0 +6,0 @@ "license": "Apache-2.0",

@@ -341,11 +341,13 @@ "use strict";

const relationColumns = metadata.relations
.filter(relation => relation.isOwning && !!relation.inverseEntityMetadata)
.filter(relation => !relation.isManyToMany && relation.isOwning && !!relation.inverseEntityMetadata)
.filter(relation => entity.hasOwnProperty(relation.propertyName))
.filter(relation => entity[relation.propertyName][relation.inverseEntityMetadata.primaryColumn.propertyName])
.map(relation => relation.name);
const relationValues = metadata.relations
.filter(relation => relation.isOwning && !!relation.inverseEntityMetadata)
.filter(relation => !relation.isManyToMany && relation.isOwning && !!relation.inverseEntityMetadata)
.filter(relation => entity.hasOwnProperty(relation.propertyName))
.filter(relation => entity[relation.propertyName].hasOwnProperty(relation.inverseEntityMetadata.primaryColumn.propertyName))
.map(relation => entity[relation.propertyName][relation.inverseEntityMetadata.primaryColumn.propertyName]);
.map(relation => {
if (entity[relation.propertyName])
return entity[relation.propertyName][relation.inverseEntityMetadata.primaryColumn.propertyName];
return entity[relation.propertyName];
});
const allColumns = columnNames.concat(relationColumns);

@@ -352,0 +354,0 @@ const allValues = values.concat(relationValues);

@@ -9,2 +9,5 @@ "use strict";

}
get selection() {
return this.parentAliasName + "." + this.parentPropertyName;
}
getPrimaryKeyValue(result, primaryColumn) {

@@ -11,0 +14,0 @@ return result[this.name + "_" + primaryColumn.name];

@@ -0,4 +1,23 @@

import { Alias } from "./alias/Alias";
import { Broadcaster } from "../subscriber/Broadcaster";
import { EntityMetadataCollection } from "../metadata-args/collection/EntityMetadataCollection";
import { Driver } from "../driver/Driver";
import { EntityMetadata } from "../metadata/EntityMetadata";
export interface JoinRelationId {
alias: Alias;
type: "LEFT" | "INNER";
conditionType: "ON" | "WITH";
condition?: string;
mapToProperty?: string;
}
export interface RelationCountMeta {
alias: Alias;
conditionType: "ON" | "WITH";
condition?: string;
mapToProperty?: string;
entities: {
entity: any;
metadata: EntityMetadata;
}[];
}
export declare class QueryBuilder<Entity> {

@@ -16,2 +35,4 @@ private driver;

private joins;
private joinRelationIds;
private relationCountMetas;
private groupBys;

@@ -42,2 +63,20 @@ private wheres;

from(entity: Function | string, alias: string): this;
countRelationAndMap(mapProperty: string, property: string, conditionType?: "ON" | "WITH", condition?: string, parameters?: {
[key: string]: any;
}): this;
countRelation(property: string, conditionType?: "ON" | "WITH", condition?: string, parameters?: {
[key: string]: any;
}): this;
leftJoinRelationIdAndMap(mapToProperty: string, property: string, conditionType?: "ON" | "WITH", condition?: string, parameters?: {
[key: string]: any;
}): this;
innerJoinRelationIdAndMap(mapToProperty: string, property: string, conditionType?: "ON" | "WITH", condition?: string, parameters?: {
[key: string]: any;
}): this;
innerJoinRelationId(property: string, conditionType?: "ON" | "WITH", condition?: string, parameters?: {
[key: string]: any;
}): this;
leftJoinRelationId(property: string, conditionType?: "ON" | "WITH", condition?: string, parameters?: {
[key: string]: any;
}): this;
innerJoinAndMapMany(mapToProperty: string, property: string, alias: string, conditionType?: "ON" | "WITH", condition?: string, parameters?: {

@@ -133,2 +172,3 @@ [key: string]: any;

}>;
private loadRelationCounts(results);
getSingleResult(): Promise<Entity>;

@@ -150,2 +190,3 @@ getCount(): Promise<number>;

private replacePropertyNames(statement);
protected createJoinRelationIdsExpression(): string[];
protected createJoinExpression(): string;

@@ -168,3 +209,6 @@ protected createGroupByExpression(): string;

}, mapToProperty?: string, isMappingMany?: boolean): this;
protected joinRelationId(joinType: "LEFT" | "INNER", mapToProperty: string | undefined, property: string, conditionType?: "ON" | "WITH", condition?: string, parameters?: {
[key: string]: any;
}): this;
private isPropertyAlias(str);
}
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
const Alias_1 = require("./alias/Alias");

@@ -13,4 +21,7 @@ const AliasMap_1 = require("./alias/AliasMap");

this.broadcaster = broadcaster;
this.type = "select";
this.selects = [];
this.joins = [];
this.joinRelationIds = [];
this.relationCountMetas = [];
this.groupBys = [];

@@ -95,2 +106,51 @@ this.wheres = [];

}
countRelationAndMap(mapProperty, property, conditionType = "ON", condition = "", parameters) {
const [parentAliasName, parentPropertyName] = property.split(".");
const alias = parentAliasName + "_" + parentPropertyName + "_relation_count";
const aliasObj = new Alias_1.Alias(alias);
this.aliasMap.addAlias(aliasObj);
aliasObj.parentAliasName = parentAliasName;
aliasObj.parentPropertyName = parentPropertyName;
const relationCountMeta = {
mapToProperty: mapProperty,
conditionType: conditionType,
condition: condition,
alias: aliasObj,
entities: []
};
this.relationCountMetas.push(relationCountMeta);
if (parameters)
this.addParameters(parameters);
return this;
}
countRelation(property, conditionType = "ON", condition = "", parameters) {
const [parentAliasName, parentPropertyName] = property.split(".");
const alias = parentAliasName + "_" + parentPropertyName + "_relation_count";
const aliasObj = new Alias_1.Alias(alias);
this.aliasMap.addAlias(aliasObj);
aliasObj.parentAliasName = parentAliasName;
aliasObj.parentPropertyName = parentPropertyName;
const relationCountMeta = {
conditionType: conditionType,
condition: condition,
alias: aliasObj,
entities: []
};
this.relationCountMetas.push(relationCountMeta);
if (parameters)
this.addParameters(parameters);
return this;
}
leftJoinRelationIdAndMap(mapToProperty, property, conditionType = "ON", condition = "", parameters) {
return this.joinRelationId("INNER", mapToProperty, property, conditionType, condition, parameters);
}
innerJoinRelationIdAndMap(mapToProperty, property, conditionType = "ON", condition = "", parameters) {
return this.joinRelationId("INNER", mapToProperty, property, conditionType, condition, parameters);
}
innerJoinRelationId(property, conditionType, condition, parameters) {
return this.joinRelationId("INNER", undefined, property, conditionType, condition, parameters);
}
leftJoinRelationId(property, conditionType = "ON", condition, parameters) {
return this.joinRelationId("LEFT", undefined, property, conditionType, condition, parameters);
}
innerJoinAndMapMany(mapToProperty, entityOrProperty, alias, conditionType = "ON", condition = "", parameters) {

@@ -210,2 +270,3 @@ this.addSelect(alias);

sql += this.createJoinExpression();
sql += this.createJoinRelationIdsExpression();
sql += this.createWhereExpression();

@@ -235,60 +296,167 @@ sql += this.createGroupByExpression();

getResultsAndScalarResults() {
if (!this.aliasMap.hasMainAlias)
throw new Error(`Alias is not set. Looks like nothing is selected. Use select*, delete, update method to set an alias.`);
const mainAliasName = this.aliasMap.mainAlias.name;
let scalarResults;
if (this.firstResult || this.maxResults) {
const metadata = this.entityMetadatas.findByTarget(this.fromEntity.alias.target);
let idsQuery = `SELECT DISTINCT(distinctAlias.${mainAliasName}_${metadata.primaryColumn.name}) as ids`;
if (this.orderBys && this.orderBys.length > 0)
idsQuery += ", " + this.orderBys.map(orderBy => orderBy.sort.replace(".", "_")).join(", ");
idsQuery += ` FROM (${this.getSql()}) distinctAlias`;
if (this.orderBys && this.orderBys.length > 0)
idsQuery += " ORDER BY " + this.orderBys.map(order => "distinctAlias." + order.sort.replace(".", "_") + " " + order.order).join(", ");
if (this.maxResults)
idsQuery += " LIMIT " + this.maxResults;
if (this.firstResult)
idsQuery += " OFFSET " + this.firstResult;
return this.driver
.query(idsQuery)
return __awaiter(this, void 0, void 0, function* () {
if (!this.aliasMap.hasMainAlias)
throw new Error(`Alias is not set. Looks like nothing is selected. Use select*, delete, update method to set an alias.`);
const mainAliasName = this.aliasMap.mainAlias.name;
let scalarResults;
if (this.firstResult || this.maxResults) {
const metadata = this.entityMetadatas.findByTarget(this.fromEntity.alias.target);
let idsQuery = `SELECT DISTINCT(distinctAlias.${mainAliasName}_${metadata.primaryColumn.name}) as ids`;
if (this.orderBys && this.orderBys.length > 0)
idsQuery += ", " + this.orderBys.map(orderBy => orderBy.sort.replace(".", "_")).join(", ");
idsQuery += ` FROM (${this.getSql()}) distinctAlias`;
if (this.orderBys && this.orderBys.length > 0)
idsQuery += " ORDER BY " + this.orderBys.map(order => "distinctAlias." + order.sort.replace(".", "_") + " " + order.order).join(", ");
if (this.maxResults)
idsQuery += " LIMIT " + this.maxResults;
if (this.firstResult)
idsQuery += " OFFSET " + this.firstResult;
return this.driver
.query(idsQuery)
.then((results) => {
scalarResults = results;
const ids = results.map(result => result["ids"]).join(", ");
if (ids.length === 0)
return Promise.resolve([]);
const queryWithIds = this.clone()
.andWhere(mainAliasName + "." + metadata.primaryColumn.name + " IN (" + ids + ")")
.getSql();
return this.driver.query(queryWithIds);
})
.then(results => this.rawResultsToEntities(results))
.then(results => this.addLazyProperties(results))
.then(results => this.broadcaster.broadcastLoadEventsForAll(this.aliasMap.mainAlias.target, results).then(() => results))
.then(results => {
return {
entities: results,
scalarResults: scalarResults
};
});
}
else {
return this.driver
.query(this.getSql())
.then(results => {
scalarResults = results;
return this.rawResultsToEntities(results);
})
.then(results => {
return this.loadRelationCounts(results)
.then(counts => {
// console.log("counts: ", counts);
return results;
});
})
.then(results => this.addLazyProperties(results))
.then(results => {
return this.broadcaster
.broadcastLoadEventsForAll(this.aliasMap.mainAlias.target, results)
.then(() => results);
})
.then(results => {
return {
entities: results,
scalarResults: scalarResults
};
});
}
});
}
/*private extractIdMap(alias: Alias, results: Entity[]): { alias: Alias, ids: any[] }[] {
// console.log("results ids:", results.map(result => result[]));
const metadata = this.aliasMap.getEntityMetadataByAlias(alias);
if (!metadata)
throw new Error("Cannot get entity metadata for the given alias " + this.aliasMap.mainAlias.name);
/!*
results.forEach(result => {
});
metadata.relations.forEach(relation => {
this.aliasMap.
});
*!/
}*/
loadRelationCounts(results) {
const promises = this.relationCountMetas.map(relationCountMeta => {
const parentAlias = relationCountMeta.alias.parentAliasName;
const foundAlias = this.aliasMap.findAliasByName(parentAlias);
if (!foundAlias)
throw new Error(`Alias "${parentAlias}" was not found`);
const parentMetadata = this.aliasMap.getEntityMetadataByAlias(foundAlias);
if (!parentMetadata)
throw new Error("Cannot get entity metadata for the given alias " + foundAlias.name);
const relation = parentMetadata.findRelationWithPropertyName(relationCountMeta.alias.parentPropertyName);
const queryBuilder = new this.constructor(this.driver, this.entityMetadatas, this.broadcaster);
let condition = "";
const metadata = this.aliasMap.getEntityMetadataByAlias(relationCountMeta.alias);
if (!metadata)
throw new Error("Cannot get entity metadata for the given alias " + relationCountMeta.alias.name);
let joinTableName = metadata.table.name;
const junctionMetadata = relation.junctionEntityMetadata;
const appendedCondition = relationCountMeta.condition ? " AND " + this.replacePropertyNames(relationCountMeta.condition) : "";
/*if (relation.isManyToMany) {
const junctionTable = junctionMetadata.table.name;
const junctionAlias = relationCountMeta.alias.parentAliasName + "_" + relationCountMeta.alias.name;
const joinAlias = relationCountMeta.alias.name;
const joinTable = relation.isOwning ? relation.joinTable : relation.inverseRelation.joinTable; // not sure if this is correct
const joinTableColumn = joinTable.referencedColumn.name; // not sure if this is correct
const inverseJoinColumnName = joinTable.inverseReferencedColumn.name; // not sure if this is correct
let condition1 = "", condition2 = "";
if (relation.isOwning) {
condition1 = junctionAlias + "." + junctionMetadata.columns[0].name + "=" + parentAlias + "." + joinTableColumn;
condition2 = joinAlias + "." + inverseJoinColumnName + "=" + junctionAlias + "." + junctionMetadata.columns[1].name;
} else {
condition1 = junctionAlias + "." + junctionMetadata.columns[1].name + "=" + parentAlias + "." + joinTableColumn;
condition2 = joinAlias + "." + inverseJoinColumnName + "=" + junctionAlias + "." + junctionMetadata.columns[0].name;
}
condition = " LEFT JOIN " + junctionTable + " " + junctionAlias + " " + relationCountMeta.conditionType + " " + condition1 +
" LEFT JOIN " + joinTableName + " " + joinAlias + " " + relationCountMeta.conditionType + " " + condition2 + appendedCondition;
} else if (relation.isManyToOne || (relation.isOneToOne && relation.isOwning)) {
const joinTableColumn = relation.joinColumn.referencedColumn.name;
const condition2 = relationCountMeta.alias.name + "." + joinTableColumn + "=" + parentAlias + "." + relation.name;
condition = " LEFT JOIN " + joinTableName + " " + relationCountMeta.alias.name + " " + relationCountMeta.conditionType + " " + condition2 + appendedCondition;
} else {
throw new Error(`Relation count can be applied only `); // this should be done on entity build
}*/
// if (relationCountMeta.condition)
// condition += relationCountMeta.condition;
// relationCountMeta.alias.target;
const ids = relationCountMeta.entities.map(entityWithMetadata => entityWithMetadata.entity[entityWithMetadata.metadata.primaryColumn.propertyName]);
if (!ids || !ids.length)
throw new Error(`No ids found to load relation counters`);
return queryBuilder
.select(`${parentMetadata.name + "." + parentMetadata.primaryColumn.propertyName} as id`)
.addSelect(`COUNT(${relation.propertyName + "." + relation.inverseEntityMetadata.primaryColumn.propertyName}) as cnt`)
.from(parentMetadata.target, parentMetadata.name)
.leftJoin(parentMetadata.name + "." + relation.propertyName, relation.propertyName, relationCountMeta.conditionType, relationCountMeta.condition)
.setParameters(this.parameters)
.where(`${parentMetadata.name + "." + parentMetadata.primaryColumn.propertyName} IN (:relationCountIds)`, { relationCountIds: ids })
.groupBy(parentMetadata.name + "." + parentMetadata.primaryColumn.propertyName)
.getScalarResults()
.then((results) => {
scalarResults = results;
const ids = results.map(result => result["ids"]).join(", ");
if (ids.length === 0)
return Promise.resolve([]);
const queryWithIds = this.clone()
.andWhere(mainAliasName + "." + metadata.primaryColumn.name + " IN (" + ids + ")")
.getSql();
return this.driver.query(queryWithIds);
})
.then(results => this.rawResultsToEntities(results))
.then(results => this.addLazyProperties(results))
.then(results => this.broadcaster.broadcastLoadEventsForAll(this.aliasMap.mainAlias.target, results).then(() => results))
.then(results => {
return {
entities: results,
scalarResults: scalarResults
};
// console.log(relationCountMeta.entities);
relationCountMeta.entities.forEach(entityWithMetadata => {
const entityId = entityWithMetadata.entity[entityWithMetadata.metadata.primaryColumn.propertyName];
const entityResult = results.find(result => result.id === entityId);
if (entityResult) {
if (relationCountMeta.mapToProperty) {
const [parentName, propertyName] = relationCountMeta.mapToProperty.split(".");
// todo: right now mapping is working only on the currently countRelation class, but
// different properties are working. make different classes to work too
entityWithMetadata.entity[propertyName] = entityResult.cnt;
}
else if (relation.countField) {
entityWithMetadata.entity[relation.countField] = entityResult.cnt;
}
}
});
});
}
else {
return this.driver
.query(this.getSql())
.then(results => {
scalarResults = results;
return this.rawResultsToEntities(results);
})
.then(results => this.addLazyProperties(results))
.then(results => {
return this.broadcaster
.broadcastLoadEventsForAll(this.aliasMap.mainAlias.target, results)
.then(() => results);
})
.then(results => {
return {
entities: results,
scalarResults: scalarResults
};
});
}
});
return Promise.all(promises);
}

@@ -339,3 +507,3 @@ getSingleResult() {

const property = join.tableName || join.alias.target || (join.alias.parentAliasName + "." + join.alias.parentPropertyName);
qb.join(join.type, property, join.alias.name, join.conditionType, join.condition, undefined, join.mapToProperty, join.isMappingMany);
qb.join(join.type, property, join.alias.name, join.conditionType, join.condition || "", undefined, join.mapToProperty, join.isMappingMany);
});

@@ -384,3 +552,3 @@ this.groupBys.forEach(groupBy => qb.addGroupBy(groupBy));

rawResultsToEntities(results) {
const transformer = new RawSqlResultsToEntityTransformer_1.RawSqlResultsToEntityTransformer(this.driver, this.aliasMap, this.extractJoinMappings());
const transformer = new RawSqlResultsToEntityTransformer_1.RawSqlResultsToEntityTransformer(this.driver, this.aliasMap, this.extractJoinMappings(), this.relationCountMetas);
return transformer.transform(results);

@@ -463,2 +631,19 @@ }

});
// add selects from relation id joins
this.joinRelationIds.forEach(join => {
// const joinMetadata = this.aliasMap.getEntityMetadataByAlias(join.alias);
const parentAlias = join.alias.parentAliasName;
const foundAlias = this.aliasMap.findAliasByName(parentAlias);
if (!foundAlias)
throw new Error(`Alias "${parentAlias}" was not found`);
const parentMetadata = this.aliasMap.getEntityMetadataByAlias(foundAlias);
if (!parentMetadata)
throw new Error("Cannot get entity metadata for the given alias " + foundAlias.name);
const relation = parentMetadata.findRelationWithPropertyName(join.alias.parentPropertyName);
const junctionMetadata = relation.junctionEntityMetadata;
// const junctionTable = junctionMetadata.table.name;
junctionMetadata.columns.forEach(column => {
allSelects.push(join.alias.name + "." + column.name + " AS " + join.alias.name + "_" + column.name);
});
});
// add all other selects

@@ -520,2 +705,30 @@ this.selects.filter(select => {

}
createJoinRelationIdsExpression() {
return this.joinRelationIds.map(join => {
const parentAlias = join.alias.parentAliasName;
const foundAlias = this.aliasMap.findAliasByName(parentAlias);
if (!foundAlias)
throw new Error(`Alias "${parentAlias}" was not found`);
const parentMetadata = this.aliasMap.getEntityMetadataByAlias(foundAlias);
if (!parentMetadata)
throw new Error("Cannot get entity metadata for the given alias " + foundAlias.name);
const relation = parentMetadata.findRelationWithPropertyName(join.alias.parentPropertyName);
const junctionMetadata = relation.junctionEntityMetadata;
const junctionTable = junctionMetadata.table.name;
const junctionAlias = join.alias.name;
const joinTable = relation.isOwning ? relation.joinTable : relation.inverseRelation.joinTable; // not sure if this is correct
const joinTableColumn = joinTable.referencedColumn.name; // not sure if this is correct
let condition1 = "";
if (relation.isOwning) {
condition1 = junctionAlias + "." + junctionMetadata.columns[0].name + "=" + parentAlias + "." + joinTableColumn;
}
else {
condition1 = junctionAlias + "." + junctionMetadata.columns[1].name + "=" + parentAlias + "." + joinTableColumn;
}
return " " + join.type + " JOIN " + junctionTable + " " + junctionAlias + " " + join.conditionType + " " + condition1;
// " " + joinType + " JOIN " + joinTableName + " " + joinAlias + " " + join.conditionType + " " + condition2 + appendedCondition;
// console.log(join);
// return " " + join.type + " JOIN " + joinTableName + " " + join.alias.name + " " + (join.condition ? (join.conditionType + " " + join.condition) : "");
});
}
createJoinExpression() {

@@ -620,7 +833,9 @@ return this.joins.map(join => {

extractJoinMappings() {
return this.joins
const mappings = [];
this.joins
.filter(join => !!join.mapToProperty)
.map(join => {
.forEach(join => {
const [parentName, propertyName] = join.mapToProperty.split(".");
return {
mappings.push({
type: "join",
alias: join.alias,

@@ -630,4 +845,17 @@ parentName: parentName,

isMany: join.isMappingMany
};
});
});
this.joinRelationIds
.filter(join => !!join.mapToProperty)
.forEach(join => {
const [parentName, propertyName] = join.mapToProperty.split(".");
mappings.push({
type: "relationId",
alias: join.alias,
parentName: parentName,
propertyName: propertyName,
isMany: false
});
});
return mappings;
}

@@ -655,2 +883,22 @@ join(joinType, entityOrProperty, alias, conditionType = "ON", condition = "", parameters, mapToProperty, isMappingMany = false) {

}
joinRelationId(joinType, mapToProperty, property, conditionType = "ON", condition, parameters) {
if (!this.isPropertyAlias(property))
throw new Error("Only entity relations are allowed in the leftJoinRelationId operation"); // todo: also check if that relation really has entityId
const [parentAliasName, parentPropertyName] = property.split(".");
const alias = parentAliasName + "_" + parentPropertyName + "_relation_id";
const aliasObj = new Alias_1.Alias(alias);
this.aliasMap.addAlias(aliasObj);
aliasObj.parentAliasName = parentAliasName;
aliasObj.parentPropertyName = parentPropertyName;
this.joinRelationIds.push({
type: joinType,
mapToProperty: mapToProperty,
alias: aliasObj,
conditionType: conditionType,
condition: condition
});
if (parameters)
this.addParameters(parameters);
return this;
}
isPropertyAlias(str) {

@@ -657,0 +905,0 @@ if (!(typeof str === "string"))

@@ -32,3 +32,3 @@ "use strict";

const entity = yield queryBuilder.getSingleResult();
// this.mergeEntityWithPlainObject(entity, plainObject);
// this.mergeEntityWithPlainObject(metadata, entity, plainObject);
return entity;

@@ -40,18 +40,4 @@ });

// -------------------------------------------------------------------------
/* private mergeEntityWithPlainObject(metadata: EntityMetadata, entity: Entity, object: ObjectLiteral) {
metadata.extractNonEmptyColumns(object).forEach(column => {
entity[column.propertyName] = object[column.propertyName];
});
metadata.extractNonEmptySingleValueRelations(object).forEach(relation => {
entity[relation.propertyName] = this.mergeEntityWithPlainObject(relation.inverseEntityMetadata, entity[relation.propertyName], object[relation.propertyName]);
});
metadata.extractNonEmptyMultiValueRelations(object).forEach(relation => {
entity[relation.propertyName] = (object[relation.propertyName] as ObjectLiteral[]).map(subObject => {
return this.mergeEntityWithPlainObject(relation.inverseEntityMetadata, entity[relation.propertyName], subObject);
});
});
}*/
mergeEntityWithPlainObject(metadata, entity, object) {
}
join(qb, needToLoad, parentAlias) {

@@ -58,0 +44,0 @@ needToLoad.forEach(i => {

@@ -10,11 +10,6 @@ "use strict";

// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor() {
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
transform(object, metadata) {
return this.groupAndTransform(object, metadata);
transform(newEntity, object, metadata) {
return this.groupAndTransform(newEntity, object, metadata);
}

@@ -28,4 +23,3 @@ // -------------------------------------------------------------------------

*/
groupAndTransform(object, metadata) {
const entity = metadata.create();
groupAndTransform(entity, object, metadata) {
// copy regular column properties from the given object

@@ -45,3 +39,3 @@ metadata.columns

entity[relation.propertyName] = object[relation.propertyName].map((subObject) => {
return this.groupAndTransform(subObject, relationMetadata);
return this.groupAndTransform(relationMetadata.create(), subObject, relationMetadata);
});

@@ -55,3 +49,3 @@ }

if (object[relation.propertyName]) {
entity[relation.propertyName] = this.groupAndTransform(object[relation.propertyName], relationMetadata);
entity[relation.propertyName] = this.groupAndTransform(relationMetadata.create(), object[relation.propertyName], relationMetadata);
}

@@ -58,0 +52,0 @@ else {

@@ -13,6 +13,7 @@ "use strict";

// -------------------------------------------------------------------------
constructor(driver, aliasMap, joinMappings) {
constructor(driver, aliasMap, joinMappings, relationCountMetas) {
this.driver = driver;
this.aliasMap = aliasMap;
this.joinMappings = joinMappings;
this.relationCountMetas = relationCountMetas;
}

@@ -86,3 +87,3 @@ // -------------------------------------------------------------------------

if (relationAlias) {
const joinMapping = this.joinMappings.find(joinMapping => joinMapping.alias === relationAlias);
const joinMapping = this.joinMappings.find(joinMapping => joinMapping.type === "join" && joinMapping.alias === relationAlias);
const relatedEntities = this.groupAndTransform(rawSqlResults, relationAlias);

@@ -105,2 +106,34 @@ const isResultArray = relation.isManyToMany || relation.isOneToMany;

}
// if relation has id field then relation id/ids to that field.
if (relation.isManyToMany) {
if (relationAlias) {
const ids = [];
const joinMapping = this.joinMappings.find(joinMapping => joinMapping.type === "relationId" && joinMapping.alias === relationAlias);
if (relation.idField || joinMapping) {
const propertyName = joinMapping ? joinMapping.propertyName : relation.idField;
const junctionMetadata = relation.junctionEntityMetadata;
const columnName = relation.isOwning ? junctionMetadata.columns[1].name : junctionMetadata.columns[0].name;
rawSqlResults.forEach(results => {
if (relationAlias) {
const resultsKey = relationAlias.name + "_" + columnName;
if (results[resultsKey])
ids.push(results[resultsKey]);
}
});
if (ids && ids.length)
entity[propertyName] = ids;
}
}
}
else if (relation.idField) {
entity[relation.idField] = alias.getColumnValue(rawSqlResults[0], relation.name);
}
// if relation counter
this.relationCountMetas.forEach(joinMeta => {
if (joinMeta.alias === relationAlias) {
// console.log("relation count was found for relation: ", relation);
// joinMeta.entity = entity;
joinMeta.entities.push({ entity: entity, metadata: metadata });
}
});
});

@@ -107,0 +140,0 @@ return hasData ? entity : null;

@@ -6,2 +6,3 @@ import { QueryBuilder } from "../query-builder/QueryBuilder";

import { EntityMetadata } from "../metadata/EntityMetadata";
import { ObjectLiteral } from "../common/ObjectLiteral";
/**

@@ -46,3 +47,3 @@ * Repository is supposed to work with your entity objects. Find entities, insert, update, delete, etc.

*/
merge(entity1: Entity, entity2: Entity): Entity;
merge(...objects: ObjectLiteral[]): Entity;
/**

@@ -49,0 +50,0 @@ * Persists (saves) a given entity in the database. If entity does not exist in the database then it inserts it,

@@ -62,4 +62,4 @@ "use strict";

*/
merge(entity1, entity2) {
return this.repository.merge(entity1, entity2);
merge(...objects) {
return this.repository.merge(...objects);
}

@@ -66,0 +66,0 @@ /**

@@ -12,2 +12,3 @@ import { Connection } from "../connection/Connection";

import { Driver } from "../driver/Driver";
import { ObjectLiteral } from "../common/ObjectLiteral";
/**

@@ -57,5 +58,5 @@ * Repository is supposed to work with your entity objects. Find entities, insert, update, delete, etc.

/**
* Merges two entities into one new entity.
* Merges multiple entity-like structures into one new entity.
*/
merge(entity1: Entity, entity2: Entity): Entity;
merge(...objects: ObjectLiteral[]): Entity;
/**

@@ -62,0 +63,0 @@ * Persists (saves) a given entity in the database. If entity does not exist in the database then it inserts it,

@@ -59,5 +59,6 @@ "use strict";

create(plainObject) {
const newEntity = this.addLazyProperties(this.metadata.create(), this.metadata.target);
if (plainObject)
return this.addLazyProperties(this.plainObjectToEntityTransformer.transform(plainObject, this.metadata), this.metadata.target);
return this.addLazyProperties(this.metadata.create(), this.metadata.target);
this.plainObjectToEntityTransformer.transform(newEntity, plainObject, this.metadata);
return newEntity;
}

@@ -81,6 +82,43 @@ /**

/**
* Merges two entities into one new entity.
* Merges multiple entity-like structures into one new entity.
*/
merge(entity1, entity2) {
return Object.assign(this.metadata.create(), entity1, entity2);
merge(...objects) {
const newEntity = this.create();
objects.forEach(entity => this.plainObjectToEntityTransformer.transform(newEntity, entity, this.metadata));
return newEntity;
/*const comparator = new Comporator(metadata, entity, object, ComparationMode.NON_EMPTY);
comparator.columns.forEach(column => {
entity[column.propertyName] = object[column.propertyName];
});
comparator.singleValueRelations.forEach(relation => {
entity[relation.propertyName] = this.mergeEntityWithPlainObject(relation.inverseEntityMetadata, entity[relation.propertyName], object[relation.propertyName]);
});
comparator.multiValueRelations.forEach(relation => {
entity[relation.propertyName] = (object[relation.propertyName] as ObjectLiteral[]).map(subObject => {
return this.mergeEntityWithPlainObject(relation.inverseEntityMetadata, entity[relation.propertyName], subObject);
});
});
// comparator.applyToRelationItems(() => {});
*/
/*metadata.extractNonEmptyColumns(object).forEach(column => {
entity[column.propertyName] = object[column.propertyName];
});
metadata.extractExistSingleValueRelations(object).forEach(relation => {
if (entity[relation.propertyName] instanceof Object) {
entity[relation.propertyName] = this.mergeEntityWithPlainObject(relation.inverseEntityMetadata, entity[relation.propertyName], object[relation.propertyName]);
} else {
entity[relation.propertyName] = object[relation.propertyName]; // todo: do we really need to do it? - probably yes for null and undefined values, but what about others
}
});
metadata.extractExistMultiValueRelations(object).forEach(relation => {
entity[relation.propertyName] = (object[relation.propertyName] as ObjectLiteral[]).map(subObject => {
if (entity[relation.propertyName] instanceof Object) {
return this.mergeEntityWithPlainObject(relation.inverseEntityMetadata, entity[relation.propertyName], subObject);
} else {
entity[relation.propertyName] = object[relation.propertyName]; // todo: do we really need to do it? - probably yes for null and undefined values, but what about others
}
});
});*/
}

@@ -87,0 +125,0 @@ /**

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc