Hierarchy

  • Database

Constructors

  • Open or create a SQLite3 database

    Example

    const db = new Database("mydb.sqlite");
    db.run("CREATE TABLE foo (bar TEXT)");
    db.run("INSERT INTO foo VALUES (?)", "baz");
    console.log(db.query("SELECT * FROM foo").all());

    Example

    Open an in-memory database

    const db = new Database(":memory:");
    db.run("CREATE TABLE foo (bar TEXT)");
    db.run("INSERT INTO foo VALUES (?)", "hiiiiii");
    console.log(db.query("SELECT * FROM foo").all());

    Example

    Open read-only

    const db = new Database("mydb.sqlite", {readonly: true});
    

    Parameters

    • Optional filename: string

      The filename of the database to open. Pass an empty string ("") or ":memory:" or undefined for an in-memory database.

    • Optional options: number | { create?: boolean; readonly?: boolean; readwrite?: boolean }

      defaults to {readwrite: true, create: true}. If a number, then it's treated as SQLITE_OPEN_* constant flags.

    Returns Database

Properties

filename: string

The filename passed when new Database() was called

Example

const db = new Database("mydb.sqlite");
console.log(db.filename);
// => "mydb.sqlite"
handle: number

The underlying sqlite3 database handle

In native code, this is not a file descriptor, but an index into an array of database handles

Accessors

  • get inTransaction(): boolean
  • Is the database in a transaction?

    Returns

    true if the database is in a transaction, false otherwise

    Example

    db.run("CREATE TABLE foo (bar TEXT)");
    db.run("INSERT INTO foo VALUES (?)", "baz");
    db.run("BEGIN");
    db.run("INSERT INTO foo VALUES (?)", "qux");
    console.log(db.inTransaction());

    Returns boolean

Methods

  • Close the database connection.

    It is safe to call this method multiple times. If the database is already closed, this is a no-op. Running queries after the database has been closed will throw an error.

    Example

    db.close();
    

    This is called automatically when the database instance is garbage collected.

    Internally, this calls sqlite3_close_v2.

    Returns void

  • This is an alias of Database.prototype.run

    Type Parameters

    Parameters

    • sqlQuery: string
    • Rest ...bindings: ParamsType[]

    Returns void

  • Load a SQLite3 extension

    macOS requires a custom SQLite3 library to be linked because the Apple build of SQLite for macOS disables loading extensions. See setCustomSQLite

    Bun chooses the Apple build of SQLite on macOS because it brings a ~50% performance improvement.

    Parameters

    • extension: string

      name/path of the extension to load

    • Optional entryPoint: string

      optional entry point of the extension

    Returns void

  • Compile a SQL query and return a Statement object.

    This does not cache the compiled query and does not execute the query.

    Example

    // compile the query
    const stmt = db.query("SELECT * FROM foo WHERE bar = ?");
    // run the query
    stmt.all("baz");

    Returns

    Statment instance

    Under the hood, this calls sqlite3_prepare_v3.

    Type Parameters

    Parameters

    • sql: string

      The SQL query to compile

    • Rest ...params: ParamsType[]

      Optional bindings for the query

    Returns Statement<ParamsType, ReturnType>

  • Compile a SQL query and return a Statement object. This is the same as prepare except that it caches the compiled query.

    This does not execute the query, but instead prepares it for later execution and caches the compiled query if possible.

    Example

    // compile the query
    const stmt = db.query("SELECT * FROM foo WHERE bar = ?");
    // run the query
    stmt.all("baz");

    // run the query again
    stmt.all();

    Returns

    Statment instance

    Under the hood, this calls sqlite3_prepare_v3.

    Type Parameters

    Parameters

    • sqlQuery: string

    Returns Statement<ParamsType, ReturnType>

  • Execute a SQL query without returning any results.

    This does not cache the query, so if you want to run a query multiple times, you should use prepare instead.

    Example

    db.run("CREATE TABLE foo (bar TEXT)");
    db.run("INSERT INTO foo VALUES (?)", "baz");

    Useful for queries like:

    • CREATE TABLE
    • INSERT INTO
    • UPDATE
    • DELETE FROM
    • DROP TABLE
    • PRAGMA
    • ATTACH DATABASE
    • DETACH DATABASE
    • REINDEX
    • VACUUM
    • EXPLAIN ANALYZE
    • CREATE INDEX
    • CREATE TRIGGER
    • CREATE VIEW
    • CREATE VIRTUAL TABLE
    • CREATE TEMPORARY TABLE

    Returns

    Database instance

    Under the hood, this calls sqlite3_prepare_v3 followed by sqlite3_step and sqlite3_finalize.

    • The following types can be used when binding parameters:
    JavaScript type SQLite type
    string TEXT
    number INTEGER or DECIMAL
    boolean INTEGER (1 or 0)
    Uint8Array BLOB
    Buffer BLOB
    bigint INTEGER
    null NULL

    Type Parameters

    Parameters

    • sqlQuery: string
    • Rest ...bindings: ParamsType[]

      Optional bindings for the query

    Returns void

  • Creates a function that always runs inside a transaction. When the function is invoked, it will begin a new transaction. When the function returns, the transaction will be committed. If an exception is thrown, the transaction will be rolled back (and the exception will propagate as usual).

    Example

    // setup
    import { Database } from "bun:sqlite";
    const db = Database.open(":memory:");
    db.exec(
    "CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)"
    );

    const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)");
    const insertMany = db.transaction((cats) => {
    for (const cat of cats) insert.run(cat);
    });

    insertMany([
    { $name: "Joey", $age: 2 },
    { $name: "Sally", $age: 4 },
    { $name: "Junior", $age: 1 },
    ]);

    Parameters

    • insideTransaction: ((...args: any) => void)

      The callback which runs inside a transaction

        • (...args: any): void
        • Parameters

          • Rest ...args: any

          Returns void

    Returns CallableFunction & { deferred: ((...args: any) => void); exclusive: ((...args: any) => void); immediate: ((...args: any) => void) }

  • This is an alias of new Database()

    See Database

    Parameters

    • filename: string
    • Optional options: number | { create?: boolean; readonly?: boolean; readwrite?: boolean }

    Returns Database

  • Change the dynamic library path to SQLite

    Note

    macOS-only

    This only works before SQLite is loaded, so that's before you call new Database().

    It can only be run once because this will load the SQLite library into the process.

    Parameters

    • path: string

      The path to the SQLite library

    Returns boolean

Generated using TypeDoc