method
SavepointSQL.connect
Referenced types
namespace SQL
class MySQLError
- readonly code: string
Bun's error code, such as
"ERR_MYSQL_SERVER_ERROR"or"ERR_MYSQL_CONNECTION_CLOSED". It is not a name likeER_DUP_ENTRY: compare errno for that. - readonly errno?: number
The error number that the server sent, such as
1062for a duplicate entry. Not set on errors that Bun raises itself. - static stackTraceLimit: number
The
Error.stackTraceLimitproperty specifies the number of stack frames collected by a stack trace (whether generated bynew Error().stackorError.captureStackTrace(obj)).The default value is
10but 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
class PostgresError
- 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 errno?: string
The SQLSTATE that the server sent, such as
"23505"for a unique violation. Not set on errors that Bun raises itself. - static stackTraceLimit: number
The
Error.stackTraceLimitproperty specifies the number of stack frames collected by a stack trace (whether generated bynew Error().stackorError.captureStackTrace(obj)).The default value is
10but 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
class SQLError
- static stackTraceLimit: number
The
Error.stackTraceLimitproperty specifies the number of stack frames collected by a stack trace (whether generated bynew Error().stackorError.captureStackTrace(obj)).The default value is
10but 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
class SQLiteError
- readonly byteOffset?: number
The UTF-8 byte offset of the token that the error refers to, counted from the start of the query text.
-1if the error refers to no token. Not set on errors that Bun raises itself. - 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 & 0xffis the primary code.0on errors that Bun raises itself. - static stackTraceLimit: number
The
Error.stackTraceLimitproperty specifies the number of stack frames collected by a stack trace (whether generated bynew Error().stackorError.captureStackTrace(obj)).The default value is
10but 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
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
namein 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 insql(object, "a", "b"), and everysql("name"), table names included.
interface ListenSubscription
One registration made by SQL.listen.
Remove this registration. Resolves once the channel is no longer subscribed, or immediately when other registrations on it remain. Idempotent;
await usingcalls it at the end of the scope.
interface NameTransform
One of
SQL.toCamel,SQL.fromCameland the like. Call it to convert a name, or pass it as thetransformoption 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 theMARIADB_*environment variables instead ofMYSQL_*. - allowPublicKeyRetrieval?: boolean
MySQL only. Allow the client to request the server's RSA public key during
caching_sha2_password/sha256_passwordauthentication 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_passworddoes not need it over a unix socket either.sha256_passworddoes. - bigint?: boolean
Return large integers as
BigInt. By default they are returned as strings.PostgreSQL: every
int8, whatever its value. MySQL:BIGINTvalues outside the 32-bit range, and alastInsertRowidaboveNumber.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 withERR_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 thePGCHANNELBINDINGenvironment 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_DATABASEandMARIADB_DATABASEtake priority over the database in a URL. - foundRows?: boolean
MySQL and MariaDB only. Report the rows that the
WHEREclause of anUPDATEmatched inaffectedRows, asmysql2, themariadbconnector, PostgreSQL and SQLite do. Without it, the server counts only the rows whose values changed, so anUPDATEthat sets a row to the values it already has reports0. 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.
- 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
Errorthat says why. It is nevernull: after SQL.close the code isERR_POSTGRES_CONNECTION_CLOSEDorERR_MYSQL_CONNECTION_CLOSED. A failed attempt passes its own error, for exampleERR_POSTGRES_CONNECTION_REFUSED. - 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. - prepare?: boolean
PostgreSQL only. Use named prepared statements. Each connection keeps the 1,024 it used last.
falsethrows 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"). ABunFileis the CA certificate to verify the server against, the same as{ ca: Bun.file(path) }, and selects"verify-full".trueand an options object ask for at least"require". An object withca,caFile,checkServerIdentityorrejectUnauthorized: trueraises a mode below"verify-ca"to"verify-full". WithoutrejectUnauthorized,NODE_TLS_REJECT_UNAUTHORIZED=0turns 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
urland without a connection string, Bun reads a URL from the environment, such asDATABASE_URL, and the other options change single fields of it.With
adapter, aDATABASE_URLthat names another adapter's server is not used, except for the TLS mode it asks for when no other URL applies.
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, andawaitcallsthen().What
then()andcatch()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 afinally()callback throws.The failure of a query that was only started, with
execute()orfinally(), is not reported once it has a connection, nor whenclose({ 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. Afterexecute(), a failure to connect, a pool that was already closed, acancel()or the end of the time ofclose({ 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,Dateor object that you passed alone until the query settles.Cancels the query.
A query that Bun has not sent yet never runs. It rejects with
ERR_POSTGRES_QUERY_CANCELLED(or theMYSQL/SQLITEcode).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 withERR_POSTGRES_QUERY_CANCELLEDand ahint, because the server may still run it.MySQL: a query that Bun has sent runs to the end and settles with its result.
- onrejected?: null | (reason: any) => TResult | PromiseLike<TResult>
Attaches a callback for only the rejection of the Promise.
@param onrejectedThe callback to execute when the Promise is rejected.
@returnsA Promise for the completion of the callback.
- onfinally?: null | () => void
Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.
@param onfinallyThe callback to execute when the Promise is settled (fulfilled or rejected).
@returnsA Promise for the completion of the callback.
Returns rows as arrays of
Bufferobjects 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[]andfloat4[]in binary and every other type as text; all types are text on the first run of a query without parameters, with.simple()and withprepare: false. On MySQL a prepared query is binary. SQLite:Uint8Arrayobjects.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 STDOUTquery 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
countwhen 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()));- onrejected?: null | (reason: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>;
Attaches callbacks for the resolution and/or rejection of the Promise.
@param onfulfilledThe callback to execute when the Promise is resolved.
@param onrejectedThe callback to execute when the Promise is rejected.
@returnsA Promise for the completion of which ever callback is executed.
- writable(): WritableStream<string | ArrayBufferLike | TypedArray<ArrayBufferLike> | DataView<ArrayBufferLike>>;
PostgreSQL only. Starts a
COPY ... FROM STDINquery 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 // ]- number?: number
PostgreSQL only. The number of the column in its table, from
1.0for an expression, negative for a system column such asctid. - table: string | number
The table that the column comes from.
- PostgreSQL: the OID of the table.
0for an expression. - MySQL: the name of the table, or its alias in the query.
""for an expression.
- PostgreSQL: the OID of the table.
- type: number
The type of the column.
- PostgreSQL: the OID of the type, such as
23forint4,25fortext,1009fortext[],3802forjsonb - MySQL: the type code of the protocol, such as
3forINT,8forBIGINT,253forVARCHAR,245forJSON
- PostgreSQL: the OID of the type, such as
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.stringifyand spreading only see the rows.A query with several statements (
.simple(), a MySQLCALL) resolves to a plain array of results. The metadata is on each inner array.- affectedRows: number
The number of rows that an
INSERT,UPDATE,DELETEorMERGEwrote.0for a statement that writes nothing.PostgreSQL tags
CREATE TABLE AS, and aSELECTwhose CTE writes, asSELECT, so it is0for them. MariaDB reportsINSERT ... RETURNINGas a result set, so it is0there 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 plainINSERT.nullon 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
INSERTgenerated.- PostgreSQL:
null. UseRETURNING. - MySQL: the first
AUTO_INCREMENTvalue of the statement,0if there is none. AboveNumber.MAX_SAFE_INTEGERit is a string, or aBigIntwithbigint: true. - SQLite: the
rowidof the last inserted row, also after a statement that inserts nothing.nullfor a statement that only reads. ABigIntwithsafeIntegers: trueorbigint: true.
- PostgreSQL:
- statement: null | ResultStatement
The text, the parameter types and the columns of the statement.
nullon 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.
- 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
filenameselects SQLite too. - bigint?: boolean
Return every integer as a
BigInt. The same assafeIntegers, under the name that the other adapters use.safeIntegerstakes 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 codeSQLITE_CANTOPEN. - filename?: URL | string & {} | ':memory:'
Path to the database file
Examples:
sqlite://:memory:sqlite://./path/to/database.dbsqlite:///Users/bun/projects/my-app/database.db./dev.db:memory:
Everything from the first
?is a query string, which can havemode=:ro(read-only),rw(read-write, the file must exist) orrwc(read-write and create, the default).memoryhas no effect, and any other mode throws. Thereadonlyandcreateoptions take priority over it, and a read-only database ignorescreateandreadwrite.Without a
filename, Bun reads aDATABASE_URLthat is not a PostgreSQL, MySQL or MariaDB URL, thenSQLITE_URL. - readonly?: boolean
Open the database as read-only (no write operations, no create).
Equivalent to constants.SQLITE_OPEN_READONLY
Together with
create: trueorreadwrite: true, the constructor throws aTypeError. - readwrite?: boolean
Open the database as read-write
Equivalent to constants.SQLITE_OPEN_READWRITE
readwrite: truewithoutcreate: truedoes not create the file.readwrite: falseis the same asreadonly: true. - safeIntegers?: boolean
When
true, integers are returned asbigint.When
false, integers are returned asnumber, and integers beyond 53 bits are rounded to the nearestnumber.When
true, abigintparameter that does not fit in a signed 64-bit integer throws aRangeError. Whenfalse, it keeps its low 64 bits:2n ** 64n - 1nis stored as-1. - strict?: boolean
When set to
true, a query with a missing bound parameter throws an error. When set tofalseorundefined, the parameter isNULL.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
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, callcheckServerIdentity()fromnode:tlsinside 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 withrejectUnauthorized: false.const sql = new SQL(url, { tls: { ca: Bun.file("./ca.pem"), checkServerIdentity: (hostname, cert) => cert.fingerprint256 === pin ? undefined : new Error("certificate pin mismatch"), }, }); - 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. - 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_BUFFERSto 1. Reduces overall performance but saves some memory. - requestCert?: boolean
If set to
true, the server requests a client certificate, and refuses a client without a valid one unlessrejectUnauthorizedisfalse. This option alone decides it:cadoes 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
interface Transform
The
transformoptionconst 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
undefinedparameter. When it is set (nullcounts), the insert and update helpers leave no column out. Without it,undefinedisNULL, and the helpers leave out a column that isundefined.
- 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> }
transformpreset:user_idin the database,userIdin JavaScript - const fromCamel: NameTransform
"userId"to"user_id". Astransform, renames the names insql()helpers only. - const fromKebab: NameTransform
"user-id"to"user_id". Astransform, renames the names insql()helpers only. - const fromPascal: NameTransform
"UserId"to"user_id". Astransform, renames the names insql()helpers only. - const kebab: { column: Required<ColumnTransform> }
transformpreset:user_idin the database,user-idin JavaScript - const pascal: { column: Required<ColumnTransform> }
transformpreset:user_idin the database,UserIdin JavaScript - const toCamel: NameTransform
"user_id"to"userId". Astransform, renames the columns of results only. - const toKebab: NameTransform
"user_id"to"user-id". Astransform, renames the columns of results only. - const toPascal: NameTransform
"user_id"to"UserId". Astransform, renames the columns of results only.