typeorm: migrations doesnt run even after doing everything

Issue type:

[ ] question [x] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [x] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

I am working on a project with typeorm on nestjs. the problem is even after running mgration after generating migration files, i get No migrations are pending

The commands i am using are

 "typeorm": "NODE_ENV=dev ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/config/typeorm.config.ts",
 
"typeorm:migrate": "npm run typeorm migration:generate -- -n",
 
"typeorm:run": "npm run typeorm migration:run"

I am doing

npm run typeorm:migrate test
npm run typeorm:run

BTW: my ormconfig looks like this


import config from '@config/index';
import { join } from 'path';
import { ConnectionOptions } from 'typeorm';

const typeormConfig: ConnectionOptions = {
  type: 'postgres',
  host: config.db.host,
  port: config.db.port,
  logging: ['error'],
  username: config.db.username,
  password: config.db.password,
  database: config.db.database,
  entities: [join(__dirname, '../entities/**{.ts,.js}')],
  synchronize: false,
  migrations: ['migrations/**/*{.ts,.js}'],
  cli: {
    migrationsDir: 'migration',
  },
};

export = typeormConfig;


About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 33 (2 by maintainers)

Most upvoted comments

This No migrations are pending means that somewhere in the migration table it says that you have already run the migration for your migration file. Follow this steps:

  1. If you are using nestjs: Delete your dist folder (Just to make sure you dont get an Duplicated migration error).
  2. Delete everything in the migrationtable.
  3. Run the migration again

Hope this solves you problem.

This is what I am using as the ormconfig.ts

import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';

interface BetterConnectionOptions extends PostgresConnectionOptions {
  readonly seeds?: (Function | string)[];
  readonly factories?: (Function | string)[];
}

const config: BetterConnectionOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'dbusernamegoeshere',
  password: 'changeme',
  database: 'dbnamegoeshere',
  entities: [__dirname + '/entities/**/*.entity{.ts,.js}'],
  synchronize: false,
  migrationsRun: false,
  logging: true,
  logger: 'file',
  migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
  seeds: ['src/database/seeds/**/*.seed.ts'],
  factories: ['src/database/factories/**/*.factory.ts'],
  cli: {
    migrationsDir: 'src/migrations',
  },
};

export = config;

From this we started using dotenv as well for configuration with a file kinda like this:

import * as dotenv from 'dotenv';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';
import * as dbindex from 'database-index';
dotenv.load('./../.env');
interface BetterConnectionOptions extends PostgresConnectionOptions {
  readonly seeds?: Function | string[];
  readonly factories?: Function | string[];
}
const dirName = __dirname;
const config: BetterConnectionOptions = {
  cli: {
    migrationsDir: dirName + '/migration',
  },
  database: process.env.mpDatabaseDatabase,
  entities: dbindex.entities,
  factories: process.env.mpDatabaseFactories.split('|'),
  host: process.env.mpDatabaseHost,
  logger: process.env.mpDatabaseLogger as any,
  logging: process.env.mpDatabaseLogging === 'true',
  migrations: dbindex.migrations,
  migrationsRun: process.env.mpDatabaseMigrationsRun === 'true',
  password: process.env.mpDatabasePassword,
  port: parseInt(process.env.mpDatabasePort),
  seeds: process.env.mpDatabaseSeeds.split('|'),
  synchronize: process.env.mpDatabaseSynchronize === 'true',
  type: process.env.mpDatabaseType as any,
  username: process.env.mpDatabaseUsername,
};

export = config;

One tip that isn’t immediately obvious if you are using dotenv and use any of the typeorm default env variables like these:

TYPEORM_HOST = localhost
TYPEORM_USERNAME = root
TYPEORM_PASSWORD = admin
TYPEORM_PORT = 3000
TYPEORM_LOGGING = true

The cli will use those over the top of your ormconfig.ts for whatever reason so if that is not the behaviour you want then you need to alter your .env.

If you are wondering what that database-index.ts thing we have going on is it is (simplified):

import * as Entities from './entity';
import * as Migrations from './migration';

export const entities = [
  Entities.User,
  Entities.Organisation,
  Entities.Role,
  Entities.Contract,
];

export const migrations = [
    Migrations.PaymentUpdates1583427782841,
    Migrations.PaymentType1583091842118,
    Migrations.AddPaymentType1583062412093,
    Migrations.CurrencyAndCountry1582976070556,
]

Make sure if you are using typescript for the config you pass it as a param in along with build options for typeorm. I was able to get mine working with in package.json "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/ormconfig.ts",

"typeorm:migrate": "npm run typeorm migration:generate -- -n",

