Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migration:generate: No changes in database schema were found #5965

Closed
diogodomanski opened this issue Apr 28, 2020 · 19 comments
Closed

migration:generate: No changes in database schema were found #5965

diogodomanski opened this issue Apr 28, 2020 · 19 comments

Comments

@diogodomanski
Copy link

diogodomanski commented Apr 28, 2020

Issue type:

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

Database system/driver:

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

TypeORM version:

[ ] latest
[ ] @next
[x] 0.2.24

I'm am developing an application using NestJS and TypeORM. Whenever I try to generate migrations from my entities (by running typeorm migration:generate) I get the following message:

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

I even deleted all the existing migration files (from migrations folder) to exclude any possibility of conflict.

The problem begun after I changed my application's modules folders structure to:

src
 |- config
 |   |- database
 |       |- mysql
 |           |- cli-configuration.ts
 |- migrations
 |- module1
     |- controller
     |- entity
     |- service

As can be seen, the migrations folder is right under src and each module has an entity folder, where the entities for that module are placed. All the ormconfig settings come from cli-configuration.ts file.

In package.json file I added the following to scripts:

{
  ...
  "scripts": {
    ...
    "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/config/database/mysql/cli-configuration.ts",
    "typeorm:migrate": "npm run typeorm migration:generate -- -n",
    "typeorm:run": "npm run typeorm migration:run"
  }
}

The content of src/config/database/mysql/cli-configuration.ts file is:

import * as path from 'path';
import * as dotenv from 'dotenv';

dotenv.config({
  // Path relative to project root folder (because cli command is invoked from there)
  path: path.resolve('environment', (process.env.NODE_ENV === "production") ? ".env.production" : ".env")
});

const config = {
  type: "mysql",
  host: process.env.TYPEORM_HOST,
  port: Number(process.env.TYPEORM_PORT),
  username: process.env.TYPEORM_USERNAME,
  password: process.env.TYPEORM_PASSWORD,
  database: process.env.TYPEORM_DATABASE,
  entities: [path.resolve('src', process.env.TYPEORM_ENTITIES)],

  // We are using migrations, synchronize should be set to false.
  synchronize: false,

  // Run migrations automatically,
  // you can disable this if you prefer running migration manually.
  migrationsRun: true,
  logging: process.env.TYPEORM_LOGGING,

  // Allow both start:prod and start:dev to use migrations
  // __dirname is either dist or src folder, meaning either
  // the compiled js in prod or the ts in dev.
  migrations: [path.resolve('src', process.env.TYPEORM_MIGRATIONS)],
  cli: {
    // Location of migration should be inside src folder
    // to be compiled into dist/ folder.
    // entitiesDir: process.env.TYPEORM_ENTITIES_DIR,
    migrationsDir: path.resolve('src', process.env.TYPEORM_MIGRATIONS_DIR),
    // subscribersDir: process.env.TYPEORM_SUBSCRIBERS_DIR,
  },
  dropSchema: false
};

export = config;

Running console.log(config) I get:

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "root",
  "password": "root",
  "database": "myapp",
  "entities": [ 
    "/var/www/html/myapp/src/**/*.entity{.ts,.js}" 
  ],
  "synchronize": false,
  "migrationsRun": true,
  "logging": "all",
  "migrations": [
    "/var/www/html/myapp/src/migrations/**/*{.ts,.js}" 
  ],
  "cli": { 
    "migrationsDir": "/var/www/html/myapp/src/migrations" 
  },
  "dropSchema": false
}

Last but not least.... After spending hours on this issue (making changes to migrations and entities paths, hard-coding values besides getting them from process.env, etc), I tried to execute yarn run typeorm schema:log (npm run works as well). I got surprised when I saw that all the content that I expected to be in the migration file I am trying to generate was output to console.

