user1073555
user1073555

Reputation: 27

PrismaJS: How to provide database url by setting all parts separately in .env file

I would like to have the different DB URL components in my .env file as following:

MYSQL_HOST: 
MYSQL_PORT:
MYSQL_USERNAME:
MYSQL_PASSWORD:

Instead of:

DATABASE_URL: mysql://<user>:<password>@<host>:<port>/<dbname>

The best would be to provide my config separately on prisma schema as following:

datasource db {
  provider = "mysql"
  host      = env("DATABASE_HOST")
  port      = env("DATABASE_PORT")
  ...
}

Another solution should be to find a way to concatenete my URL as following:

datasource db {
  provider = "mysql"
  url      = mysql://env("DATABASE_USER"):env("DATABASE_PASS")@env("DATABASE_HOST")...
  ...
}

Is it possible easily?

I cannot create a .env variable from other variables as following:

MYSQL_HOST: 
MYSQL_PORT:
MYSQL_USERNAME:
MYSQL_PASSWORD:
MYSQL_URL: mysql://$MYSQL_USERNAME:$MYSQL_PASSWORD@...

Because all variables in my .env file are downloaded (so replaced) from a vault and I don't want to get define MYSQL_URL in my vault.

So I tried to override the constructor of the PrismaClient as following:

export class PrismaService extends PrismaClient implements OnModuleInit {
  constructor() {
    let url = 'mysql://'

    url += process.env.MYSQL_USERNAME
    url += ':'
    url += process.env.MYSQL_PASSWORD
    url += '@'
    url += process.env.MYSQL_HOST
    url += ':'
    url += process.env.MYSQL_PORT
    url += '/'
    url += process.env.MYSQL_DATABASE

    super({
      datasources: {
        db: {
          url,
        },
      },
    })
  }
}

But the commands npx prisma migrate, npx prisma generate, etc. don't work anymore.

Do you have an idea?

Thank you

Upvotes: 1

Views: 2728

Answers (1)

Ded the Super Duck
Ded the Super Duck

Reputation: 107

Check this out: how to make dynamic db url?

You can just initiate prisma like this

const prisma = new PrismaClient({
  datasources: {
    db: {
      url: `mysql://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}/${DB_NAME}`,
    },
  },
})

And on prisma.schema change your url to empty string

datasource db {
  provider = "mysql"
  url = ""
}

New Update, you can also try this at .env file

DATABASE_URL=mysql://${MYSQL_USER}:${MYSQL_PASSWORD}@${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DBNAME}

Upvotes: 3

Related Questions