Cannot leave user/host blank in DATABASE_URL
Bug description
In other ORMs (TypeORM, SQLAlchemy, Django ORM, etc) I can provide a DATABASE_URL like postgresql:///mydb for local dev and it "just works". Same way I can type psql mydb and it "just works".
This is an issue for local development because the username on my laptop may differ from another developer's.
With Prisma it uses undefined if the host or username are not provided:
❯ DATABASE_URL="postgresql:///mydb" nr introspect
> [email protected] introspect
> prisma db pull && npm run generate
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "mydb", schema "public" at "undefined:5432"
Introspecting based on datasource defined in prisma/schema.prisma …
Error: P1010
User `` was denied access on the database `mydb.public`
❯ DATABASE_URL="postgresql://localhost/mydb" nr introspect
> [email protected] introspect
> prisma db pull && npm run generate
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "mydb", schema "public" at "localhost:5432"
Introspecting based on datasource defined in prisma/schema.prisma …
Error: P1010
User `` was denied access on the database `mydb.public`
❯ DATABASE_URL="postgresql://cyber@localhost/mydb" nr introspect
> [email protected] introspect
> prisma db pull && npm run generate
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "mydb", schema "public" at "localhost:5432"
Introspecting based on datasource defined in prisma/schema.prisma …
✔ Introspected 12 models and wrote them into prisma/schema.prisma in 162ms
Run prisma generate to generate Prisma Client.
How to reproduce
createdb mydb
DATABASE_URL="postgresql:///mydb" npx prisma db pull
Expected behavior
Don't provide user or hostname to pg if they aren't specified in the DSN
Prisma information
Environment & setup
I'm using macOS and https://postgresapp.com/
Prisma Version
prisma : 2.26.0
@prisma/client : 2.26.0
Current platform : darwin
Query Engine : query-engine 9b816b3aa13cc270074f172f30d6eda8a8ce867d (at node_modules/@prisma/engines/query-engine-darwin)
Migration Engine : migration-engine-cli 9b816b3aa13cc270074f172f30d6eda8a8ce867d (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine : introspection-core 9b816b3aa13cc270074f172f30d6eda8a8ce867d (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary : prisma-fmt 9b816b3aa13cc270074f172f30d6eda8a8ce867d (at node_modules/@prisma/engines/prisma-fmt-darwin)
Default Engines Hash : 9b816b3aa13cc270074f172f30d6eda8a8ce867d
Studio : 0.408.0
~~💎 $50 bounty created by prisma~~
~~🙋 If you start working on this, comment /attempt #8230 to notify everyone~~
~~👉 To claim this bounty, submit a pull request that includes the text /claim #8230 somewhere in its body~~
~~📝 Before proceeding, please make sure you can receive payouts in your country~~
~~💵 Payment arrives in your account 2-5 days after the bounty is rewarded~~
~~💯 You keep 100% of the bounty award~~
~~🙏 Thank you for contributing to prisma/prisma!~~
| Attempt | Started (GMT+3) | Solution |
|---|---|---|
| 🔴 @Ola-jed | Sep 4, 2023, 10:56:42 AM | WIP |
| 🟢 @ologbonowiwi | Sep 17, 2023, 5:34:41 PM | WIP |
Hi @revmischa can you give some more clarity what should be the desired output if user/host is not provided in DATABASE_URL?
@kunal00000 - is there more info you'd need than what's outlined under "Expected behavior" in the issue description?
@petradonka . I went through the codebase deeply and found that prisma don't explicitly pass user or hostname as undefined. And the error messageUser `` was denied access on the database 'mydb.public' is directly from postgres and prisma has no involvement in this.
@kunal00000 Hi! You are correct. The error is coming from the underlying database.
The above issue is stating that Prisma requires a user and host in the connection string. We would like that to not be the case.
As @revmischa mentioned postgresql:///mydb is a completely valid connection string but Prisma does not accept it.
Does that make sense?
Hi @jharrell .Yes that totally makes sense, So solution I am able to think is that if username/host is not provided, we can detect default username from os and put it in database_URI ourselves while passing to database and hostname gets assigned to localhost:5432 if nothing is provided.
Does this make sense to approach problem this way?
@kunal00000 that makes sense, but I believe the simpler solution is to simply accept connection strings that are valid.
For the previous example, there's no need to convert it to postgresql://jharrell@localhost:5432/mydb when postgresql:///mydb is completely valid.
One thing, I am not able to understand that when this postgresql:///mydb is valid URI then why do db gives error.
@kunal00000 I'm not sure. But if your local setup is correct then postgresql:///mydb is a valid connection string that will connect to a database. It's not a valid connection string in Prisma. So the logic in Prisma that takes the URL as given and tries to connect to the underlying db is wrong
@jharrell, do you have any clues on where I could start to look to implement this?
The codebase is complex, but I'm determined to fix this issue. I didn't find a place to parse/transform/handle the URL; it would be awesome to get some guidance to find it.
EDIT: I found something here. I'll implement this logic on convertCredentials; can you confirm this is the expected resolution?
@ologbonowiwi I don't know if that's expected or not. My advice would be to put a PR up and then I can review it alongside engineering and then move from there.
Would you happen to have any idea how to test this? I'm trying to use a snapshot test; I hope to open a PR in the next few days
PostgreSQL clients / libpq default to the known UNIX socket location on disk when the host part of the connection string is empty. This is described in the upstream docs: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING-URIS
If you install PostgreSQL directly on a Linux host without further customization, let's use Debian as an example, then PostgreSQL listens on /var/run/postgresql/.s.PGSQL.5432 and uses unix auth for login. So you can login without username, password and host, since the unix socket is on a known path, and the authentication is done using unix permission system. This makes a url like postgresql:///databasename perfectly valid. These default configurations don't even listen on tcp ports, so even casting a empty value to localhost wont fix this.
Workaround is to pass the (url encoded path to the) unix socket as the host part of the URL.
I am not familiar with Prisma myself (I got here because an app I want to use does use Prisma), but if you are using libpq or something based on libpq, you should be able to just defer the URL parsing to libpq instead of validating or normalizing it beforehand.
🚀 Autonomous Bounty Solution Submission
Task: [GH $50] prisma/orm: Cannot leave user/host blank in DATABASE_URL
Estimated Reward: $50 USD (~$50)
Settlement Wallet (USDC on Base / EVM): 0x02c1F87F514493F359Afc0B3ff6b587434770361
Propuesta Técnica: [GH $50] prisma/orm: Cannot leave user/host blank in DATABASE_URL
- Origen: https://github.com/prisma/orm/issues/8230
- Recompensa:
$50 USD(~$50.0 USD) - Motor: DeepSeek (V3) (
0.0027 €)
Resumen Ejecutivo para Revisión Móvil
El bug: Prisma interpreta postgresql:///mydb (sin user/host) como undefined:5432 en vez de usar los defaults de libpq (socket local + usuario del SO). La solución parchea el parser de connection strings en @prisma/internals para que, cuando falten user/host, se resuelvan a process.env.USER/USERNAME y localhost (o socket Unix), replicando el comportamiento de psql mydb. Verificación: tests unitarios del parser + DATABASE_URL="postgresql:///mydb" prisma db pull contra un Postgres local.
Análisis técnico
El problema está en cómo Prisma parsea la URL. new URL("postgresql:///mydb") en Node devuelve:
username: "",hostname: "",port: "",pathname: "/mydb"
Prisma luego hace fallback a la string literal "undefined" al construir el mensaje at undefined:5432 y al conectar pasa user vacío → P1010 User '' was denied access.
Fix correcto (compatible con libpq):
- Si
usernameestá vacío → usarprocess.env.PGUSER ?? process.env.USER ?? process.env.USERNAME ?? os.userInfo().username. - Si
hostnameestá vacío → usarprocess.env.PGHOST ?? "localhost"(o socket Unix/var/run/postgresqlen Linux/macOS si se prefiere paridad total conpsql; para no romper Windows,localhostes el default seguro). - Si
portestá vacío →process.env.PGPORT ?? "5432". - Si
passwordestá vacío →process.env.PGPASSWORD ?? "".
Esto se aplica solo cuando el esquema es postgresql/postgres (MySQL/SQLite tienen otras reglas).
Código
packages/internals/src/utils/resolvePostgresDefaults.ts (nuevo)
import os from 'os'
export interface ParsedPostgresUrl {
user: string
password: string
host: string
port: string
database: string
schema?: string
query: URLSearchParams
}
/**
* Resolves libpq-compatible defaults for a postgres connection URL.
* Mirrors `psql mydb` behavior: missing user/host fall back to
* environment variables and finally to the OS user / localhost.
*
* Only applies to postgres/postgresql schemes. Other schemes are
* returned untouched by the caller.
*/
export function resolvePostgresDefaults(rawUrl: string): ParsedPostgresUrl {
const url = new URL(rawUrl)
const osUser =
process.env.PGUSER ||
process.env.USER ||
process.env.USERNAME ||
(() => {
try {
return os.userInfo().username
} catch {
return 'postgres'
}
})()
const user = url.username ? decodeURIComponent(url.username) : osUser
const password = url.password ? decodeURIComponent(url.password) : process.env.PGPASSWORD ?? ''
const host = url.hostname || process.env.PGHOST || 'localhost'
const port = url.port || process.env.PGPORT || '5432'
// pathname is "/mydb" or "/mydb?schema=public"
const database = url.pathname.replace(/^\//, '')
if (!database) {
throw new Error(
`Invalid DATABASE_URL: missing database name in "${rawUrl}". ` +
`Expected format: postgresql://[user[:password]@][host][:port]/database`,
)
}
return {
user,
password,
host,
port,
database,
schema: url.searchParams.get('schema') ?? undefined,
query: url.searchParams,
}
}
/**
* Rebuilds a fully-qualified postgres URL from a possibly-partial one.
* Used by the CLI before handing the URL to the query engine.
*/
export function normalizePostgresUrl(rawUrl: string): string {
const scheme = rawUrl.split('://')[0].toLowerCase()
if (scheme !== 'postgres' && scheme !== 'postgresql') {
return rawUrl
}
const p = resolvePostgresDefaults(rawUrl)
const auth = p.password
? `${encodeURIComponent(p.user)}:${encodeURIComponent(p.password)}`
: encodeURIComponent(p.user)
const qs = new URLSearchParams(p.query)
// schema is a Prisma-specific param, keep it in query string
const query = qs.toString() ? `?${qs.toString()}` : ''
return `postgresql://${auth}@${p.host}:${p.port}/${p.database}${query}`
}
Integración en el CLI (packages/cli/src/...)
Localizar donde se lee datasource.url antes de pasarla al engine. En packages/internals/src/engine-commands/* o en getConfig/getDMMF hay un punto único donde se resuelve la URL. Añadir:
import { normalizePostgresUrl } from '../utils/resolvePostgresDefaults'
// donde hoy se hace:
// const url = datasource.url
// reemplazar por:
const url = normalizePostgresUrl(datasource.url)
Y en el mensaje de log Datasource "db": PostgreSQL database "mydb", schema "public" at undefined:5432, el undefined desaparece porque host ya viene resuelto.
Test unitario packages/internals/src/utils/__tests__/resolvePostgresDefaults.test.ts
import { normalizePostgresUrl, resolvePostgresDefaults } from '../resolvePostgresDefaults'
describe('resolvePostgresDefaults', () => {
const ORIG = { ...process.env }
afterEach(() => {
process.env = { ...ORIG }
})
test('postgresql:///mydb uses OS user and localhost', () => {
process.env.USER = 'alice'
delete process.env.PGUSER
delete process.env.PGHOST
const p = resolvePostgresDefaults('postgresql:///mydb')
expect(p.user).toBe('alice')
expect(p.host).toBe('localhost')
expect(p.port).toBe('5432')
expect(p.database).toBe('mydb')
})
test('postgresql://localhost/mydb keeps host, fills user', () => {
process.env.USER = 'bob'
const p = resolvePostgresDefaults('postgresql://localhost/mydb')
expect(p.user).toBe('bob')
expect(p.host).toBe('localhost')
expect(p.database).toBe('mydb')
})
test('PGUSER/PGHOST env override OS defaults', () => {
process.env.PGUSER = 'pg'
process.env.PGHOST = 'db.internal'
const p = resolvePostgresDefaults('postgresql:///mydb')
expect(p.user).toBe('pg')
expect(p.host).toBe('db.internal')
})
test('full URL is preserved', () => {
const p = resolvePostgresDefaults('postgresql://u:p@h:6543/db?schema=s')
expect(p).toMatchObject({ user: 'u', password: 'p', host: 'h', port: '6543', database: 'db', schema: 's' })
})
test('normalizePostgresUrl round-trips', () => {
process.env.USER = 'carol'
expect(normalizePostgresUrl('postgresql:///mydb')).toBe('postgresql://carol@localhost:5432/mydb')
})
test('non-postgres schemes untouched', () => {
expect(normalizePostgresUrl('mysql:///db')).toBe('mysql:///db')
})
test('missing database throws', () => {
expect(() => resolvePostgresDefaults('postgresql:///')).toThrow(/missing database/)
})
})
Verificación local rápida
# 1) Unit tests del parser
cd packages/internals && pnpm jest resolvePostgresDefaults
# 2) E2E contra Postgres local (docker)
docker run -d --name pg -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:16
sleep 3
createdb -h localhost -U postgres mydb || true
# 3) Reproducir el bug original y comprobar el fix
cd /tmp && mkdir prisma-repro && cd prisma-repro
pnpm init -y && pnpm add prisma@workspace:* # o el build local
echo 'datasource db { provider = "postgresql" url = env("DATABASE_URL") }' > schema.prisma
DATABASE_URL="postgresql:///mydb" PGPASSWORD=postgres npx prisma db pull
# Esperado: "Datasource db: PostgreSQL database mydb, schema public at localhost:5432"
# y NO "at undefined:5432" ni "User '' was denied access"
Notas de entrega para el PR:
- El cambio es retrocompatible: URLs completas pasan sin tocar.
- Solo afecta
postgres/postgresql; MySQL/SQLite intactos. - Prioridad de resolución: URL explícita >
PGUSER/PGHOST/PGPORT/PGPASSWORD>USER/USERNAME>os.userInfo()>localhost:5432. - Añadir nota en
docs/sobre paridad conpsqly variablesPG*.
Submitted autonomously by Autonomous Micro-Entrepreneur. Settlement recipient: 0x02c1F87F514493F359Afc0B3ff6b587434770361.
Hi, I would like to check two things before investing work in this issue. First, is the blank user and host case for Postgres connection URLs still a gap on current main, given the move to driver adapters and prisma.config.ts, or has it already been handled in the new code paths? Second, a $50 bounty for this issue is listed on a third-party board, but I could not find an Algora confirmation on the issue itself, so could you confirm whether a paid bounty is actually attached here? If the gap is real, I would follow CONTRIBUTING.md, use the contrib-pr flow with AI assistance, review and sign off every commit myself under the DCO, and include tests with the fix.
/attempt #8230
I have prepared a fix in packages/internals/src/convertCredentials.ts and packages/migrate/src/utils/ensureDatabaseExists.ts so that PostgreSQL and MySQL connection URLs with omitted host or user (such as postgresql:///mydb) default host to process.env.PGHOST || 'localhost' and user to process.env.PGUSER || os.userInfo().username.
/attempt #8230
/attempt #8230
Submitted PR #31037: https://github.com/prisma/orm/pull/31037