Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter soft-deleted join-table entities #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/decorator/options/JoinTableOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ export interface JoinTableOptions {
*/
name?: string

/**
* Specifies the entity (if any) that defines the join table.
*/
junctionEntity?: Function

/**
* First column of the join table.
*/
Expand Down
1 change: 1 addition & 0 deletions src/decorator/relations/JoinTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export function JoinTable(
({} as JoinTableOptions | JoinTableMultipleColumnsOptions)
getMetadataArgsStorage().joinTables.push({
target: object.constructor,
junctionEntity: (options as JoinTableOptions).junctionEntity,
propertyName: propertyName,
name: options.name,
joinColumns: (options && (options as JoinTableOptions).joinColumn
Expand Down
5 changes: 5 additions & 0 deletions src/metadata-args/JoinTableMetadataArgs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ export interface JoinTableMetadataArgs {
*/
readonly target: Function | string

/**
* Class that defines the junction table.
*/
readonly junctionEntity?: Function

/**
* Class's property name to which this column is applied.
*/
Expand Down
11 changes: 11 additions & 0 deletions src/metadata-builder/EntityMetadataBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ export class EntityMetadataBuilder {
relation,
joinTable,
)

relation.registerForeignKeys(
...junctionEntityMetadata.foreignKeys,
)
Expand All @@ -313,6 +314,16 @@ export class EntityMetadataBuilder {
junctionEntityMetadata,
entityMetadatas,
)

// Add deleteDateColumn to junctionEntityMetadata to support filtering soft-deleted join records
const entityMetadataForJunction = entityMetadatas.find(
(en) =>
en.target === joinTable.junctionEntity &&
en.isJunction === false,
)
junctionEntityMetadata.deleteDateColumn =
entityMetadataForJunction?.deleteDateColumn

entityMetadatas.push(junctionEntityMetadata)
})
})
Expand Down
14 changes: 14 additions & 0 deletions src/query-builder/SelectQueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2373,6 +2373,10 @@ export class SelectQueryBuilder<Entity extends ObjectLiteral>
let junctionCondition = "",
destinationCondition = ""

const deleteDateColumn =
relation.junctionEntityMetadata?.deleteDateColumn
?.propertyPath

if (relation.isOwning) {
junctionCondition = relation.joinColumns
.map((joinColumn) => {
Expand All @@ -2387,6 +2391,11 @@ export class SelectQueryBuilder<Entity extends ObjectLiteral>
joinColumn.referencedColumn!.propertyPath
)
})
.concat(
deleteDateColumn
? ` "${junctionAlias}"."${deleteDateColumn}" IS NULL`
: [],
)
.join(" AND ")

destinationCondition = relation.inverseJoinColumns
Expand Down Expand Up @@ -2419,6 +2428,11 @@ export class SelectQueryBuilder<Entity extends ObjectLiteral>
)
},
)
.concat(
deleteDateColumn
? ` "${junctionAlias}"."${deleteDateColumn}" IS NULL`
: [],
)
.join(" AND ")

destinationCondition = relation
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { ManyToMany } from "../../../../../../../src/decorator/relations/ManyToMany"
import { Entity } from "../../../../../../../src/decorator/entity/Entity"
import { PrimaryGeneratedColumn } from "../../../../../../../src/decorator/columns/PrimaryGeneratedColumn"
import { Column } from "../../../../../../../src/decorator/columns/Column"
import { JoinTable } from "../../../../../../../src/decorator/relations/JoinTable"
import { Post } from "./Post"
import { PostCategory } from "./PostCategory"

@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number

@Column()
name: string

@ManyToMany((type) => Post, (post) => post.categories)
@JoinTable({
name: "post_category",
synchronize: false,
junctionEntity: PostCategory,
joinColumn: {
name: "cid",
referencedColumnName: "id",
},
})
posts: Post[]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ManyToMany } from "../../../../../../../src/decorator/relations/ManyToMany"
import { Entity } from "../../../../../../../src/decorator/entity/Entity"
import { PrimaryGeneratedColumn } from "../../../../../../../src/decorator/columns/PrimaryGeneratedColumn"
import { Column } from "../../../../../../../src/decorator/columns/Column"
import { Category } from "./Category"
import { DeleteDateColumn } from "../../../../../../../src"

@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number

@Column()
title: string

@ManyToMany((type) => Category, (category) => category.posts)
categories: Category[]

@DeleteDateColumn()
deletedAt: Date | null
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Entity } from "../../../../../../../src/decorator/entity/Entity"
import { PrimaryGeneratedColumn } from "../../../../../../../src/decorator/columns/PrimaryGeneratedColumn"
import { Column } from "../../../../../../../src/decorator/columns/Column"
import { DeleteDateColumn } from "../../../../../../../src"

@Entity()
export class PostCategory {
@PrimaryGeneratedColumn()
id: number

@Column({ nullable: true })
name: string

@Column()
postId: number

@Column()
cid: number

@DeleteDateColumn()
deletedAt: Date | null
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import "reflect-metadata"
import { expect } from "chai"
import { DataSource } from "../../../../../../src/data-source/DataSource"
import {
closeTestingConnections,
createTestingConnections,
reloadTestingDatabases,
} from "../../../../../utils/test-utils"
import { Post } from "./entity/Post"
import { Category } from "./entity/Category"
import { PostCategory } from "./entity/PostCategory"

describe("query builder > relation-id > many-to-many > join-conditions", () => {
let connections: DataSource[]
before(
async () =>
(connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
})),
)
beforeEach(() => reloadTestingDatabases(connections))
after(() => closeTestingConnections(connections))

it("should filter deleted join table rows when join condition is specified", () =>
Promise.all(
connections.map(async (connection) => {
const post1 = new Post()
post1.title = "Post 1"
await connection.manager.save(post1)

const category1 = new Category()
category1.name = "Category 1"
await connection.manager.save(category1)

const category2 = new Category()
category2.name = "Category 2"
await connection.manager.save(category2)

const pc1 = new PostCategory()
pc1.cid = category1.id
pc1.postId = post1.id
await connection.manager.save(pc1)

const pc2 = new PostCategory()
pc2.cid = category2.id
pc2.postId = post1.id
pc2.deletedAt = new Date()
await connection.manager.save(pc2)

const loadedPost = await connection.manager.find(Post, {
relations: {
categories: true,
},
})

// Since 1 postCategory is deleted, this should only return 1 category
expect(loadedPost[0].categories.length).to.be.equal(1)
}),
))
})