TypeORM - generate migrations from existings entites

Viewed 3543

Got a nest.js/typeorm/postgres application that I have been developing for the last year. Been creating/adding/removing tables/columns but never used migrations.

Now comes time to deploy and whenever I run typeorm migration:generate, a migration file is created for the last colums that I added/removed from only 1 or 2 tables.

Is it possible to generate a migration for all existing entities that are already part of my db schema?

Basically, the up would create each table with FKs, indexes, constraints, etc and the down would drop all of that.

Note: I noticed this post. Is this the correct approach for my issue?

1 Answers

I solved this by doing the following:

  1. dropping and recreating my database in postgres
  2. ran npm run typeorm:reset
  3. then npm run typeorm:migrate
  4. then typeorm:run

scripts for reference

package.json

    "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js",
    "typeorm:sync": "npm run typeorm schema:sync",
    "typeorm:drop": "npm run typeorm schema:drop",
    "typeorm:reset": "npm run typeorm:drop && npm run typeorm:sync",
    "typeorm:migrate": "env NODE_ENV=development npm run typeorm migration:generate -- -n",
    "typeorm:create": "env NODE_ENV=development npm run typeorm migration:create -- -n",
    "typeorm:run": "ts-node -r tsconfig-paths/register $(yarn bin typeorm) migration:run"

ormconfig.js

const config = {
  type: 'postgres',
  host: process.env.RDS_HOST,
  port: Number(process.env.RDS_PORT),
  username: process.env.RDS_USERNAME,
  password: process.env.RDS_PASSWORD,
  database: process.env.RDS_DB_NAME,
  synchronize: process.env.NODE_ENV === 'production' ? false : true,
  dropSchema: false,
  logging: process.env.NODE_ENV === 'development' ? true : false,
  entities: [`${__dirname}/src/**/**.entity{.ts,.js}`],
  migrations: [`${__dirname}/src/migrations/**/*{.ts,.js}`],
  cli: {
    migrationsDir: 'src/migrations',
  },
}

module.exports = config

Note:

  • in my typeORM scripts, I use tsconfig-paths/register because I have path aliases in my tsconfig.json file that I use in my *.entity.ts files.
Related