Reputation: 1023
I'm trying to generate migration files for my entities, but whenever I run the command to create the entity, it creates an "empty" file, just the up and down methods are created.
I have added this script in my package.json file: "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
.
In my app.module.ts, the connection is configured like this:
TypeOrmModule.forRoot({
type: 'mysql',
host: database().host,
port: parseInt(database().port),
username: database().username,
password: database().password,
database: database().schema,
entities: [Question, QuestionOption],
migrations: ['src/migration/*{.ts,.js}'],
cli: {
migrationsDir: 'src/migration'
},
synchronize: true,
})
Where database()
it's a nestjs config file and get the values from an .env file.
The script I'm using to create the migration is: npm run typeorm migration:create -- -n QuestionTables -d src/migrations
where need to specify the -d, otherwise the migration file is not created (even if it's specified in the cli of the forRoot method.
Do I need to write manually the SQL to create the tables?
What if I need to add a new column to an existing table, should I create a new migration file and write manually the SQL code to add that?
Another command that I tried to run was this one: npm run typeorm migration:generate -- -n QuestionTables -d src/migrations
and here it gives me an error: " Error: No connection options were found in any orm configuration files."
Upvotes: 20
Views: 70621
Reputation: 4444
The command npm run typeorm migration:create
will generate empty migration file.
The command for migrations auto generation is: npm run typeorm migration:generate
As written in the error you received you need to specify the configuration file for the cli. Than means should extract the configuration passed to forRoot
to a ts/json file. You'll need 2 files for that, 1 for the server's connection and another for migrations configuration.
For example:
// ormconfig.ts
export const config: TypeOrmModuleOptions = {
type: 'mysql',
host: database().host,
port: parseInt(database().port),
username: database().username,
password: database().password,
database: database().schema,
entities: [Question, QuestionOption], // maybe you should also consider chage it to something like: [__dirname + '/**/*.entity.ts', __dirname + '/src/**/*.entity.js']
migrations: ['src/migration/*{.ts,.js}'],
cli: {
migrationsDir: 'src/migration'
},
synchronize: true,
}
// ormconfig-migrations.ts
import {config} from './ormconfig';
export = config;
import {config} from './ormconfig';
TypeOrmModule.forRoot(config);
// package.json
"scripts": {
...
"typeorm:cli": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -f ./ormconfig-migrations.ts",
"migration-generate": "npm run typeorm:cli -- migration:generate -n"
}
Upvotes: 34