method

TransactionSQL.connect

connect(): Promise<SQL>;

Waits for the database connection to be established

await sql.connect();

Referenced types

namespace SQL

    • cause?: unknown

      The cause of the error.

    • readonly code: string
    • readonly errno?: number
    • message: string
    • name: string
    • readonly sqlState?: 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;
    • cause?: unknown

      The cause of the error.

    • readonly code: string
    • readonly column?: string
    • readonly constraint?: string
    • readonly dataType?: string
    • readonly detail?: string
    • readonly errno?: string
    • 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
    • cause?: unknown

      The cause of the error.

    • readonly code: string
    • readonly errno: number
    • 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 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 PostgresOrMySQLOptions

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

      Database adapter/driver to use

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

    • bigint?: boolean

      Return values outside the i32 range as BigInt. By default they are returned as strings.

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

      Postgres client runtime configuration options

    • connectionTimeout?: number

      Maximum time in seconds to wait when establishing a connection

    • database?: string

      Name of the database to connect to

    • hostname?: string

      Database server hostname

    • idleTimeout?: number

      Maximum time in seconds a connection can sit idle before it is closed

    • max?: number

      Maximum number of connections in the pool

    • maxLifetime?: number

      Maximum lifetime in seconds of a connection

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

      Called when a connection is closed. Receives the closing Error, or null.

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

      Called when a connection attempt completes. Receives an Error on failure, or null on success.

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

      Database password for authentication

    • path?: string

      Unix domain socket path for connection

    • port?: string | number

      Database server port number

    • prepare?: boolean

      Automatic creation of prepared statements

    • tls?: boolean | BunFile | 'require' | TLSOptions | 'disable' | 'allow' | '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").

    • url?: string | URL

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

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

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

      True while the query is executing

    • cancelled: boolean

      True if the query has been cancelled

    • cancel(): Query<T>;

      Cancels the executing query

    • catch<TResult = never>(
      onrejected?: null | (reason: any) => TResult | PromiseLike<TResult>
      ): Promise<T | 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>;

      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

    • 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, TResult2 = never>(
      onfulfilled?: null | (value: T) => 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

  • interface SQLiteOptions

    Options for Database

    • adapter?: 'sqlite'
    • create?: boolean

      Allow creating a new database

      Equivalent to constants.SQLITE_OPEN_CREATE

    • 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:
    • onclose?: (err: null | Error) => void

      Called when a connection is closed. Receives the closing Error, or null.

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

      Called when a connection attempt completes. Receives an Error on failure, or null on success.

    • readonly?: boolean

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

      Equivalent to constants.SQLITE_OPEN_READONLY

    • readwrite?: boolean

      Open the database as read-write

      Equivalent to constants.SQLITE_OPEN_READWRITE

    • safeIntegers?: boolean

      When true, integers are returned as bigint.

      When false, integers are returned as number and truncated to 52 bits.

    • strict?: boolean

      When set to false or undefined:

      • Queries missing bound parameters do NOT throw an error
      • Bound named parameters in JavaScript need to exactly match the SQL query.
      const db = new Database(":memory:", { strict: false });
      db.run("INSERT INTO foo (name) VALUES ($name)", { $name: "foo" });

      When set to true:

      • Queries missing bound parameters throw an error
      • Bound named parameters in JavaScript no longer need the $, :, or @ prefix. The SQL query keeps its prefix.
  • 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 = {
      host: 'localhost',
      port: 5432,
      user: '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