namespace

SQL

namespace SQL

    • cause?: unknown

      The cause of the error.

    • readonly code: string

      Bun's error code, such as "ERR_MYSQL_SERVER_ERROR" or "ERR_MYSQL_CONNECTION_CLOSED". It is not a name like ER_DUP_ENTRY: compare errno for that.

    • readonly errno?: number

      The error number that the server sent, such as 1062 for a duplicate entry. Not set on errors that Bun raises itself.

    • message: string
    • name: string
    • readonly sqlState?: string

      The SQLSTATE that the server sent, such as "23000"

    • stack?: string
    • static stackTraceLimit: number

      The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

      The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

      If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

    • targetObject: object,
      constructorOpt?: Function
      ): void;

      Create .stack property on a target object

    • static isError(
      value: unknown
      ): value is Error;

      Check if a value is an instance of Error

      @param value

      The value to check

      @returns

      True if the value is an instance of Error, false otherwise

    • err: Error,
      stackTraces: CallSite[]
      ): any;
    • cause?: unknown

      The cause of the error.

    • readonly code: string

      Bun's error code, such as "ERR_POSTGRES_SERVER_ERROR" or "ERR_POSTGRES_CONNECTION_CLOSED". The server's own code is in errno.

    • readonly column?: string
    • readonly constraint?: string
    • readonly dataType?: string
    • readonly detail?: string
    • readonly errno?: string

      The SQLSTATE that the server sent, such as "23505" for a unique violation. Not set on errors that Bun raises itself.

    • readonly file?: string
    • readonly hint?: string
    • readonly internalPosition?: string
    • readonly internalQuery?: string
    • readonly line?: string
    • message: string
    • name: string
    • readonly position?: string
    • readonly routine?: string
    • readonly schema?: string
    • readonly severity?: string
    • stack?: string
    • readonly table?: string
    • readonly where?: string
    • static stackTraceLimit: number

      The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

      The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

      If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

    • targetObject: object,
      constructorOpt?: Function
      ): void;

      Create .stack property on a target object

    • static isError(
      value: unknown
      ): value is Error;

      Check if a value is an instance of Error

      @param value

      The value to check

      @returns

      True if the value is an instance of Error, false otherwise

    • err: Error,
      stackTraces: CallSite[]
      ): any;
  • class SQLError

    • cause?: unknown

      The cause of the error.

    • message: string
    • name: string
    • stack?: string
    • static stackTraceLimit: number

      The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

      The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

      If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

    • targetObject: object,
      constructorOpt?: Function
      ): void;

      Create .stack property on a target object

    • static isError(
      value: unknown
      ): value is Error;

      Check if a value is an instance of Error

      @param value

      The value to check

      @returns

      True if the value is an instance of Error, false otherwise

    • err: Error,
      stackTraces: CallSite[]
      ): any;
    • readonly byteOffset?: number

      The UTF-8 byte offset of the token that the error refers to, counted from the start of the query text. -1 if the error refers to no token. Not set on errors that Bun raises itself.

    • cause?: unknown

      The cause of the error.

    • readonly code: string

      SQLite's extended result code, such as "SQLITE_CONSTRAINT_UNIQUE", or one of Bun's own codes, such as "ERR_SQLITE_CONNECTION_CLOSED"

    • readonly errno: number

      The number of the extended result code, such as 2067. errno & 0xff is the primary code. 0 on errors that Bun raises itself.

    • message: string
    • name: string
    • stack?: string
    • static stackTraceLimit: number

      The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

      The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

      If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

    • targetObject: object,
      constructorOpt?: Function
      ): void;

      Create .stack property on a target object

    • static isError(
      value: unknown
      ): value is Error;

      Check if a value is an instance of Error

      @param value

      The value to check

      @returns

      True if the value is an instance of Error, false otherwise

    • err: Error,
      stackTraces: CallSite[]
      ): any;
  • interface ColumnTransform

    The two directions of Transform.column

    • from?: (name: string) => string

      Renames a column that comes from the database: the keys of the row objects, and name in ResultMetadata.columns.

      Bun calls it once for each column of a statement, not once for each row, so it must return the same name every time.

    • to?: (name: string) => string

      Renames a name that goes to the database: the keys of sql(object), the columns picked in sql(object, "a", "b"), and every sql("name"), table names included.

  • interface Helper<T>

    A parameter or serializable value interpolated into a query.

    const helper = sql(users, 'id');
    await sql`insert into users ${helper}`;
  • interface ListenSubscription

    One registration made by SQL.listen.

    • readonly channel: string
    • [Symbol.asyncDispose](): PromiseLike<void>;
    • unlisten(): Promise<void>;

      Remove this registration. Resolves once the channel is no longer subscribed, or immediately when other registrations on it remain. Idempotent; await using calls it at the end of the scope.

  • interface NameTransform

    One of SQL.toCamel, SQL.fromCamel and the like. Call it to convert a name, or pass it as the transform option to rename in one direction.

  • 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

  • interface Query<T>

    A pending SQL query. Extends Promise, so it can be awaited, and adds methods to control how it runs. The array it resolves to also has ResultMetadata.

    A query is lazy. It starts in the call to then(), catch(), finally() or execute, and await calls then().

    What then() and catch() return is a promise like any other: when it rejects with nothing to handle the rejection, that is reported as an unhandled rejection. So is an error that a finally() callback throws.

    The failure of a query that was only started, with execute() or finally(), is not reported once it has a connection, nor when close({ timeout: 0 }) closes the pool while it waits for one, when it was cancelled before it started, or when its reservation, transaction or savepoint has ended. After execute(), a failure to connect, a pool that was already closed, a cancel() or the end of the time of close({ timeout }), with a timeout above 0, while it waits for a connection, and a query that cannot be built are reported. So is the failure of a query that SQLite runs outside a transaction.

    Bun reads the parameters when it sends the query. Leave a Buffer, TypedArray, Date or object that you passed alone until the query settles.

    • readonly [Symbol.toStringTag]: string
    • active: boolean

      True while a connection runs the query

    • cancelled: boolean

      True after cancel was called

    • cancel(): Query<T>;

      Cancels the query.

      A query that Bun has not sent yet never runs. It rejects with ERR_POSTGRES_QUERY_CANCELLED (or the MYSQL / SQLITE code).

      PostgreSQL: Bun asks the server to stop a running query, on a second connection. The query rejects with the server's error, errno "57014", or resolves if it ends first. A query that Bun sent behind another one, or that has another one sent behind it, rejects with ERR_POSTGRES_QUERY_CANCELLED and a hint, because the server may still run it.

      MySQL: a query that Bun has sent runs to the end and settles with its result.

    • catch<TResult = never>(
      onrejected?: null | (reason: any) => TResult | PromiseLike<TResult>
      ): Promise<T & ResultMetadata | TResult>;

      Attaches a callback for only the rejection of the Promise.

      @param onrejected

      The callback to execute when the Promise is rejected.

      @returns

      A Promise for the completion of the callback.

    • execute(): Query<T>;

      Starts executing the query. Queries are lazy: they only run when awaited or executed with this method.

    • onfinally?: null | () => void
      ): Promise<T & ResultMetadata>;

      Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.

      @param onfinally

      The callback to execute when the Promise is settled (fulfilled or rejected).

      @returns

      A Promise for the completion of the callback.

    • raw(): Query<T>;

      Returns rows as arrays of Buffer objects instead of objects.

      PostgreSQL and MySQL: the bytes the server sent. On PostgreSQL a prepared query gets bool, int4, float4, float8, numeric, bytea, time, timestamp, timestamptz, int4[] and float4[] in binary and every other type as text; all types are text on the first run of a query without parameters, with .simple() and with prepare: false. On MySQL a prepared query is binary. SQLite: Uint8Array objects.

      Call it before the query starts. After that, SQLite ignores it, and on PostgreSQL some types can arrive in the other format.

    • PostgreSQL only. Starts a COPY ... TO STDOUT query and returns the bytes that the server sends, in the format that the statement names. A chunk can end in the middle of a row.

      Call it before the query starts. The query takes no parameters, and resolves with the row count in count when the server has finished. A failure reaches the stream, so the query needs no handler of its own.

      await Bun.write("users.csv", new Response(sql`COPY users TO STDOUT (FORMAT csv)`.readable()));
    • simple(): Query<T>;

      Executes the query as a simple query. Parameters are not allowed, but the query can contain multiple commands separated by semicolons.

    • then<TResult1 = T & ResultMetadata, TResult2 = never>(
      onfulfilled?: null | (value: T & ResultMetadata) => TResult1 | PromiseLike<TResult1>,
      onrejected?: null | (reason: any) => TResult2 | PromiseLike<TResult2>
      ): Promise<TResult1 | TResult2>;

      Attaches callbacks for the resolution and/or rejection of the Promise.

      @param onfulfilled

      The callback to execute when the Promise is resolved.

      @param onrejected

      The callback to execute when the Promise is rejected.

      @returns

      A Promise for the completion of which ever callback is executed.

    • values(): Query<T>;

      Returns each row as an array of values, in the same order as the columns in the query.

      It has no effect after execute() on SQLite, which has run the query.

    • writable(): WritableStream<string | ArrayBufferLike | TypedArray<ArrayBufferLike> | DataView<ArrayBufferLike>>;

      PostgreSQL only. Starts a COPY ... FROM STDIN query and returns a stream that takes the bytes for the server, in the format that the statement names.

      close() resolves when the server has stored the rows, and rejects with the server's error. abort() stores nothing. The connection runs nothing else until then, so always close or abort the stream. Bun aborts a stream that is still open when its transaction, savepoint or reservation ends.

      Call it before the query starts. The query takes no parameters, and resolves with the row count in count.

      await Bun.file("users.csv").stream().pipeTo(sql`COPY users FROM STDIN (FORMAT csv)`.writable());
  • interface ResultColumn

    A column of a PostgreSQL or MySQL result, as the server described it

    const result = await sql`SELECT id, data FROM posts`;
    console.log(result.columns);
    // PostgreSQL:
    // [
    //   { name: "id", type: 23, table: 16388, number: 1 }, // int4
    //   { name: "data", type: 3802, table: 16388, number: 2 }, // jsonb
    // ]
    • flags?: number

      MySQL only. The flags of the column, as the server sent them

    • length?: number

      MySQL only. The length of the column, as the server sent it

    • name: string

      The name of the column in the result

    • number?: number

      PostgreSQL only. The number of the column in its table, from 1. 0 for an expression, negative for a system column such as ctid.

    • table: string | number

      The table that the column comes from.

      • PostgreSQL: the OID of the table. 0 for an expression.
      • MySQL: the name of the table, or its alias in the query. "" for an expression.
    • type: number

      The type of the column.

      • PostgreSQL: the OID of the type, such as 23 for int4, 25 for text, 1009 for text[], 3802 for jsonb
      • MySQL: the type code of the protocol, such as 3 for INT, 8 for BIGINT, 253 for VARCHAR, 245 for JSON
  • interface ResultMetadata

    Properties of the array that a query resolves to, next to the rows. They are accessors on the prototype, not own properties, so console.log, Object.keys, JSON.stringify and spreading only see the rows.

    A query with several statements (.simple(), a MySQL CALL) resolves to a plain array of results. The metadata is on each inner array.

    • affectedRows: number

      The number of rows that an INSERT, UPDATE, DELETE or MERGE wrote. 0 for a statement that writes nothing.

      PostgreSQL tags CREATE TABLE AS, and a SELECT whose CTE writes, as SELECT, so it is 0 for them. MariaDB reports INSERT ... RETURNING as a result set, so it is 0 there too.

    • columns: null | ResultColumn[]

      The columns of the result, also when it has no rows and with .values() or .raw(). Empty for a statement that returns no rows, such as a plain INSERT. null on SQLite.

    • command: null | string

      The kind of statement. PostgreSQL: the command tag, such as "INSERT" or "CREATE TABLE". SQLite: the first keyword. MySQL: null, because the protocol does not report it.

    • count: number

      The number of rows returned, or the number of rows written when the statement returns none

    • lastInsertRowid: null | string | number | bigint

      The key that an INSERT generated.

      • PostgreSQL: null. Use RETURNING.
      • MySQL: the first AUTO_INCREMENT value of the statement, 0 if there is none. Above Number.MAX_SAFE_INTEGER it is a string, or a BigInt with bigint: true.
      • SQLite: the rowid of the last inserted row, also after a statement that inserts nothing. null for a statement that only reads. A BigInt with safeIntegers: true or bigint: true.
    • statement: null | ResultStatement

      The text, the parameter types and the columns of the statement. null on SQLite.

  • interface ResultStatement

    The statement that produced a PostgreSQL or MySQL result.

    The runs of one prepared statement on one connection share one object. Treat it as read-only.

    • columns: ResultColumn[]

      The same array as ResultMetadata.columns

    • string: string

      The text that Bun sent, with $1 or ? for each parameter

    • types: number[]

      The types of the parameters, as the server reported them: OIDs on PostgreSQL, type codes on MySQL. MariaDB does not type parameters, so each one is 6. Empty for a query without parameters.

  • 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 TLSOptions

    TLS options of a PostgreSQL or MySQL connection

    • ca?: string | BunFile | BufferSource | unknown[]

      Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option.

      On a server these verify client certificates, which it requests only with requestCert: true.

    • cert?: string | BunFile | BufferSource | unknown[]

      Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private key, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see ca). When providing multiple cert chains, they do not have to be in the same order as their private keys in key. If the intermediate certificates are not provided, the peer cannot validate the certificate, and the handshake fails.

    • checkServerIdentity?: (hostname: string, cert: PeerCertificate) => undefined | Error

      Replaces the built-in check of the host name against the server's certificate, as in node:tls. To keep that check, call checkServerIdentity() from node:tls inside the function.

      Bun calls it once for each connection, after the certificate chain verified and before it sends the user name or the password. Like ca, it raises an SSL mode below "verify-ca" to "verify-full". Bun does not call it with rejectUnauthorized: false.

      const sql = new SQL(url, {
        tls: {
          ca: Bun.file("./ca.pem"),
          checkServerIdentity: (hostname, cert) =>
            cert.fingerprint256 === pin ? undefined : new Error("certificate pin mismatch"),
        },
      });
    • ciphers?: string
    • crl?: string | BunFile | BufferSource | unknown[]

      PEM formatted CRLs (Certificate Revocation Lists). A peer certificate listed in one of them fails verification: a client certificate when a server sets requestCert, or the server certificate when connecting.

    • dhParamsFile?: string

      File path to a .pem file containing custom Diffie-Hellman parameters

    • key?: string | BunFile | BufferSource | unknown[]

      Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys are decrypted with options.passphrase. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form {pem: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array. object.passphrase is optional. Encrypted keys are decrypted with object.passphrase if provided, or options.passphrase if it is not.

    • lowMemoryMode?: boolean

      Sets OPENSSL_RELEASE_BUFFERS to 1. Reduces overall performance but saves some memory.

    • passphrase?: string

      Passphrase for the TLS key

    • rejectUnauthorized?: boolean

      If set to false, any certificate is accepted.

      For a server, the default is true. $NODE_TLS_REJECT_UNAUTHORIZED does not change it. For a client, the default is the $NODE_TLS_REJECT_UNAUTHORIZED environment variable, or true if it is not set.

    • requestCert?: boolean

      If set to true, the server requests a client certificate, and refuses a client without a valid one unless rejectUnauthorized is false. This option alone decides it: ca does not request a certificate.

      Default is false.

    • secureOptions?: number

      Optionally affect the OpenSSL protocol behavior, which is not usually necessary. Use it carefully, if at all. Value is a numeric bitmask of the SSL_OP_* options from OpenSSL Options

    • servername?: string

      Alias of serverName, the node:tls spelling. serverName wins if both are set.

    • serverName?: string

      Explicitly set a server name

  • interface Transform

    The transform option

    const sql = new SQL({ transform: SQL.camel });
    await sql`INSERT INTO users ${sql({ firstName: "Alice" })}`; // "first_name"
    const [user] = await sql`SELECT first_name FROM users`;
    console.log(user.firstName);
    • column?: ColumnTransform | (name: string) => string

      Renames columns. A function means ColumnTransform.from.

    • undefined?: unknown

      The value that Bun sends for an undefined parameter. When it is set (null counts), the insert and update helpers leave no column out. Without it, undefined is NULL, and the helpers leave out a column that is undefined.

  • type AwaitPromisesArray<T extends PromiseLike<any>[]> = { [K in keyof T]: Awaited<T[K]> }
  • type ContextCallback<T, SQL> = (sql: SQL) => Bun.MaybePromise<T>
  • type ContextCallbackResult<T> = T extends PromiseLike<any>[] ? AwaitPromisesArray<T> : Awaited<T>
  • 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');
      }
    };
  • type SavepointContextCallback<T> = ContextCallback<T, SavepointSQL>

    Callback function type for savepoint contexts

  • type TransactionContextCallback<T> = ContextCallback<T, TransactionSQL>

    Callback function type for transaction contexts

  • const camel: { column: Required<ColumnTransform> }

    transform preset: user_id in the database, userId in JavaScript

  • const fromCamel: NameTransform

    "userId" to "user_id". As transform, renames the names in sql() helpers only.

  • const fromKebab: NameTransform

    "user-id" to "user_id". As transform, renames the names in sql() helpers only.

  • const fromPascal: NameTransform

    "UserId" to "user_id". As transform, renames the names in sql() helpers only.

  • const kebab: { column: Required<ColumnTransform> }

    transform preset: user_id in the database, user-id in JavaScript

  • const pascal: { column: Required<ColumnTransform> }

    transform preset: user_id in the database, UserId in JavaScript

  • const toCamel: NameTransform

    "user_id" to "userId". As transform, renames the columns of results only.

  • const toKebab: NameTransform

    "user_id" to "user-id". As transform, renames the columns of results only.

  • const toPascal: NameTransform

    "user_id" to "UserId". As transform, renames the columns of results only.