ronantakizawa/codereview-bench huggingface dataset:
Repository: twentyhq/twenty
File: packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/logic-function/services/update-logic-function-action-handler.service.ts (TypeScript)

Code before:
    const existingLogicFunction = findFlatEntityByIdInFlatEntityMapsOrThrow({
      flatEntityMaps: allFlatEntityMaps.flatLogicFunctionMaps,
      flatEntityId: entityId,
    });

    const applicationUniversalIdentifier = flatApplication.universalIdentifier;

    const sourcePathChanged =
      isDefined(update.sourceHandlerPath) &&
      update.sourceHandlerPath !== existingLogicFunction.sourceHandlerPath;

    const builtPathChanged =
      isDefined(update.builtHandlerPath) &&
      update.builtHandlerPath !== existingLogicFunction.builtHandlerPath;

    const logicFunctionRepository =
      queryRunner.manager.getRepository<LogicFunctionEntity>(
        LogicFunctionEntity,
      );

    await logicFunctionRepository.update(
      { id: entityId, workspaceId },
      update as Parameters<typeof logicFunctionRepository.update>[1],
    );

    if (sourcePathChanged) {
      await this.fileStorageService.delete({
        workspaceId,
        applicationUniversalIdentifier,
        fileFolder: FileFolder.Source,
        resourcePath: getLogicFunctionSubfolderForFromSource(entityId),
      });
    }

    if (builtPathChanged) {
      await this.fileStorageService.delete({
        workspaceId,
        applicationUniversalIdentifier,
        fileFolder: FileFolder.BuiltLogicFunction,
        resourcePath: existingLogicFunction.builtHandlerPath,
      });
    }
  }
}


Review comment (suggestion):
I would not touch source at all, it's not their responsibility

I could even argue that built source is not but as there is a 1 for 1 logicFunction / built files, why not

Code after:
      flatEntityMaps: allFlatEntityMaps.flatLogicFunctionMaps,
      flatEntityId: entityId,
    });

    const applicationUniversalIdentifier = flatApplication.universalIdentifier;

    const builtPathChanged =
      isDefined(update.builtHandlerPath) &&
      update.builtHandlerPath !== existingLogicFunction.builtHandlerPath;

    const logicFunctionRepository =
      queryRunner.manager.getRepository<LogicFunctionEntity>(
        LogicFunctionEntity,
      );

    await logicFunctionRepository.update(
      { id: entityId, workspaceId },
      update as Parameters<typeof logicFunctionRepository.update>[1],
    );

    if (builtPathChanged) {
      await this.fileStorageService.delete({
        workspaceId,
        applicationUniversalIdentifier,
        fileFolder: FileFolder.BuiltLogicFunction,
        resourcePath: existingLogicFunction.builtHandlerPath,
      });
    }
  }
}
Repository: typeorm/typeorm
File: test/github-issues/108/issue-108.ts (TypeScript)

Code before:
import "reflect-metadata";
import { createTestingConnections, closeTestingConnections, reloadTestingDatabases } from "../../utils/test-utils";
import { Connection } from "../../../src/connection/Connection";
import { Project } from "./entity/Project";
import { User } from "./entity/User";
import { expect } from "chai";

describe("github issues > #108 Error with constraint names on postgres", () => {

    let connections: Connection[];
    before(async () => connections = await createTestingConnections({
        entities: [__dirname + "/entity/*{.js,.ts}"],
        schemaCreate: true,
        dropSchemaOnConnection: true,
        enabledDrivers: ["postgres", "mssql"] // TODO:Add tests for mssql
    }));
    after(() => closeTestingConnections(connections));

    it("should sync and create column names in the form uk_{tableName}_{columnName}", () => Promise.all(connections.map(async connection => {
        await connection.syncSchema(true);
        for (const entityType of [User, Project]) {
            const metaData = connection.getMetadata(entityType);
            const [nameCol] = metaData.columns.filter(cm => cm.name === "name");
            expect(nameCol).not.undefined;
            expect(nameCol.isUnique).to.be.true;
        }
    })));

});

Review comment (suggestion):
because you have `schemaCreate: true, dropSchemaOnConnection: true,` connection settings sync schema already happens without this line of code

