method

ReservedSQL.array

values: any[] | TypedArray<ArrayBufferLike>,
typeNameOrTypeID?: number | ArrayType

Creates a PostgreSQL array parameter. null elements are SQL NULL, and nested arrays make a multi-dimensional array. Throws on MySQL and SQLite.

@param values

Array values to bind

@param typeNameOrTypeID

Element type name, or the OID of the array type. Bun casts the parameter to it: $1::INT[]. When omitted, Bun adds no cast and the server infers the type from the column, the compared value or a cast in the query. Pass it when the query gives no context: a bare SELECT ${sql.array([1])} returns the text {"1"}. Pass "JSON" or "JSONB" to encode each element as JSON: there null is the JSON value null, undefined is SQL NULL, and sql.json([1, 2]) stores a JSON array as one element.

@returns

The array parameter, ready to interpolate into a query

const array = sql.array([1, 2, 3], "INT");
await sql`CREATE TABLE users_posts (user_id INT, posts_id INT[])`;
await sql`INSERT INTO users_posts (user_id, posts_id) VALUES (${user.id}, ${array})`;

// the server infers the type from the compared column
await sql`SELECT * FROM users WHERE id = ANY(${sql.array([1, 2, 3])})`;

Referenced types

type ArrayType =
| 'BOOLEAN'
| 'BYTEA'
| 'CHAR'
| 'NAME'
| 'TEXT'
| 'VARCHAR'
| 'SMALLINT'
| 'INT2VECTOR'
| 'INTEGER'
| 'INT'
| 'BIGINT'
| 'REAL'
| 'DOUBLE PRECISION'
| 'NUMERIC'
| 'MONEY'
| 'OID'
| 'TID'
| 'XID'
| 'CID'
| 'JSON'
| 'JSONB'
| 'JSONPATH'
| 'XML'
| 'UUID'
| 'POINT'
| 'LSEG'
| 'PATH'
| 'BOX'
| 'POLYGON'
| 'LINE'
| 'CIRCLE'
| 'CIDR'
| 'MACADDR'
| 'INET'
| 'MACADDR8'
| 'DATE'
| 'TIME'
| 'TIMESTAMP'
| 'TIMESTAMPTZ'
| 'INTERVAL'
| 'TIMETZ'
| 'BIT'
| 'VARBIT'
| 'ACLITEM'
| 'PG_DATABASE'
| string & {}

interface SQLArrayParameter

An array parameter created by SQL.array

  • arrayType: undefined | ArrayType

    The element type of the array, for example "INT". undefined when no type was given: Bun adds no cast, and the server infers the type.

  • serializedValues: string

    The array values, serialized into a single string