简体   繁体   English

typeORM 未发现数据库架构更改 - 无法生成迁移。 要创建新的空迁移,请使用“typeorm migration:create”命令

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

I'm doing a course where we are using express-node postgres and react (with typescript) and typeORM.我正在做一门课程,我们使用 express-node postgres 并做出反应(使用打字稿)和 typeORM。 Everything has worked well so far, but I'm facing an issue with typeORM and I don't know what is going and why is this error happening到目前为止一切都运行良好,但我遇到了 typeORM 的问题,我不知道发生了什么以及为什么会发生这个错误

The Big Problem : So, the problem is that, I was doing the auth, and at some point we changed users schema in the DB so we had to make a migration, but, before migration, we did npm run typeorm schema:drop ,but when I tried, this happened with migration大问题:所以,问题是,我正在做身份验证,并且在某些时候我们更改了数据库中的用户模式,所以我们必须进行迁移,但是,在迁移之前,我们做了npm run typeorm schema:drop ,但是当我尝试时,这发生在迁移

This is the first command I used这是我使用的第一个命令

npm run typeorm migration:generate -- --n create-users-table

This was the error这是错误

> new-typeorm-project@0.0.1 typeorm C:\Users\diego cifuentes\Desktop\Studying  Backend\redit> ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"

bin.js migration:generate

Generates a new migration file with sql needs to be executed to update
schema.

Opciones:
  -h, --help          Muestra ayuda                             [booleano]  -c, --connection    Name of the connection on which run a query.
                                                      [defecto: "default"]  -n, --name          Name of the migration class.
                                        [cadena de caracteres] [requerido]  -d, --dir           Directory where migration should be created.
  -p, --pretty        Pretty-print generated SQL
                                               [booleano] [defecto: false]  -f, --config        Name of the file with connection configuration.
                                                    [defecto: "ormconfig"]  -o, --outputJs      Generate a migration file on Javascript instead of
                      Typescript               [booleano] [defecto: false]      --dr, --dryrun  Prints out the contents of the migration instead of
                      writing it to a file     [booleano] [defecto: false]      --ch, --check   Verifies that the current database is up to date and                      that no migrations are needed. Otherwise exits with
                      code 1.                  [booleano] [defecto: false]  -v, --version       Muestra número de versión                 [booleano]
Falta argumento requerido: n
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! new-typeorm-project@0.0.1 typeorm: `ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the new-typeorm-project@0.0.1 typeorm script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\diego cifuentes\AppData\Roaming\npm-cache\_logs\2021-05-11T15_29_02_081Z-debug.log

After hours trying to search for solution everywhere, I change the last command to this one经过数小时试图到处寻找解决方案后,我将最后一个命令更改为这个

npx typeorm migration:generate -- --n create-users-table

And the error was different this time, looks like this而这次的错误不同,看起来像这样

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

So, I said, ok, I'm getting closer to fixing this, but... After hours ( again ) looking for a new answer, I couldn't find anything, so, I'm getting to a point where I need to write this post in order to fix my problem.所以,我说,好吧,我越来越接近解决这个问题了,但是......几个小时后(再次)寻找新答案,我找不到任何东西,所以,我已经到了我需要的地步写这篇文章是为了解决我的问题。 So now, let me show you my ormconfig, my package.json and the entity I want to migrate in my postgres DB.现在,让我向您展示我的 ormconfig、我的 package.json 以及我想在我的 postgres 数据库中迁移的实体。

package.json (the script typeorm is at the end) package.json(脚本typeorm在最后)

{
  "name": "new-typeorm-project",
  "version": "0.0.1",
  "description": "Awesome project developed with TypeORM.",
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/cookie": "^0.4.0",
    "@types/cookie-parser": "^1.4.2",
    "@types/express": "^4.17.11",
    "@types/jsonwebtoken": "^8.5.1",
    "@types/morgan": "^1.9.2",
    "@types/node": "^15.0.2",
    "morgan": "^1.10.0",
    "nodemon": "^2.0.7",
    "ts-node": "^9.1.1",
    "typescript": "^4.2.4"
  },
  "dependencies": {
    "bcrypt": "^5.0.1",
    "class-transformer": "^0.4.0",
    "class-validator": "^0.13.1",
    "cookie": "^0.4.1",
    "cookie-parser": "^1.4.5",
    "dotenv": "^9.0.1",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "pg": "^8.4.0",
    "reflect-metadata": "^0.1.10",
    "typeorm": "0.2.32"
  },
  "scripts": {
    "start": "ts-node src/server.ts",
    "dev": "nodemon --exec ts-node src/server.ts",
    "typeorm": "ts-node ./node_modules/typeorm/cli.js"
  }
}

ormconfing.json Quick note : I changed entities, migrations and subscribers to.js, because with.ts was always giving me error. ormconfing.json快速说明:我将实体、迁移和订阅者更改为.js,因为 with.ts 总是给我错误。

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "**",
  "password": "**",
  "database": "**",
  "synchronize": true,
  "logging": true,
  "entities": ["src/entities/**/*.js"],
  "migrations": ["src/migrations/**/*.js"],
  "subscribers": ["src/subscribers/**/*.js"],
  "cli": {
    "entitiesDir": "src/entities",
    "migrationsDir": "src/migrations",
    "subscribersDir": "src/subscribers"
  }
}

And last thing I want to show you, even though it might not be that important, this is the users schema最后我想向您展示的东西,即使它可能不那么重要,这是用户模式

import {
  Entity as TOEntity,
  Column,
  Index,
  BeforeInsert,
  OneToMany
} from "typeorm";
import bcrypt from "bcrypt";
import { IsEmail, Length } from "class-validator";
import { Exclude } from "class-transformer";

import Entity from "./Entity";
// import Post from "./Post";

@TOEntity("users")
export default class User extends Entity {
  constructor(user: Partial<User>) {
    super();
    Object.assign(this, user);
  }

  @Index()
  @IsEmail()
  @Column({ unique: true })
  email: string;

  @Index()
  @Length(3, 200)
  @Column({ unique: true })
  username: string;

  @Exclude()
  @Length(6, 200)
  @Column()
  password: string;

  // @OneToMany(() => Post, post => post.user)
  // posts: Post[];

  @BeforeInsert()
  async hashedPassword() {
    this.password = await bcrypt.hash(this.password, 6);
  }
}

End Goal : So, if you can help me with this, you will save my life.最终目标:所以,如果你能帮助我,你会救我的命。 One last thing is that I tried to post my problems first in the Spanish website of stack overflow, but nobody could help me, so maybe here someone will, thanks for your time and take care!最后一件事是我试图首先在堆栈溢出的西班牙语网站上发布我的问题,但没有人可以帮助我,所以也许这里有人会,感谢您的时间并保重!

Change your entities , migrations and subscribers into your dist directory.将您的entitiesmigrationssubscribers更改为您的dist目录。

eg:例如:

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

dist directory is the directory which gets created when you build the app. dist目录是您构建应用程序时创建的目录。 You can find your dist directory using tsconfig.json -> compilerOptions -> outDir .您可以使用tsconfig.json -> compilerOptions -> outDir找到您的dist目录。

Then build your app again using npm run build and try to generate the migrations.然后使用npm run build并尝试生成迁移。

I've seen this error, and if I'm not mistaken it's because I was trying to create a bank that had already been created.我已经看到了这个错误,如果我没记错的话,那是因为我试图创建一个已经创建的银行。

This command below deletes all tables:下面的这个命令删除所有表:

yarn 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';"

then:然后:

yarn typeorm --migration:generate -n migration_name -d path/to/your/migrations/

For me the ormconfig.json's was like this,对我来说 ormconfig.json 是这样的,

   "entities": [
      "dist/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],

Changing it to将其更改为

   "entities": [
      "src/entity/**/*{.js,.ts}"
   ],
   "migrations": [
      "src/migration/**/*{.js,.ts}"
   ],
   "subscribers": [
      "src/subscriber/**/*{.js,.ts}"
   ],

generated the migration correctly.正确生成迁移。

And the package.json script is like this "typeorm": "node --require ts-node/register./node_modules/typeorm/cli.js"而package.json脚本是这样的“typeorm”:“node --require ts-node/register./node_modules/typeorm/cli.js”

And the command used is使用的命令是

npm run typeorm migration:generate -- -n FileAddTemporaryDeletedFields -p --dr --ch npm 运行 typeorm 迁移:生成 -- -n FileAddTemporaryDeletedFields -p --dr --ch

ormconfig.json is deprecated in latest version as i know.据我所知,ormconfig.json 在最新版本中已弃用。 but anyway I'm gonna share my solution when i used old version.但无论如何,当我使用旧版本时,我会分享我的解决方案。

when generate, typeorm first reads ormconfig.json and login into rdbms.生成时,typeorm 首先读取 ormconfig.json 并登录到 rdbms。 and compares between 'the actual schema of db' and 'schema file as ormconfig.json[entities]'并在“数据库的实际模式”和“作为 ormconfig.json [实体] 的模式文件”之间进行比较

so, if the file (writen at 'entities' in ormconfig.json) is in dist folder.因此,如果文件(写在 ormconfig.json 中的“实体”处)位于 dist 文件夹中。 you have to edit that.js file.(not.ts file in src folder)您必须编辑 that.js 文件。(不是 src 文件夹中的 .ts 文件)

but, if the 'entities' file is in src folder as ormconfig.json, check if 'autosave' feature of vscode is on.但是,如果“实体”文件在 src 文件夹中为 ormconfig.json,请检查 vscode 的“自动保存”功能是否打开。 if you 'npm run start:dev' It could be the case that the actual schema of db has been already modified before you edit entities file.如果您 'npm run start:dev' 在您编辑实体文件之前,可能已经修改了 db 的实际架构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM