Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/runtime/sql.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,8 @@ await query;

You can configure `sql` connection parameters with environment variables. The client checks them in order of precedence and detects the database type from the connection string format.

The connection URL variables (`DATABASE_URL`, `POSTGRES_URL`, `MYSQL_URL`, `SQLITE_URL` and the `TLS_*` variants) are a fallback for when nothing names a target. A connection string, or an options object with `url`, `filename`, `hostname`, `host` or `path`, is used as given and these variables are not consulted.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

### Automatic Database Detection

When you use `Bun.sql()` without arguments, or `new SQL()` with a connection string, Bun detects the adapter from the URL format:
Expand Down
10 changes: 9 additions & 1 deletion src/js/internal/sql/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1639,6 +1639,12 @@ function getConnectionDetailsFromEnvironment(
return [url, sslMode, adapter || null];
}

/** The environment connection URLs only apply when nothing names a target. */
function hasConnectionTarget(options: Bun.SQL.Options): boolean {
const o = options as Record<string, unknown>;
return !!(o.url || o.filename || o.hostname || o.host || o.path);
}

function ensureUrlHasProtocol<T extends string | URL>(
url: T | null,
protocol: string,
Expand Down Expand Up @@ -1683,7 +1689,9 @@ function parseConnectionDetailsFromOptionsOrEnvironment(
options = stringOrUrlOrOptions
? { ...stringOrUrlOrOptions, ...definitelyOptionsButMaybeEmpty }
: definitelyOptionsButMaybeEmpty;
[stringOrUrl, sslMode, adapter] = getConnectionDetailsFromEnvironment(options.adapter);
if (!hasConnectionTarget(options)) {
[stringOrUrl, sslMode, adapter] = getConnectionDetailsFromEnvironment(options.adapter);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
}

// Resolve URL based on adapter type
Expand Down
111 changes: 111 additions & 0 deletions test/js/sql/adapter-env-var-precedence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,117 @@ describe("SQL adapter environment variable precedence", () => {
expect(options.options.username).toBe("postgres");
});

describe("an options object that names a connection target ignores the environment connection strings", () => {
const byUrl = { url: "postgres://appuser:apppw@127.0.0.1:1/appdb", max: 1 };
const byFields = { hostname: "127.0.0.1", port: 1, username: "appuser", password: "apppw", database: "appdb" };

test.each([
["MYSQL_URL", "mysql://x:y@127.0.0.1:9/x"],
["MARIADB_URL", "mariadb://x:y@127.0.0.1:9/x"],
["SQLITE_URL", "sqlite://envfile.db"],
["DATABASE_URL", ":memory:"],
["DATABASE_URL", "mysql://envuser:envpw@envhost:7/envdb"],
["POSTGRES_URL", "postgres://envuser:envpw@envhost:7/envdb"],
])("%s=%s does not pick the adapter or the target", (name, value) => {
process.env[name] = value;

for (const options of [byUrl, byFields]) {
const sql = new SQL(options);
expect(sql.options).toMatchObject({ adapter: "postgres", hostname: "127.0.0.1", port: 1, username: "appuser" });
expect(sql.options.database).toBe("appdb");
expect(sql.options.filename).toBeUndefined();
}
});

test("the explicit URL scheme picks the adapter", () => {
process.env.POSTGRES_URL = "postgres://x:y@127.0.0.1:9/x";

const sql = new SQL({ url: "mysql://appuser:apppw@127.0.0.1:1/appdb" });
expect(sql.options).toMatchObject({ adapter: "mysql", hostname: "127.0.0.1", port: 1, username: "appuser" });
});

test.each(["TLS_DATABASE_URL", "TLS_POSTGRES_DATABASE_URL"])("%s does not force sslmode=require", name => {
process.env[name] = "postgres://x:y@127.0.0.1:9/x";

expect(new SQL(byUrl).options.sslMode).toBe(0);
expect(new SQL(byFields).options.sslMode).toBe(0);
});

test("a URL copied from TLS_DATABASE_URL into options.url is an explicit URL: its own ?sslmode= applies", () => {
process.env.TLS_DATABASE_URL = "postgres://x:y@127.0.0.1:9/x?sslmode=require";

expect(new SQL({ url: process.env.TLS_DATABASE_URL }).options.sslMode).toBe(2);
process.env.TLS_DATABASE_URL = "postgres://x:y@127.0.0.1:9/x";
expect(new SQL({ url: process.env.TLS_DATABASE_URL }).options.sslMode).toBe(0);
});

test("a filename is a connection target", () => {
process.env.DATABASE_URL = "postgres://x:y@127.0.0.1:9/x";

const sql = new SQL({ filename: ":memory:" });
expect(sql.options.adapter).toBe("sqlite");
expect(sql.options.filename).toBe(":memory:");
});
Comment thread
robobun marked this conversation as resolved.
Resolved

test("the host option alias is a connection target", () => {
process.env.DATABASE_URL = ":memory:";

const sql = new SQL({ host: "127.0.0.1", port: 1 });
expect(sql.options).toMatchObject({ adapter: "postgres", hostname: "127.0.0.1", port: 1 });
});

test.each(["DATABASE_URL", "POSTGRES_URL"])("credentials in %s do not go to a host named in the options", name => {
process.env[name] = "postgres://envuser:ENVSECRET@10.9.9.9:7/envdb";
process.env.USER = "shelluser";
delete process.env.PASSWORD;

const noCreds = new SQL({ hostname: "127.0.0.1", port: 1 });
expect(noCreds.options).toMatchObject({
adapter: "postgres",
hostname: "127.0.0.1",
port: 1,
username: "shelluser",
password: "",
database: "shelluser",
});

const withUser = new SQL({ hostname: "127.0.0.1", port: 1, username: "optuser" });
expect(withUser.options).toMatchObject({ username: "optuser", password: "", database: "optuser" });

// The host-agnostic per-field variables still fill in what is missing.
process.env.PGPASSWORD = "pgpw";
process.env.PGDATABASE = "pgdb";
const withPgVars = new SQL({ hostname: "127.0.0.1", port: 1, username: "optuser" });
expect(withPgVars.options).toMatchObject({ username: "optuser", password: "pgpw", database: "pgdb" });
});

test("a unix socket path is a connection target", () => {
process.env.SQLITE_URL = "sqlite://envfile.db";

const sql = new SQL({ path: "/var/run/postgresql", database: "appdb" });
expect(sql.options).toMatchObject({ adapter: "postgres", database: "appdb" });
expect(sql.options.filename).toBeUndefined();
});

test.each([{ max: 1, username: "appuser" }, { port: 9 }])(
"an options object without a target (%p) still falls back to the environment",
options => {
process.env.MYSQL_URL = "mysql://envuser:envpw@envhost:7/envdb";

const sql = new SQL(options);
expect(sql.options).toMatchObject({ adapter: "mysql", hostname: "envhost", port: options.port ?? 7 });
},
);

test("an explicit adapter without a target still reads that adapter's environment URL", () => {
process.env.MYSQL_URL = "mysql://envuser:envpw@envhost:7/envdb";
process.env.POSTGRES_URL = "postgres://pguser:pgpw@pghost:5/pgdb";

expect(new SQL({ adapter: "mysql" }).options).toMatchObject({ adapter: "mysql", hostname: "envhost", port: 7 });
expect(new SQL({ adapter: "postgres" }).options).toMatchObject({ adapter: "postgres", hostname: "pghost" });
});
});

test("should only read PostgreSQL env vars when adapter is postgres", () => {
process.env.PGHOST = "pg-host";
process.env.PGUSER = "pg-user";
Expand Down