Code after:
import "reflect-metadata";
import { createTestingConnections, closeTestingConnections, reloadTestingDatabases } from "../../utils/test-utils";
import { Connection } from "../../../src/connection/Connection";
import { Project } from "./entity/Project";
import { User } from "./entity/User";
import { expect } from "chai";

describe("github issues > #108 Error with constraint names on postgres", () => {

    let connections: Connection[];
    before(async () => connections = await createTestingConnections({
        entities: [__dirname + "/entity/*{.js,.ts}"],
        schemaCreate: true,
        dropSchemaOnConnection: true,        
    }));
    after(() => closeTestingConnections(connections));

    it("should sync even when there unqiue constraints placed on similarly named columns", () => Promise.all(connections.map(async connection => {        
       // By virtue that we got here means that it must have worked.
       expect(true).is.true;
    })));

});
Repository: typeorm/typeorm
File: test/github-issues/108/issue-108.ts (TypeScript)

Code before:
import "reflect-metadata";
import { createTestingConnections, closeTestingConnections, reloadTestingDatabases } from "../../utils/test-utils";
import { Connection } from "../../../src/connection/Connection";
import { Project } from "./entity/Project";
import { User } from "./entity/User";
import { expect } from "chai";

describe("github issues > #108 Error with constraint names on postgres", () => {

    let connections: Connection[];
    before(async () => connections = await createTestingConnections({
        entities: [__dirname + "/entity/*{.js,.ts}"],
        schemaCreate: true,
        dropSchemaOnConnection: true,
        enabledDrivers: ["postgres", "mssql"] // TODO:Add tests for mssql
    }));
    after(() => closeTestingConnections(connections));

    it("should sync and create column names in the form uk_{tableName}_{columnName}", () => Promise.all(connections.map(async connection => {
        await connection.syncSchema(true);
        for (const entityType of [User, Project]) {
            const metaData = connection.getMetadata(entityType);
            const [nameCol] = metaData.columns.filter(cm => cm.name === "name");
            expect(nameCol).not.undefined;
            expect(nameCol.isUnique).to.be.true;
        }
    })));

});

Review comment (suggestion):
not sure if its a correct test... You probably shouldn't check it here because this test looks like it tests if metadatas are properly created from decorators 

Code after:
import "reflect-metadata";
import { createTestingConnections, closeTestingConnections, reloadTestingDatabases } from "../../utils/test-utils";
import { Connection } from "../../../src/connection/Connection";
import { Project } from "./entity/Project";
import { User } from "./entity/User";
import { expect } from "chai";

describe("github issues > #108 Error with constraint names on postgres", () => {

    let connections: Connection[];
    before(async () => connections = await createTestingConnections({
        entities: [__dirname + "/entity/*{.js,.ts}"],
        schemaCreate: true,
        dropSchemaOnConnection: true,        
    }));
    after(() => closeTestingConnections(connections));

    it("should sync even when there unqiue constraints placed on similarly named columns", () => Promise.all(connections.map(async connection => {        
       // By virtue that we got here means that it must have worked.
       expect(true).is.true;
    })));

});
Repository: typeorm/typeorm
File: src/find-options/FindOperator.ts (TypeScript)

Code before:
     * Gets the child FindOperator if it exists
     */
    get child(): FindOperator<T> | undefined {
        if (InstanceChecker.isFindOperator(this._value)) return this._value

        return undefined
    }

    /**
     * Gets the SQL generator
     */
    get getSql(): SqlGeneratorType | undefined {
        if (InstanceChecker.isFindOperator(this._value))
            return this._value.getSql

        return this._getSql
    }

    transformValue(transformer: ValueTransformer | ValueTransformer[]) {
        if (this._value instanceof FindOperator) {
            this._value.transformValue(transformer)
        } else {
            // do not convert each value of json, since an array is a valid json object
            this._value =
                Array.isArray(this._value) &&
                this["@instanceof"] !== Symbol.for("JsonContains")
                    ? this._value.map(
                          (v: any) =>
                              transformer &&
                              ApplyValueTransformers.transformTo(
                                  transformer,
                                  v,
                              ),
                      )
                    : ApplyValueTransformers.transformTo(
                          transformer,
                          this._value,
                      )
        }
    }
}


Review comment (suggestion):
This is an anti-pattern.. the general `FindOperator` shuoldn't know about `JsonContains`..
`JsonContains` can override `transformValue` maybe.. and call `super` if needed

Code after:
     * Gets the child FindOperator if it exists
     */
    get child(): FindOperator<T> | undefined {
        if (InstanceChecker.isFindOperator(this._value)) return this._value

        return undefined
    }

    /**
     * Gets the SQL generator
     */
    get getSql(): SqlGeneratorType | undefined {
        if (InstanceChecker.isFindOperator(this._value))
            return this._value.getSql

        return this._getSql
    }

    transformValue(transformer: ValueTransformer | ValueTransformer[]) {
        if (this._value instanceof FindOperator) {
            this._value.transformValue(transformer)
        } else {
            this._value =
                Array.isArray(this._value) && this._multipleParameters
                    ? this._value.map(
                          (v: any) =>
                              transformer &&
                              ApplyValueTransformers.transformTo(
                                  transformer,
                                  v,
                              ),
                      )
                    : ApplyValueTransformers.transformTo(
                          transformer,
                          this._value,
                      )
        }
    }
}
Repository: typeorm/typeorm
File: test/github-issues/9944/issue-9944.ts (TypeScript)

Code before:
    let dataSources: DataSource[]
    before(
        async () =>
            (dataSources = await createTestingConnections({
                entities: [__dirname + "/entity/*{.js,.ts}"],
                schemaCreate: true,
                dropSchema: true,
                relationLoadStrategy: "query",
                enabledDrivers: ["mysql"],
            })),
    )
    beforeEach(() => reloadTestingDatabases(dataSources))
    after(() => closeTestingConnections(dataSources))

    it("Validate correct loading of eager, nested relations", () =>
        Promise.all(
            dataSources.map(async (dataSource) => {
                const aEntity = new A()
                aEntity.b = new B()
                aEntity.b.cs = [new C()]
                await dataSource.manager.save(aEntity)

                const [fetchedA] = await dataSource.manager.find(A)
                expect(fetchedA.b).exist // Validates correct relation A.b is loaded
                expect(fetchedA.b.cs).exist // Validates correct relation A.b.cs is loaded
                expect(fetchedA.b.cs[0]).exist
            }),
        ))
})


Review comment (suggestion):
Before the fix, running this test resulted in the `TypeORMError: "A__b" alias was not found. Maybe you forgot to join it?`

With the fix it runs perfectly. I jut added these three assertions to make sure that data from nested relations was indeed loaded correctly

Code after:
    let dataSources: DataSource[]
    before(
        async () =>
            (dataSources = await createTestingConnections({
                entities: [__dirname + "/entity/*{.js,.ts}"],
                schemaCreate: true,
                dropSchema: true,
                relationLoadStrategy: "query",
                enabledDrivers: ["mysql", "postgres"],
            })),
    )
    beforeEach(() => reloadTestingDatabases(dataSources))
    after(() => closeTestingConnections(dataSources))

    it("Validate correct loading of eager, nested relations", () =>
        Promise.all(
            dataSources.map(async (dataSource) => {
                const aEntity = new A()
                aEntity.b = new B()
                aEntity.b.cs = [new C()]
                await dataSource.manager.save(aEntity)

                const [fetchedA] = await dataSource.manager.find(A)
                expect(fetchedA.b).exist // Validates correct relation A.b is loaded
                expect(fetchedA.b.cs).exist // Validates correct relation A.b.cs is loaded
                expect(fetchedA.b.cs[0]).exist
            }),
        ))
})
Repository: typeorm/typeorm
File: test/github-issues/10054/issue-10054.ts (TypeScript)

Code before:
import { OR, DataSource, ILike, Equal } from "../../../src"
import {
    closeTestingConnections,
    createTestingConnections,
    reloadTestingDatabases,
} from "../../utils/test-utils"
import { Person } from "./entity/Person"
import { expect } from "chai"

