Mconnect
Bun

method

SavepointSQL.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: undefined | number
    • message: string
    • name: string
    • readonly sqlState: undefined | string
    • stack?: string
    • static stackTraceLimit: number

      The maximum number of stack frames to capture.

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

      Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

      const myObject = {};
      Error.captureStackTrace(myObject);
      myObject.stack;  // Similar to `new Error().stack`
      

      The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

      The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

      The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

      function a() {
        b();
      }
      
      function b() {
        c();
      }
      
      function c() {
        // Create an error without stack trace to avoid calculating the stack trace twice.
        const { stackTraceLimit } = Error;
        Error.stackTraceLimit = 0;
        const error = new Error();
        Error.stackTraceLimit = stackTraceLimit;
      
        // Capture the stack trace above function b
        Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
        throw error;
      }
      
      a();
      
    • 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: undefined | string
    • readonly constraint: undefined | string
    • readonly dataType: undefined | string
    • readonly detail: undefined | string
    • readonly errno: undefined | string
    • readonly file: undefined | string
    • readonly hint: undefined | string
    • readonly internalPosition: undefined | string
    • readonly internalQuery: undefined | string
    • readonly line: undefined | string
    • message: string
    • name: string
    • readonly position: undefined | string
    • readonly routine: undefined | string
    • readonly schema: undefined | string
    • readonly severity: undefined | string
    • stack?: string
    • readonly table: undefined | string
    • readonly where: undefined | string
    • static stackTraceLimit: number

      The maximum number of stack frames to capture.

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

      Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

      const myObject = {};
      Error.captureStackTrace(myObject);
      myObject.stack;  // Similar to `new Error().stack`
      

      The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

      The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

      The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

      function a() {
        b();
      }
      
      function b() {
        c();
      }
      
      function c() {
        // Create an error without stack trace to avoid calculating the stack trace twice.
        const { stackTraceLimit } = Error;
        Error.stackTraceLimit = 0;
        const error = new Error();
        Error.stackTraceLimit = stackTraceLimit;
      
        // Capture the stack trace above function b
        Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
        throw error;
      }
      
      a();
      
    • 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 maximum number of stack frames to capture.

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

      Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

      const myObject = {};
      Error.captureStackTrace(myObject);
      myObject.stack;  // Similar to `new Error().stack`
      

      The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

      The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

      The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

      function a() {
        b();
      }
      
      function b() {
        c();
      }
      
      function c() {
        // Create an error without stack trace to avoid calculating the stack trace twice.
        const { stackTraceLimit } = Error;
        Error.stackTraceLimit = 0;
        const error = new Error();
        Error.stackTraceLimit = stackTraceLimit;
      
        // Capture the stack trace above function b
        Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
        throw error;
      }
      
      a();
      
    • 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 maximum number of stack frames to capture.

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

      Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

      const myObject = {};
      Error.captureStackTrace(myObject);
      myObject.stack;  // Similar to `new Error().stack`
      

      The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

      The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

      The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

      function a() {
        b();
      }
      
      function b() {
        c();
      }
      
      function c() {
        // Create an error without stack trace to avoid calculating the stack trace twice.
        const { stackTraceLimit } = Error;
        Error.stackTraceLimit = 0;
        const error = new Error();
        Error.stackTraceLimit = stackTraceLimit;
      
        // Capture the stack trace above function b
        Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
        throw error;
      }
      
      a();
      
    • 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>

    SQL.Helper represents a parameter or serializable value inside of a query.

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

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

      Database adapter/driver to use

    • bigint?: boolean

      By default values outside i32 range are returned as strings. If this is true, values outside i32 range are returned as BigInts.

    • 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

    • host?: string

      Database server hostname

    • idleTimeout?: number

      Maximum time in seconds to wait for connection to become available

    • max?: number

      Maximum number of connections in the pool

    • maxLifetime?: number

      Maximum lifetime in seconds of a connection

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

      Callback executed when a connection is closed Receives the closing Error or null.

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

      Callback executed 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

    • ssl?: boolean | TLSOptions

      Whether to use TLS/SSL for the connection (alias for tls)

    • tls?: boolean | TLSOptions

      Whether to use TLS/SSL for the connection

    • url?: string | URL

      Connection URL (can be string or URL object)

    • username?: string

      Database user for authentication

  • interface Query<T>

    Represents a SQL query that can be executed, with additional control methods Extends Promise to allow for async/await usage

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

      Indicates if the query is currently executing

    • cancelled: boolean

      Indicates 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>;

      Executes the query

    • 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 the raw query result

    • simple(): Query<T>;

      Executes the query as a simple query, no parameters are allowed but can execute 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 only the values from the query result

  • interface SQLiteOptions

    Options for Database

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

      Allow creating a new database

      Equivalent to constants.SQLITE_OPEN_CREATE

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

      Specify the 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

      Callback executed when a connection is closed (SQLite) Receives the closing Error or null.

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

      Callback executed when a connection attempt completes (SQLite) 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 set to true, integers are returned as bigint types.

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

    • strict?: boolean

      When set to false or undefined:

      • Queries missing bound parameters will 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 will throw an error
      • Bound named parameters in JavaScript no longer need to be $, :, or @. The SQL query will remain prefixed.
  • 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: (client) => {
        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