Home > Software engineering >  typeorm migration with nestjs and postgres "error: database "admin" does not exist&qu
typeorm migration with nestjs and postgres "error: database "admin" does not exist&qu

Time:08-24

please help me.. I'm following this instruction to do migrations in nestjs using typeORM but its always return an error. These my codes:

.env

POSTGRES_HOST = localhost
POSTGRES_PORT = 5432
POSTGRES_USERNAME = postgres
POSTGRES_PASSWORD = pass123
POSTGRES_DATABASE = postgres

ormconfig.ts

import { DataSource } from 'typeorm';
import * as dotenv from 'dotenv';
import { cwd } from 'process';

dotenv.config();

export const dataSource = new DataSource ({
  type: 'postgres',
  host: process.env.DATABASE_HOST,
  port: Number(process.env.DATABASE_PORT),
  username: process.env.DATABASE_USERNAME,
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE_NAME,
  entities: [cwd()   'src/**/*.entity{.ts,.js}'],
  migrations: [cwd()   'src/migrations/*{.ts,.js}'],
  migrationsTableName: 'migrations',
  synchronize: false,
  dropSchema: false,
});

package.json

 "scripts": {
        ....
        "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d ./src/config/ormconfig.ts",
        "migration:create": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli migration:create ./src/migrations/$npm_config_name",
        "migration:generate": "npm run typeorm -- migration:generate ./src/migrations/$npm_config_name",
        "migration:run": "npm run typeorm -- migration:run",
        "migration:revert": "npm run typeorm -- migration:revert",
        "schema:sync": "npm run typeorm -- schema:sync"
        }

when i try to run the command at the first time using this comand

npm run migration:generate --name:CofffeeRefactor

i got the error message that there is no role admin

error: role "admin" does not exist

so i created the role admin in postgresql with this command

CREATE ROLE admin WITH CREATEDB CREATEROLE LOGIN ENCRYPTED PASSWORD 'pass123' SUPERUSER;

I checked

                                   List of roles
 Role name |                         Attributes                         | Member of
----------- ------------------------------------------------------------ -----------
 admin     | Superuser, Create role, Create DB                          | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

so I try it again to generate the migration, but i got the error message that there is no admin database

error: database "admin" does not exist

what should i do now? please help me figure it out

CodePudding user response:

It looks likely that you have at least one previous migration failed or all previous migrations doesn't match with your current database schema.

CodePudding user response:

It seems like your environment variables are not being loaded and typeorm is trying to use a default connection.

Since you are using NestJs you can use the ConfigModule to load your environment. This is how I setup mine:

ormconfig.ts:

import { ConfigModule } from '@nestjs/config';
import { DataSource, DataSourceOptions } from 'typeorm';
import postgresMasterConfig from './postgres.config';

const ENV = process.env.NODE_ENV || 'local';

ConfigModule.forRoot({
  isGlobal: true,
  load: [postgresMasterConfig],
  envFilePath: `env/env.${ENV}`, // If you don't specify envFilePath it will use your .env file
});

export const connectionSource = new DataSource(postgresMasterConfig() as DataSourceOptions);

postgres.config:

import { registerAs } from '@nestjs/config';
import { join } from 'path';

export default registerAs('database', () => ({
  name: 'default',
  type: 'postgres',
  url: process.env.DATABASE_URL,
  ssl: false,
  logging: process.env.DATABASE_ENABLE_LOGGING === 'true',
  entities: [join(__dirname, '../synchronizer/models/**/*.entity.{ts,js}')],
  migrations: [join(__dirname, process.env.NODE_ENV === 'test' ? '../database/tests/*.ts' : '../database/migrations/*.ts')],
  seeds: [join(__dirname, '../database/seeds/**/*.{ts,js}')],
  autoLoadEntities: true,
  synchronize: false,
  migrationsRun: false,
}));

For me the benefits of setting it up like this is to allow me to access specific aspects of the configuration from the NestJs ConfigService that you can inject somewhere else to access your configuration.

  • Related