Skip to content

Incorrect subject sorting with multi-inheritance entities #9405

@ZBAGI

Description

@ZBAGI

Issue Description

When having multiple layers of inherence in the same entity, entities are incorrectly sorted thus causing error upon cascade insertion.

Expected Behavior

Entities dependence should be correctly sorted allowing cascade actions.

Actual Behavior

While SubjectTopoligicalSorter.sort checks for parentEntityMetadata. Problem lays in subject.metadata.parentEntityMetadata which only holds root parent and ignores intermediate one. Thus while trying to save entity with more then one inheritance order gets messed up.
In my example provided bellow:
subject.metadata.targetName = EmailChanged
subject.metadata.parentEntityMetadata?.targetName = Log
sortedEntityTarget = ChangeLog
As you can see above this this sorter condition will miss EmailChange entity.

And then script tries to insert Change first which causes error:

QueryFailedError: ER_NO_DEFAULT_FOR_FIELD: Field 'logId' doesn't have a default value

Steps to Reproduce

export class Email {}

@Entity()
@TableInheritance({ column: { type: "varchar", name: "type" } })
export abstract class Log {
	@PrimaryGeneratedColumn("increment")
	public readonly id: number;
}
@ChildEntity()
export abstract class ChangeLog<T> extends Log {
	@OneToMany(() => Change, change => change.log, { cascade: true })
	public changes: Change<T>[];
}

@ChildEntity()
export class EmailChanged extends ChangeLog<Email> {}

@Entity()
export class Change<T> {
	@PrimaryGeneratedColumn("increment")
	public readonly id: number;
	@Column("varchar", { nullable: false, length: 255 })
	readonly propertyName: any;
	@Column("json", { nullable: true })
	readonly oldValue?: any;
	@Column("json", { nullable: true })
	readonly newValue?: any;

	@ManyToOne(() => ChangeLog, { cascade: false, nullable: false, onDelete: "CASCADE" })
	public log: ChangeLog<T>;
}

const emailChanged = new EmailChanged();
const change = new Change<Email>();
change.propertyName = "Example";
emailChanged.changes = [change];

await dataSource.getRepository(Log).save(emailChanged); 

My Environment

Dependency Version
Node.js version v16.13.0
Typescript version 4.5.2
TypeORM version 0.3.10

Relevant Database Driver(s)

Tested on mysql driver all tho im pretty sure all other drivers will experience the same issue.

Are you willing to resolve this issue by submitting a Pull Request?

  • ✅ Yes, I have the time, and I know how to start. But I will require additional help with testing and validation of the bugfix.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions