typeorm icon indicating copy to clipboard operation
typeorm copied to clipboard

Entity manager relies on entity class in migrations

Open PatrickHallek opened this issue 3 years ago • 0 comments

Issue Description

The entity manager within a migration uses the entity classes defined in the code, which leads to incorrect migrations when the entity definition changes.

Expected Behavior

The entity manager should use the current data models set in the database and not entities that are not part of the migration logic. I.e. calling await queryRunner.manager.find('User') should translate to a query that is not selecting the whole entity definition defined in code.

Actual Behavior

Using the find() method leads to the following error:

SqliteError: no such column: User.name

Steps to Reproduce

/* 1663656414862-create-user.migration.ts */
export class createUser1663656414862 implements MigrationInterface {
    name = 'createUser1663656414862'

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`CREATE TABLE "User" ("id" integer PRIMARY KEY NOT NULL)`)

        await queryRunner.manager.find('User') // This line leads to the error
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`DROP TABLE "User"`)
    }
}
/* orm-config.ts */
const ormConfig: TypeOrmModuleOptions = {
    keepConnectionAlive: true,
    autoLoadEntities: true,
    type: 'better-sqlite3',
    database: 'typeorm-test/test.db',
    synchronize: false,
    logging: false,
    migrationsRun: true,
    cli: {
        migrationsDir: 'typeorm-test/migrations',
    },
    entities: [path.resolve('typeorm-test', '*.entity.ts')],
    migrations: ['typeorm-test/migrations/*.ts'],
}
/* user.entity.ts */
import { Column, Entity, PrimaryColumn } from 'typeorm'

@Entity('User')
export class User {
    @PrimaryColumn()
    id: number

    @Column()
    name: string // Added after the first migration
}

My Environment

Dependency Version
Operating System MacOS Monterey 12.5.1
Node.js version v16.13.0
Typescript version 4.6.2
TypeORM version 0.2.41

Relevant Database Driver(s)

DB Type Reproducible
aurora-mysql no
aurora-postgres no
better-sqlite3 yes
cockroachdb no
cordova no
expo no
mongodb no
mysql no
nativescript no
oracle no
postgres no
react-native no
sap no
spanner no
sqlite no
sqlite-abstract no
sqljs no
sqlserver no

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

  • ✖️ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

PatrickHallek avatar Sep 20 '22 07:09 PatrickHallek