type

SQL.Options

type Options = SQLiteOptions | PostgresOrMySQLOptions

Configuration options for SQL client connection and behavior

const config: Bun.SQL.Options = {
  hostname: 'localhost',
  port: 5432,
  username: 'dbuser',
  password: 'secretpass',
  database: 'myapp',
  idleTimeout: 30,
  max: 20,
  onconnect: (err) => {
    if (!err) console.log('Connected to database');
  }
};

Referenced types

interface SQLiteOptions

Options for Database

  • adapter?: 'sqlite'

    Selects the SQLite adapter. Optional when filename is set, because a filename selects SQLite too.

  • bigint?: boolean

    Return every integer as a BigInt. The same as safeIntegers, under the name that the other adapters use. safeIntegers takes priority.

  • create?: boolean

    Allow creating a new database

    Equivalent to constants.SQLITE_OPEN_CREATE

    When false, opening a file that does not exist throws an error with the code SQLITE_CANTOPEN.

  • filename?: URL | string & {} | ':memory:'

    Path to the database file

    Examples:

    • sqlite://:memory:
    • sqlite://./path/to/database.db
    • sqlite:///Users/bun/projects/my-app/database.db
    • ./dev.db
    • :memory:

    Everything from the first ? is a query string, which can have mode=: ro (read-only), rw (read-write, the file must exist) or rwc (read-write and create, the default). memory has no effect, and any other mode throws. The readonly and create options take priority over it, and a read-only database ignores create and readwrite.

    Without a filename, Bun reads a DATABASE_URL that is not a PostgreSQL, MySQL or MariaDB URL, then SQLITE_URL.

  • onclose?: (err: null | Error) => void

    SQLite: called when SQL.close closes the database. Receives an Error with the message "Connection closed", not null.

  • onconnect?: (err: null | Error) => void

    SQLite: called once, when Bun has tried to open the database. Receives null, or the Error that kept it from opening (for example SQLITE_CANTOPEN).

  • readonly?: boolean

    Open the database as read-only (no write operations, no create).

    Equivalent to constants.SQLITE_OPEN_READONLY

    Together with create: true or readwrite: true, the constructor throws a TypeError.

  • readwrite?: boolean

    Open the database as read-write

    Equivalent to constants.SQLITE_OPEN_READWRITE

    readwrite: true without create: true does not create the file. readwrite: false is the same as readonly: true.

  • safeIntegers?: boolean

    When true, integers are returned as bigint.

    When false, integers are returned as number, and integers beyond 53 bits are rounded to the nearest number.

    When true, a bigint parameter that does not fit in a signed 64-bit integer throws a RangeError. When false, it keeps its low 64 bits: 2n ** 64n - 1n is stored as -1.

  • strict?: boolean

    When set to true, a query with a missing bound parameter throws an error. When set to false or undefined, the parameter is NULL.

    In both modes, the key of a named parameter can include the $, :, or @ prefix or leave it out. If an object has both keys, the key without the prefix wins in strict mode, and the key with the prefix otherwise.

    const db = new Database(":memory:", { strict: true });
    db.run("INSERT INTO foo (name) VALUES ($name)", { name: "foo" });
    db.run("INSERT INTO foo (name) VALUES ($name)", { nmae: "foo" }); // throws
  • transform?: Transform | NameTransform

    Renames columns between the database and JavaScript, for example SQL.camel

  • url?: string | URL

    The same as filename, which takes priority. Needs adapter: "sqlite" unless the value is a sqlite: or file: URL.

