bun.envdrizzledrizzle-ormdrizzle-kit

drizzle-kit not using .env.test or .env.development in bun.js


I'm working with bun.js and I'm trying to do bun run drizzle-kit push, bun run drizzle-kit generate, bun run drizzle-kit migrate but no any of these commands works for testing environment, the drizzle cannot get my DATABASE_URL from .env.test or .env.development or .env.local...etc I discovered that drizzle-kit can get the environment variables only from .env.

This is my drizzle.config.ts file:

import { defineConfig } from "drizzle-kit";
import config from "config";

export default defineConfig({
  out: "./drizzle",
  schema: "./src/db/schema.ts",
  dialect: "postgresql",
  dbCredentials: {
    url: process.env.DATABASE_URL as string,
  },
});

I'm trying to generate migrations for my DATABASE_URL in .env.test but its always getting the URL from .env only, and if I don't have .env file it will give me error says:

Error  Either connection "url" or "host", "database" are required for PostgreSQL database connection

Is there any way to use different .env file for drizzle?
Note: I am using built in bun.js .env, I am not using any additional dotenv packages


Solution

  • I ended up using --env-file flag to tell bun what .env file to use when I'm running the drizzle commands, for example:

    bun run --env-file=.env.test drizzle-kit push
    

    And I created a scripts in package.json specifically for those operations like bellow:-

    "scripts": {
        "start": "bun run server.ts",
        "dev": "bun run --watch server.ts",
        "test": "NODE_ENV=test bun test --preload ./tests/setup.ts",// this is a bonus line. this line will make sure the tests will use .env.test when test is running and we load a global setup file before starting the tests
        "test-drizzle-generate": "bun --env-file=.env.test drizzle-kit generate",
        "test-drizzle-migrate": "bun --env-file=.env.test drizzle-kit migrate",
        "test-drizzle-push": "bun --env-file=.env.test drizzle-kit push"
      }