"typeorm:run": "npm run typeorm migration:run",

Try to update paths to load entities and migrations from dist (build folder). For example

  "entities": ["dist/**/*.entity{.js}"],
  "migrations": ["dist/migrations/*.js"],

this is caused that the script cannt find any migration files

I’ve solved like this ormconfig.js

// detecting running in ts-node/node
const isTsNode = process[Symbol.for('ts-node.register.instance')]

const config = {
    "type": parsed.protocol.replace(":", ""),
    "host": parsed.hostname,
    "port": parsed.port,
    "username": user,
    "password": pass,
    "database": parsed.pathname.replace(/\//g, ""),
    "synchronize": false,
    "migrationsRun": true,
    "logging": true,
    "entities": [
        path.resolve(__dirname, isTsNode ? `src/db/entity/**/*.ts` : `dist/db/entity/**/*.js`),
    ],
    "migrations": [
        path.resolve(__dirname, isTsNode ? `src/db/migration/**/*.ts` : `dist/db/migration/**/*.js`,),
    ],
    "subscribers": [
        path.resolve(__dirname, isTsNode ? `src/db/entity/**/*.ts` : `dist/db/entity/**/*.js`,),
    ],
    "cli": {
        "entitiesDir": "src/db/entity",
        "migrationsDir": "src/db/migration",
        "subscribersDir": "src/db/subscriber"
    }
}

running with ts-node

node --require ts-node/register /Users/raphaelsoul/projects/zuma/sprider/AssetsMgr/bin/www --project tsconfig.json

// migration deployed

running with node

node /Users/raphaelsoul/projects/zuma/sprider/AssetsMgr/bin/www

cli usage also runs good with yarn exec -- ts-node node_modules/.bin/typeorm migration:revert

Notice if you need run cli without ts-node, the cli section should be also properly configured.

I had similar experiences of not seeing migrations in a NextJS / TypeORM / TS project. This is what I’m doing now:


For migration files in TS:

$ yarn ts-node node_modules/typeorm/cli.js migration:show --config .typeorm-dev.env
# .typeorm-dev.env
TYPEORM_URL='postgres://pguser:secret@127.0.0.1:12345/dev_db'
TYPEORM_MIGRATIONS='./src/db/migrations/*.ts'

For migration files in JS (also, production build and database):

$ TYPEORM_URL=SECRET yarn typeorm migration:run --config .typeorm-prod.env
# .typeorm-prod.env
TYPEORM_MIGRATIONS='dist/db/migrations/*.js'

So I guess TYPEORM_MIGRATIONS and TYPEORM_URL are the minimum requirements to run migrations.

TypeORM document menthions some rules on TypeORM config files and env-vars: https://github.com/typeorm/typeorm/blob/master/docs/using-ormconfig.md#which-configuration-file-is-used-by-typeorm. I didn’t understand them all but this setting works for me now.

This No migrations are pending means that somewhere in the migration table it says that you have already run the migration for your migration file. Follow this steps:

  1. If you are using nestjs: Delete your dist folder (Just to make sure you dont get an Duplicated migration error).
  2. Delete everything in the migrationtable.
  3. Run the migration again

Hope this solves you problem.

@danieldspx Thanks for your tips!

I’m new in the typeorm and back-end world. The step 1 give to me the answer about why I having duplicated migration files.

After generating the initial migration. Have you made sure to run it before making changes to the entities?

You should see a table in postgres called migration that lists all of the migrations that have been run.

Make sure migrationsRun: false in config.

Create inital migration: npm run typeorm:migrate InitialMigration

Run initial migration: npm run typeorm:run

Make changes to an entity.ts npm run typeorm:migrate MyChanges

Run the new migration: npm run typeorm:run

It should give you something like this in the migration files

It could have creates / updates / deletes etc depending on what you have changed.

image

Hi @rubiin I have taken a look at your repo and it seems pretty standard. I have some suggestions that you can try to rule out some issues. If you have already tried these apologies.

Firstly I notice in your typeorm.config.ts your migrations directory typeormConfig.cli.migrationsDir doesn’t seem correct as there doesn’t seem to be a folder called src/Migrations in your project.

I also notice you have migrationsRun: true this will cause nest to auto-run them on startup rather than defering to the cli migration.

Does your db connect in general? I see synchronize is set to false. If it is set to true is it actually writing your db changes?

Next have you tried directly linking your typescript entity files / migration files in your config like I have in the comment above with dbindex ^ https://github.com/typeorm/typeorm/issues/5103#issuecomment-602058732

We need to rule out tooling differences / typescript versions etc next so let me know.