interface PostgresOrMySQLOptions

  • adapter?: 'postgres' | 'mysql' | 'mariadb'

    Database adapter/driver to use. Takes priority over the protocol of the URL. "mariadb" uses the MySQL driver and reads the MARIADB_* environment variables instead of MYSQL_*.

  • allowPublicKeyRetrieval?: boolean

    MySQL only. Allow the client to request the server's RSA public key during caching_sha2_password / sha256_password authentication when the connection is not protected by TLS. Disabled by default because a network attacker can substitute their own key and recover the plaintext password. Enable only for trusted local connections, or use TLS instead. Not needed over TLS, where Bun sends the password directly. caching_sha2_password does not need it over a unix socket either. sha256_password does.

  • bigint?: boolean

    Return large integers as BigInt. By default they are returned as strings.

    PostgreSQL: every int8, whatever its value. MySQL: BIGINT values outside the 32-bit range, and a lastInsertRowid above Number.MAX_SAFE_INTEGER.

  • channelBinding?: 'require' | 'disable' | 'prefer'

    PostgreSQL only. Whether a SCRAM login over TLS is tied to the server's certificate (SCRAM-SHA-256-PLUS), so that someone who terminates TLS between the client and the server cannot pass the login on.

    • "prefer": binds the login when the connection uses TLS and the server offers it
    • "require": only accepts a bound login. Otherwise the connection fails with ERR_POSTGRES_CHANNEL_BINDING_REQUIRED: without TLS, and when the server asks for an MD5 password, a clear text password, or none.
    • "disable": never binds the login

    Also the ?channel_binding= parameter of the URL, and the PGCHANNELBINDING environment variable.

    On MySQL and MariaDB, "require" throws when the client is created, and the other values have no effect.

  • connection?: Record<string, string | number | boolean>

    PostgreSQL only. Runtime configuration parameters that Bun sends when it opens a connection, for example { application_name: "api", search_path: "app" }.

  • connectionTimeout?: number

    Maximum time in seconds to wait when establishing a connection. Does not limit how long a query runs.

  • database?: string

    Name of the database to connect to. PGDATABASE, MYSQL_DATABASE and MARIADB_DATABASE take priority over the database in a URL.

  • foundRows?: boolean

    MySQL and MariaDB only. Report the rows that the WHERE clause of an UPDATE matched in affectedRows, as mysql2, the mariadb connector, PostgreSQL and SQLite do. Without it, the server counts only the rows whose values changed, so an UPDATE that sets a row to the values it already has reports 0. Also the ?foundRows= parameter of the URL.

  • hostname?: string

    Database server hostname. For PostgreSQL, a value that starts with / is the directory of a unix socket.

  • idleTimeout?: number

    Maximum time in seconds a connection can sit idle before it is closed. A connection that runs a query, is reserved, or has an open transaction is not idle.

  • max?: number

    Maximum number of connections in the pool

  • maxLifetime?: number

    Maximum lifetime in seconds of a connection. A connection that is busy at that moment finishes its queries, its transaction or its reservation first. It takes no new queries, and then closes.

  • onclose?: (err: null | Error) => void

    PostgreSQL and MySQL: called once for each connection that closes or fails to connect, with the Error that says why. It is never null: after SQL.close the code is ERR_POSTGRES_CONNECTION_CLOSED or ERR_MYSQL_CONNECTION_CLOSED. A failed attempt passes its own error, for example ERR_POSTGRES_CONNECTION_REFUSED.

  • onconnect?: (err: null | Error) => void

    PostgreSQL and MySQL: called once for each connection that opens, always with null. Bun reports a failed connection attempt to onclose, not here.

  • password?: string | () => MaybePromise<string>

    Database password for authentication

  • path?: string

    Unix domain socket to connect through instead of TCP to hostname:port. For PostgreSQL, a directory resolves to <path>/.s.PGSQL.<port>. A path that does not exist fails the connection. Also the ?path= parameter of the URL.

  • port?: string | number

    Database server port number

  • prepare?: boolean

    PostgreSQL only. Use named prepared statements. Each connection keeps the 1,024 it used last. false throws for MySQL and does nothing for MariaDB.

  • socket?: string

    Unix domain socket to connect through (alias for path). Also the ?socket= parameter of the URL.

  • tls?: boolean | 'allow' | BunFile | 'require' | 'disable' | TLSOptions | 'prefer' | 'verify-ca' | 'verify-full'

    Whether to use TLS/SSL for the connection. A string selects the SSL mode ("disable", "allow", "prefer", "require", "verify-ca", "verify-full"). A BunFile is the CA certificate to verify the server against, the same as { ca: Bun.file(path) }, and selects "verify-full".

    true and an options object ask for at least "require". An object with ca, caFile, checkServerIdentity or rejectUnauthorized: true raises a mode below "verify-ca" to "verify-full". Without rejectUnauthorized, NODE_TLS_REJECT_UNAUTHORIZED=0 turns certificate verification off in every mode. PostgreSQL ignores this option on a unix socket.

    A URL that Bun reads from a TLS_* environment variable uses "require" unless the URL or this option names a mode.

    const sql = new SQL(url, { tls: Bun.file("./rds-ca-bundle.pem") });
  • transform?: Transform | NameTransform

    Renames columns between the database and JavaScript, for example SQL.camel

  • url?: string | URL

    Connection URL, for example postgres://user:pass@localhost:5432/mydb.

    For each setting, an option takes priority over the URL, and the URL over the environment. Without url and without a connection string, Bun reads a URL from the environment, such as DATABASE_URL, and the other options change single fields of it.

    With adapter, a DATABASE_URL that names another adapter's server is not used, except for the TLS mode it asks for when no other URL applies.

  • username?: string

    Database user for authentication