typescriptpostgresqltypeormdatabase-migration

TypeORM: No changes in database schema were found - cannot generate a migration


After having created all the database tables using synchronize: true, I am trying to add migration support to my nodejs typescript project. When I am running the command npx typeorm-ts-node-commonjs migration:generate -d path/to/datasource path/to/migration after making changes in one of the entities defined in the datasource object, typeorm is unable to detect the new schema changes and not creating a migration file.

TypeORM Version: 0.3.24 (also tried with o.3.23 and 0.3.20)

I am getting below message:

No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command.

Here is my data source (I am using Postgres as my database):

export default new DataSource({
    type: "postgres",
    host: process.env.POSTGRES_HOSTNAME,
    port: parseInt(process.env.POSTGRES_PORT),
    username: process.env.POSTGRES_USERNAME,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_CONTENT_DATABASE,
    synchronize: false,
    entities: ["src/entity/content/*.{ts,js}"],
    migrations: ["src/migrations/content/*.{ts,js}"],
    logging: "all",
});

After spending a lot of time debugging the issue, I though of running the command on an entirely new & empty Postgres DB, and I observed something very strange. I saw that migration file actually got generated BUT ONLY FOR THE JOIN TABLES (i.e., the many-to-many relationship tables)

I can still continue with the migration using migration:create command and write the migration sql by myself, but I want to generate the diff SQL, which doesn't seem to be working in my case.

Can someone please guide or help me with this issue?

I was expecting to generate the auto generated SQL migration for my schema, but I only got the SQL for join tables


Solution

  • After hours of debugging, I found what the issue was. Each of my entity class was decorated with the below decorator

    @Entity({ name: "table_name", synchronize: false })
    

    I mark all the entities with synchronize: false to avoid any accidental schema changes, as if I enable the synchronization on data source level, it will apply to all the entities (or tables).

    Setting this to synchronize: true enabled typeorm to consider this entity for migration, and thus, I were able to generate migrations for all modified entities by temporarily enabling this synchronization attribute for entities requiring migration script to be generated automatically.