CREATE TABLE `permission_permission` (`id` varchar(36) NOT NULL, `name` varchar(100) NOT NULL, `code` text NOT NULL, `create_date` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `update_date` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `delete_date` datetime(6) NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE `permission_role` (`id` varchar(36) NOT NULL, `name` varchar(100) NOT NULL, `code` varchar(255) NOT NULL, `create_date` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `update_date` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `delete_date` datetime(6) NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE `user_user` (`id` varchar(36) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `is_active` tinyint NOT NULL DEFAULT 0, `create_date` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `update_date` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `delete_date` datetime(6) NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE `permission_role_permission` (`permission_id` varchar(36) NOT NULL, `role_id` varchar(36) NOT NULL, INDEX `IDX_3247040996395a5faea3c9b3a5` (`permission_id`), INDEX `IDX_7d9cfbfd027256ab08658bcf6e` (`role_id`), PRIMARY KEY (`permission_id`, `role_id`)) ENGINE=InnoDB;
CREATE TABLE `user_user_role` (`role_id` varchar(36) NOT NULL, `user_id` varchar(36) NOT NULL, INDEX `IDX_c0c2bbb31e8e8708efc6dd5a64` (`role_id`), INDEX `IDX_beb8c39c852f4d132ba44b483c` (`user_id`), PRIMARY KEY (`role_id`, `user_id`)) ENGINE=InnoDB;
ALTER TABLE `permission_role_permission` ADD CONSTRAINT `FK_3247040996395a5faea3c9b3a54` FOREIGN KEY (`permission_id`) REFERENCES `permission_role`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
ALTER TABLE `permission_role_permission` ADD CONSTRAINT `FK_7d9cfbfd027256ab08658bcf6e1` FOREIGN KEY (`role_id`) REFERENCES `permission_permission`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
ALTER TABLE `user_user_role` ADD CONSTRAINT `FK_c0c2bbb31e8e8708efc6dd5a64b` FOREIGN KEY (`role_id`) REFERENCES `user_user`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
ALTER TABLE `user_user_role` ADD CONSTRAINT `FK_beb8c39c852f4d132ba44b483c0` FOREIGN KEY (`user_id`) REFERENCES `permission_role`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;

Can anyone tell me why is schema:log detecting the changes in my entities, but migration:generate is not working?

@mastilver
Copy link

Generating migrations compare your current database with your schema

So if your database it already in the desired state, no migrations will be generated

@diogodomanski
Copy link
Author

Hi @mastilver, thanks for you answer, but the problem is that there are changes in my entities that need to be synced with the database. Those changes are being detected by schema:log command, but not by migration:generate

@anton-bot
Copy link

Run npm run build before generating a migration. For me the problem was that typeorm can only pick up the changes after building.

@Gennady77
Copy link

The same problem! schema:log says me that my schema is up to date but my database is empty. There is no any table.

@chiahsoon
Copy link

chiahsoon commented Nov 8, 2021

I'm encountering this issue as well for postgres! @diogodomanski did you manage to fix this?

@Kalud-Z
Copy link

Kalud-Z commented Dec 1, 2021

Im having the same issue. How to fix this !

@CorentinPacaud
Copy link

CorentinPacaud commented Dec 8, 2021

I think I am not the only one to have this problem. :D
Edit : I uninstall typeorm package and reinstall it in version 0.2.24 and it works. I really think there is a pb with the last version.
Edit 2: In latest version, typeorm was unable to synchronize the DB automaticaally. WIth version 0.2.21, it did it at first try.

@mezeru
Copy link

mezeru commented Jan 13, 2022

Turns out my postgres database was storing the migrations in a pgdata folder
I solved this issue by deleting the pgdata folder and removing volumes from the docker-compose file
Still the migrations are not getting reflected on the database for some reason

@kzamulin
Copy link

kzamulin commented Jan 23, 2022

Faced with same error and fixed it. I'm using ormconfig.env configuration and I had a coma ',' inside TYPEORM_ENTITIES variable it looked like:

TYPEORM_ENTITIES='./apps/**/*.entity{.ts,.js}'

This variable must turn to array in JS, thus there is function that splits string by coma

protected stringToArray(variable?: string) {
. As far as my string value had coma in it I got incorrect entities path in the end and typeorm could not find my entities
After I set variable as below, issue was fixed:

TYPEORM_ENTITIES='./apps/**/*.entity.ts'

@Kyubendo
Copy link

I have a similar problem.

In my ormconfig.js:

{
    entities: [
        "src/entity/**/*.{.ts,.js}"
    ],
    migrations: [
        "src/migration/**/*.{.ts,.js}"
    ],
    cli: {
        "entitiesDir": "src/entity",
        "migrationsDir": "src/migration",
        "subscribersDir": "src/subscriber"
    },
}

packege.json:

"scripts": {
    [...]
    "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
  },

I have empty database (and some entities classes), but after npm run typeorm schema:log and npm run typeorm migration:generate -- -n Initial i get
No changes in database schema were found

I'm also using docker with posgres and I've deleted data folder as @mezeru said, but nothing changed.

@ffastym
Copy link

ffastym commented Jan 30, 2022

In my case was just missed TYPEORM_ENTITIES=src/db/models/entities/*.ts .env constant

@Martin444
Copy link

i can solve this runnin:
npm run typeorm query "DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT USAGE ON SCHEMA public to PUBLIC; GRANT CREATE ON SCHEMA public to PUBLIC; COMMENT ON SCHEMA public IS 'standard public schema';"

and try again

@fortuneehis
Copy link

Run npm run build before generating a migration. For me the problem was that typeorm can only pick up the changes after building.

This worked for me, i still don't know why

@LeandroMedvedev
Copy link

it was giving the same error but it worked with this structure:

my data-source.ts file:

import "reflect-metadata";
import { config } from "dotenv";
import { DataSource } from "typeorm";
import { join } from "path";

config();

export const AppDataSource = new DataSource({
  type: "postgres",
  url: process.env.DB_URI_DEV,
  ssl:
    process.env.NODE_ENV === "production"
      ? { rejectUnauthorized: false }
      : false,
  synchronize: false,
  logging: true,
  entities:
    process.env.NODE_ENV === "production"
      ? ["dist/entities/**/*.js"]
      : [join(__dirname, "./entities/**/*.ts")],
  migrations:
    process.env.NODE_ENV === "production"
      ? ["dist/migrations/**/*.js"]
      : [join(__dirname, "./migrations/**/*.ts")],
});

my server.ts file:

import { config } from "dotenv";

import app from "./app";
import { AppDataSource } from "./data-source";

config();

AppDataSource.initialize()
  .then(() => {
    console.log("Data Source initialized");

    const port = process.env.PORT ?? 3000;

    app.listen(port, () =>
      console.log(`App running!\nhttp://localhost:${port}/`)
    );
  })
  .catch((error) =>
    console.log("Error during Data Source initialization", error)
  );

my app.ts file:

import "express-async-errors";
import express from "express";

import { errorHandling } from "./errors";
import registerRoutes from "./routes";

const app = express();

app.use(express.json());

registerRoutes(app);

app.use(errorHandling);

export default app;

My error was in the entities path in the data-source.ts file.
After I fixed the path, it worked.

@RohitRox
Copy link

it was giving the same error but it worked with this structure:

my data-source.ts file:

import "reflect-metadata";
import { config } from "dotenv";
import { DataSource } from "typeorm";
import { join } from "path";

config();

export const AppDataSource = new DataSource({
  type: "postgres",
  url: process.env.DB_URI_DEV,
  ssl:
    process.env.NODE_ENV === "production"
      ? { rejectUnauthorized: false }
      : false,
  synchronize: false,
  logging: true,
  entities:
    process.env.NODE_ENV === "production"
      ? ["dist/entities/**/*.js"]
      : [join(__dirname, "./entities/**/*.ts")],
  migrations:
    process.env.NODE_ENV === "production"
      ? ["dist/migrations/**/*.js"]
      : [join(__dirname, "./migrations/**/*.ts")],
});

my server.ts file:

import { config } from "dotenv";

import app from "./app";
import { AppDataSource } from "./data-source";

config();

AppDataSource.initialize()
  .then(() => {
    console.log("Data Source initialized");

    const port = process.env.PORT ?? 3000;

    app.listen(port, () =>
      console.log(`App running!\nhttp://localhost:${port}/`)
    );
  })
  .catch((error) =>
    console.log("Error during Data Source initialization", error)
  );

my app.ts file:

import "express-async-errors";
import express from "express";

import { errorHandling } from "./errors";
import registerRoutes from "./routes";

const app = express();

app.use(express.json());

registerRoutes(app);

app.use(errorHandling);

export default app;

My error was in the entities path in the data-source.ts file. After I fixed the path, it worked.

Can confirm this in datasource config

 // ...
  entities:
    process.env.NODE_ENV === "production"
      ? ["dist/entities/**/*.js"]
      : [join(__dirname, "./entities/**/*.ts")],
  migrations:
    process.env.NODE_ENV === "production"
      ? ["dist/migrations/**/*.js"]
      : [join(__dirname, "./migrations/**/*.ts")],

works with/without running npm run build.

@Rayjunqueira
Copy link

it was giving the same error but it worked with this structure:
my data-source.ts file:

import "reflect-metadata";
import { config } from "dotenv";
import { DataSource } from "typeorm";
import { join } from "path";

config();

export const AppDataSource = new DataSource({
  type: "postgres",
  url: process.env.DB_URI_DEV,
  ssl:
    process.env.NODE_ENV === "production"
      ? { rejectUnauthorized: false }
      : false,
  synchronize: false,
  logging: true,
  entities:
    process.env.NODE_ENV === "production"
      ? ["dist/entities/**/*.js"]
      : [join(__dirname, "./entities/**/*.ts")],
  migrations:
    process.env.NODE_ENV === "production"
      ? ["dist/migrations/**/*.js"]
      : [join(__dirname, "./migrations/**/*.ts")],
});

my server.ts file:

import { config } from "dotenv";

import app from "./app";
import { AppDataSource } from "./data-source";

config();

AppDataSource.initialize()
  .then(() => {
    console.log("Data Source initialized");

    const port = process.env.PORT ?? 3000;

    app.listen(port, () =>
      console.log(`App running!\nhttp://localhost:${port}/`)
    );
  })
  .catch((error) =>
    console.log("Error during Data Source initialization", error)
  );

my app.ts file:

import "express-async-errors";
import express from "express";

import { errorHandling } from "./errors";
import registerRoutes from "./routes";

const app = express();

app.use(express.json());

registerRoutes(app);

app.use(errorHandling);

export default app;

My error was in the entities path in the data-source.ts file. After I fixed the path, it worked.

Can confirm this in datasource config

 // ...
  entities:
    process.env.NODE_ENV === "production"
      ? ["dist/entities/**/*.js"]
      : [join(__dirname, "./entities/**/*.ts")],
  migrations:
    process.env.NODE_ENV === "production"
      ? ["dist/migrations/**/*.js"]
      : [join(__dirname, "./migrations/**/*.ts")],

works with/without running npm run build.

Did you manage to solve it? same problem here

@wenmoonsir
Copy link

Run npm run build before generating a migration. For me the problem was that typeorm can only pick up the changes after building.

this works for me. after scratching my head for hours and deleting everything

@Zeshan-Shakil
Copy link

Run npm run build before generating a migration. For me the problem was that typeorm can only pick up the changes after building.

thanks janu its works for me but i don't know why

@Master-gg-02
Copy link

Master-gg-02 commented Dec 13, 2023

I have a similar problem.
schema:log
Your schema is up to date - there are no queries to be executed
by schema synchronization
{ type:"mongodb", host: 'localhost', port: parseInt(37017), database: 'fresh', synchronize: true, cache: true, migrationsRun:true, entities: ["src/entity/**/*.ts"], migrations: ["src/migration/**/*.ts"], subscribers: ["src/subscriber/**/*.ts"], cli: { entitiesDir: "src/entity", migrationsDir: "src/migration", subscribersDir: "src/subscriber", }, dropSchema:true, options: { trustServerCertificate: true, cryptoCredentialsDetails: { minVersion: 'TLSv1' }, }, useUnifiedTopology: true, namingStrategy: new CustomNamingStrategy(), }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests