Nestjs with Typeorm No migrations are pending - nestjs

i have a fresh database, i generate migration and then i try to run it but this is the result:
query: SELECT VERSION() AS version
query: SELECT VERSION() AS version
Data Source has been initialized!
query: SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'laps5' AND TABLE_NAME = 'migrations'
query: SELECT * FROM testdb.migrations migrations ORDER BY id DESC
No migrations are pending
It work correctly until i have updated my package.json and now it can't work.
This is my config:
export const datasourceOptions: DataSourceOptions = {
type: 'mysql',
host: 'localhost',
username: 'xxxx',
password: 'xxxxxx',
synchronize: false,
entities: [Token, UserAnag, User],
migrations: ['/migrations/*.js'],
database: process.env.DATABASE,
};
My migration folder is on root of project. I also must change entities option
from:
entities: [__dirname + '/src/entities/*.js'],
to
entities: [Token, UserAnag, User]
because the generate command return to me "No changes in database schema were found"
So actually i can create migration but if i try to run it doesn't work.
I search and try a lot of solution, like change my migration folder position into dist and build solution before launch migration but without it work
The command i use to run migration is:
npm run typeorm migration:run -- -d ./db.datasource.ts
where typeorm is defined as
cross-env NODE_ENV=development typeorm-ts-node-commonjs
In my Production system, it seem's work correctly. Locally none.

You can actually fix it the same way you did with the entities, although it becomes harder to manage once your project grows.
For the entities I would suggest to create a barrel index file to export all your entities, so you can:
import * as entitiesMap from '#project-name/entities';
const entities = Object.values(entitiesMap);
I have entities defined in a lib, read more here NestJS docs.
As for the migrations: TypeOrm can't locate them. Long story short: it tries to resolve them starting from the root and finds the folder with .ts migrations.
To get to the .js you will need to amend the path __dirname + '/**/migrations/*.js' or __dirname + '*/**/migrations/*.js'.
Try adding console log of the resulting path in your config.

Related

Typeorm cli paths on windows

i have a problem with typeorm path on windows. When I want to run an autogenerated migration through the commandline I get this error
"No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command".
I have made changes in entities but they are not registered. Here is a screen of my folder structure (entities are in the entities folder)
And here is my code where for the cli. The error is there but i have no idea how paths are working on windows and i lost few hours on this already.
cli: {
entitiesDir: join(__dirname, "entities", "bookmarks.entity.ts"),
// migrationsDir: join(__dirname, "migration"),
},
I have tried a lot of combinations but nothing is working
Thanks for help in advance

TypeORM configuration

I'm writing a Typescript NodeJs server.
I use TypeORM and for work it needs a config file with two arrays of paths or functions to entities and migrations.
Right now it looks like
{
subscribers: ['build/subscriber/*.js'],
migrations: ['build/migration/*.js'],
}
When I'm starting my app it'll be transpile with tsc and create a build folder with js files. And in these case everything works fine.
But TypeORM have a CLI tool, and I want use it for creating migrations. But I don't want to transpile all projects just to create migration. I'd run the CLI command with ts-node and use ts files. But without transpiration "build/subscriber/*.js" doesn't exist.
Can I do something to use TypeORM CLI without transpiration the whole project?
P.s. If I change config paths to
{
subscribers: ['src/subscriber/*.ts'],
migrations: ['src/migration/*.ts'],
}
The project will stop running.
May there exists a way to see in code transpiled them or not to implement something like optional paths
{
subscribers: isTranspiled ?['build/subscriber/*.js'] : ['src/subscriber/*.ts'],
migrations: isTranspiled ? ['build/migration/*.js'] : ['src/migration/*.ts'],
}
We have the same problem and do the following:
// Hack for webpack
const migrations_path = __dirname.trim() === '/usr/src/app/dist' ? __dirname.trim() : path.join(__dirname, '..');
{
...
migrations: [migrations_path + '/typeorm/migrations/*.{js,ts}'],
}
You'll need to update for your own paths, but this is how we support the dist for production webpack build and for our src folder during hot reloading.

How to generate migration file in typeorm using nest js

I am new this framework Nest JS and created sample Restful API but could not migrate the entity file. I tried many ways it's not working. first time run migration command to generate migration file it's working fine. but second time creating a new entity then run the migration command it's show no changes message how to fix this Issue.
DB config .ts file
{
type: 'postgres',
host: process.env.POSTGRES_HOST,
port: parseInt(process.env.POSTGRES_PORT) || 5432,
database: process.env.POSTGRES_DATABASE,
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
entities: ["dist/**/*.entity{ .ts,.js}"],
synchronize: true,
"migrations": ["dist/migrations/*{.ts,.js}"],
"migrationsTableName": "migrations_typeorm",
// ssl:{
// rejectUnauthorized:false
// }
}
Migration Command
Create and generate migration command
npx typeorm migration:create -n User -d src/migrations
npx typeorm migration:generate -n User -d src/migrations
Run Migration File
npx typeorm migration:run
You should only use migration:generate in your case. This will check your current database structure and compare it against entity file and based on this generate a new migration file with changes.
Problem that you were experiencing was porbably due to override.
migration:create will generate a new empty file and you run migration:generate it will not overwrite that file.
In case you want to write your own migration you can use migration:create as a simple and easy way to name it and structure it automatically.
Edit:
Also make sure to set synchronize to false as it will automatically migrate your data based on entities and changes otherwise.
I always turn this feature off and generate or write migration manually as it gives the most control.

Error: No connection options were found in any orm configuration files

I want connect to oracle with typeorm
createConnection().then(async connection => {
const app = express();
const userRepository = getRepository(User);
const users = await userRepository.find();
console.log(users);
app.listen(3000);
}).catch(error => console.log("xxx",error));
ormconfig.json is in ./Myproject/ormconfig.json but say error :Error: No connection options were found in any orm configuration files.
With these settings , I was already connected to the database with the oracledb.
Please help me
UPDATE
I generate project with this typeorm init --name MyProject --database oracle.
This is typeorm default structure.
Hello I had the same error for one day, but I had to explicitly show the path of the config file
This was my current typeorm package.json script command
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
i changed it to
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js --config src/config/postgres.config.ts"
not how I explicitly set the path of the config file that I am using, no matter which extension you are using, either .js, .ts, or .json
here is the example of my config file
// postgres.config.ts
import { TypeOrmModuleOptions } from '#nestjs/typeorm';
export const pgConfig: TypeOrmModuleOptions = {
type: 'postgres',
host: process.env.POSTGRES_HOST,
port: parseInt(<string>process.env.POSTGRES_PORT),
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DATABASE,
entities: ['dist/src/modules/**/entities/*.entity.js'],
synchronize: true,
migrations: ['dist/src/db/migrations.js'],
cli: { migrationsDir: 'src/db/migrations' },
};
Hope it gonna help
From the picture you posted, you misplaced the ormconfig.json in ./src directory which path maybe your_project/src/ormconfig.json.Please move it to root directory of project(path: your_project/ormconfig.json) will work out!
You can try use the following instead
npx typeorm migration:create -n migrationName
I've experienced this a few times and I noticed that it's some caching issues.
Here're a few things you could do:
Option 1:
Delete your node_modules/ folder and reinstall.
Option 2:
Restart your editor (I'm using vscode)
I solved this problem
$ npm remove -g typeorm
It seems that the path was recognized incorrectly because typeorm is installed as global.

Why my TypeORM can't connect database in product mode?

I am using Nest.js+TypeORM to develop and try to deploy in my computer.
I can connect to mysql in develop mode, but it failed in product mode.
Below is my TypeORM config.
#Module({
imports: [
AuthModule,
ClassificationModule,
ArticleModule,
UserModule,
CommentModule,
FragmentModule,
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
// logging: ["query"],
port: 3306,
username: 'root',
password: '123456',
database: 'myblog',
entities: ['src/**/**.entity{.ts,.js}'],
synchronize: true
})
]
})
export class AppModule { }
In develop mode, it can connect to mysql successfully.
But in product mode, it shows can't connect mysql.
ts-node manages your typescript compilation in memory and handles chaning references from src to dist internally. However, this is a problem when you get into running your pure node variant, as you'll be in a dist directory instead of src, so TypeORM won't be able to find your entities with the defined entities array. Instead you should use entities: [join(__dirname, '/**/*.entity.{js,ts}')], to allow for dynamically changing between ts and js so you don't have to worry about what you are running with.
I would also suggest using tsc-watch for develpoment, as it will run node by default on successful compilation and you won't have to worry about memory consumption from ts-node.

Resources