nikivdev/code · error · anyhow::Error

DATABASE_URL not found (set env, PLANETSCALE_DATABASE_URL, o

Error message

DATABASE_URL not found (set env, PLANETSCALE_DATABASE_URL, or add it to {})

What it means

resolve_database_url collects the Postgres connection string from (in order) environment variables (DATABASE_URL / PLANETSCALE_DATABASE_URL) and the .env file inside the project directory. When none of these sources contain DATABASE_URL it bails with this message telling the developer where it looked (the .env path is interpolated).

Source

Thrown at src/storage.rs:127

    for key in [
        "DATABASE_URL",
        "PLANETSCALE_DATABASE_URL",
        "PSCALE_DATABASE_URL",
    ] {
        if let Ok(url) = std::env::var(key) {
            if !url.trim().is_empty() {
                return Ok(url);
            }
        }
    }

    let env_path = project_dir.join(".env");
    if let Some(value) = read_env_value(&env_path, "DATABASE_URL")? {
        return Ok(value);
    }

    bail!(
        "DATABASE_URL not found (set env, PLANETSCALE_DATABASE_URL, or add it to {})",
        env_path.display()
    )
}

fn read_env_value(path: &Path, key: &str) -> Result<Option<String>> {
    if !path.exists() {
        return Ok(None);
    }
    let contents = fs::read_to_string(path)
        .with_context(|| format!("failed to read env file {}", path.display()))?;
    for line in contents.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let line = line.strip_prefix("export ").unwrap_or(line);
        let Some((name, value)) = line.split_once('=') else {

View on GitHub (pinned to a747e741ae)

Solutions

  1. export DATABASE_URL=postgres://user:pass@host:5432/db in your shell before running the command.
  2. Add DATABASE_URL=... to the .env file in the project directory the CLI reports in the message.
  3. Set PLANETSCALE_DATABASE_URL if using PlanetScale-managed credentials.
  4. Copy .env.example to .env in the project dir and fill in the connection string.

Example fix

// before (.env missing DATABASE_URL)
POSTGRES_URL=postgres://localhost/app
// after
DATABASE_URL=postgres://localhost:5432/app
Defensive patterns

Strategy: validation

Validate before calling

import 'dotenv/config'; // or read <project>/.env manually
if (!process.env.DATABASE_URL && !process.env.PLANETSCALE_DATABASE_URL) {
  throw new Error('Set DATABASE_URL (env or <projectDir>/.env) before running migrations.');
}

Type guard

function hasDatabaseUrl(env: NodeJS.ProcessEnv): env is NodeJS.ProcessEnv & { DATABASE_URL: string } {
  return typeof env.DATABASE_URL === 'string' && env.DATABASE_URL.length > 0;
}

Try / catch

try {
  await postgresMigrate({ project });
} catch (e) {
  if (String(e).includes('DATABASE_URL not found')) {
    console.error('Provide DATABASE_URL via env or .env in the project directory.');
    process.exitCode = 1;
    return;
  }
  throw e;
}

Prevention

When it happens

Trigger: Running postgres_migrate when: DATABASE_URL is unset in the shell, PLANETSCALE_DATABASE_URL is unset, and read_env_value finds no DATABASE_URL key in <project_dir>/.env (file missing, key missing, or unreadable).

Common situations: Fresh environment / CI machine with no .env committed (correctly gitignored); .env.example not copied to .env; variable named differently (POSTGRES_URL, SUPABASE_DB_URL) in .env; .env present in repo root but not in the resolved --project directory.

Understand the failure class

Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.

Related errors


AI-assisted analysis of nikivdev/code@a747e741ae (2026-09-01). Data as JSON: /api/errors/a9d831a116dbeb08. Report an issue: GitHub.