describe("github issues > #10054 Nested 'OR' Condition/Operation Support in Repository Where condition", () => {
    let dataSources: DataSource[]

    before(async () => {
        dataSources = await createTestingConnections({
            entities: [Person],
            enabledDrivers: ["postgres", "mysql"],
            schemaCreate: true,
            dropSchema: true,
        })
    })

    beforeEach(() => reloadTestingDatabases(dataSources))
    after(() => closeTestingConnections(dataSources))

    it("should find person where name starts with foo or equal to jane", async () => {
        await Promise.all(

Review comment (suggestion):
```suggestion
import { Or, DataSource, ILike, Equal } from "../../../src"
```

Code after:
import { Or, DataSource, ILike, Equal } from "../../../src"
import {
    closeTestingConnections,
    createTestingConnections,
    reloadTestingDatabases,
} from "../../utils/test-utils"
import { Person } from "./entity/Person"
import { expect } from "chai"

describe("github issues > #10054 Nested 'Or' Condition/Operation Support in Repository Where condition", () => {
    let dataSources: DataSource[]

    before(async () => {
        dataSources = await createTestingConnections({
            entities: [Person],
            enabledDrivers: ["postgres", "mysql"],
            schemaCreate: true,
            dropSchema: true,
        })
    })

    beforeEach(() => reloadTestingDatabases(dataSources))
    after(() => closeTestingConnections(dataSources))

    it("should find person where name starts with foo or equal to jane", async () => {
        await Promise.all(
Repository: typeorm/typeorm
File: test/github-issues/10054/issue-10054.ts (TypeScript)

Code before:
import { OR, DataSource, ILike, Equal } from "../../../src"
import {
    closeTestingConnections,
    createTestingConnections,
    reloadTestingDatabases,
} from "../../utils/test-utils"
import { Person } from "./entity/Person"
import { expect } from "chai"

describe("github issues > #10054 Nested 'OR' Condition/Operation Support in Repository Where condition", () => {
    let dataSources: DataSource[]

    before(async () => {
        dataSources = await createTestingConnections({
            entities: [Person],
            enabledDrivers: ["postgres", "mysql"],
            schemaCreate: true,
            dropSchema: true,
        })
    })

    beforeEach(() => reloadTestingDatabases(dataSources))
    after(() => closeTestingConnections(dataSources))

    it("should find person where name starts with foo or equal to jane", async () => {
        await Promise.all(
            dataSources.map(async (dataSource) => {
                debugger
                const foo = new Person()
                foo.name = "Foo"
                foo.age = null

                const john = new Person()
                john.name = "John"
                john.age = 11

Review comment (suggestion):
```suggestion
describe("github issues > #10054 Nested 'Or' Condition/Operation Support in Repository Where condition", () => {
```

Code after:
import { Or, DataSource, ILike, Equal } from "../../../src"
import {
    closeTestingConnections,
    createTestingConnections,
    reloadTestingDatabases,
} from "../../utils/test-utils"
import { Person } from "./entity/Person"
import { expect } from "chai"

describe("github issues > #10054 Nested 'Or' Condition/Operation Support in Repository Where condition", () => {
    let dataSources: DataSource[]

    before(async () => {
        dataSources = await createTestingConnections({
            entities: [Person],
            enabledDrivers: ["postgres", "mysql"],
            schemaCreate: true,
            dropSchema: true,
        })
    })

    beforeEach(() => reloadTestingDatabases(dataSources))
    after(() => closeTestingConnections(dataSources))

    it("should find person where name starts with foo or equal to jane", async () => {
        await Promise.all(
            dataSources.map(async (dataSource) => {
                debugger
                const foo = new Person()
                foo.name = "Foo"
                foo.age = null

                const john = new Person()
                john.name = "John"
                john.age = 11
Repository: typeorm/typeorm
File: test/github-issues/10054/issue-10054.ts (TypeScript)

Code before:
    after(() => closeTestingConnections(dataSources))

    it("should find person where name starts with foo or equal to jane", async () => {
        await Promise.all(
            dataSources.map(async (dataSource) => {
                debugger
                const foo = new Person()
                foo.name = "Foo"
                foo.age = null

                const john = new Person()
                john.name = "John"
                john.age = 11

                const dave = new Person()
                dave.name = "Jane"
                dave.age = 12

                const foobar = new Person()
                foobar.name = "FooBar"
                foobar.age = 14

                await dataSource.manager.save([foo, john, dave, foobar])
                const persons = await dataSource.manager.find(Person, {
                    where: {
                        name: OR(ILike("foo%"), Equal("Jane")),
                    },
                })

                expect(persons).to.have.length(3)

                expect(persons.find((user) => user.name === "Foo")).to.be.not
                    .undefined

                expect(persons.find((user) => user.name === "Jane")).to.be.not
                    .undefined

                expect(persons.find((user) => user.name === "FooBar")).to.be.not
                    .undefined
            }),
        )
    })
})


Review comment (suggestion):
```suggestion
                        name: Or(ILike("foo%"), Equal("Jane")),
```

Code after:
    after(() => closeTestingConnections(dataSources))

    it("should find person where name starts with foo or equal to jane", async () => {
        await Promise.all(
            dataSources.map(async (dataSource) => {
                debugger
                const foo = new Person()
                foo.name = "Foo"
                foo.age = null

                const john = new Person()
                john.name = "John"
                john.age = 11

                const dave = new Person()
                dave.name = "Jane"
                dave.age = 12

                const foobar = new Person()
                foobar.name = "FooBar"
                foobar.age = 14

                await dataSource.manager.save([foo, john, dave, foobar])
                const persons = await dataSource.manager.find(Person, {
                    where: {
                        name: Or(ILike("foo%"), Equal("Jane")),
                    },
                })

                expect(persons).to.have.length(3)

                expect(persons.find((user) => user.name === "Foo")).to.be.not
                    .undefined

                expect(persons.find((user) => user.name === "Jane")).to.be.not
                    .undefined

                expect(persons.find((user) => user.name === "FooBar")).to.be.not
                    .undefined
            }),
        )
    })
})
Repository: typeorm/typeorm
File: src/error/EntityNotFoundError.ts (TypeScript)

Code before:
import { EntityTarget } from "../common/EntityTarget"
import { TypeORMError } from "./TypeORMError"
import { ObjectUtils } from "../util/ObjectUtils"
import { InstanceChecker } from "../util/InstanceChecker"

/**
 * Thrown when no result could be found in methods which are not allowed to return undefined or an empty set.
 */
export class EntityNotFoundError extends TypeORMError {
    constructor(entityClass: EntityTarget<any>, criteria: any) {
        super()

        this.message =
            `Could not find any entity of type "${this.stringifyTarget(
                entityClass,
            )}" ` + `matching: ${this.stringifyCriteria(criteria)}`
    }

    private stringifyTarget(target: EntityTarget<any>): string {
        if (InstanceChecker.isEntitySchema(target)) {
            return target.options.name
        } else if (typeof target === "function") {
            return target.name
        } else if (ObjectUtils.isObject(target) && "name" in (target as any)) {
            return (target as any).name
        } else {
            return target as any
        }
    }

    private stringifyCriteria(criteria: any): string {
        try {
            return JSON.stringify(criteria, null, 4)
        } catch (e) {}
        return "" + criteria
    }
}


Review comment (suggestion):
```suggestion
export class EntityNotFoundError<Entity> extends TypeORMError {
    public readonly entityClass: EntityTarget<Entity>
    public readonly criteria: any

    constructor(entityClass: EntityTarget<Entity>, criteria: any) {
```

Code after:
import { EntityTarget } from "../common/EntityTarget"
import { TypeORMError } from "./TypeORMError"
import { ObjectUtils } from "../util/ObjectUtils"
import { InstanceChecker } from "../util/InstanceChecker"

/**
 * Thrown when no result could be found in methods which are not allowed to return undefined or an empty set.
 */
export class EntityNotFoundError extends TypeORMError {
    public readonly entityClass: EntityTarget<any>
    public readonly criteria: any

    constructor(entityClass: EntityTarget<any>, criteria: any) {
        super()

        this.entityClass = entityClass
        this.criteria = criteria

        this.message =
            `Could not find any entity of type "${this.stringifyTarget(
                entityClass,
            )}" ` + `matching: ${this.stringifyCriteria(criteria)}`
    }

    private stringifyTarget(target: EntityTarget<any>): string {
        if (InstanceChecker.isEntitySchema(target)) {
            return target.options.name
        } else if (typeof target === "function") {
            return target.name
        } else if (ObjectUtils.isObject(target) && "name" in (target as any)) {
            return (target as any).name
        } else {
            return target as any
        }
    }

    private stringifyCriteria(criteria: any): string {
        try {