How to Use Batch Values (Virtual Data Source)
batchValues() lets you pass an in-memory array of records into a SQL query as a virtual table, without inserting them into the database first. This is useful for bulk updates, ordered lookups, and large IN-list alternatives that scale beyond what a plain parameter list supports.
When
When you need to pass an in-memory array of records into a query as a virtual table — without inserting them into the database first. Typical use cases:
- Bulk UPDATE FROM — update multiple rows in one SQL round-trip using a lookup table
- Filtered SELECT — join an existing table against an in-memory set to return only matching rows
- Ordered lookup — fetch rows in a caller-defined order using an
ordcolumn numbering the batch rows from 1 (bigint) - In-memory filtering — use a set of ids/values as a dynamic IN-list alternative that scales
batchValues() compiles to a subquery that unnests one array parameter per column in its select list, (SELECT pg_catalog.unnest(CAST($1 AS type[])) AS col1, pg_catalog.unnest(CAST($2 AS type[])) AS col2, ...) AS alias — zero extra round-trips, no temp tables. A composite-typed cell stays one column.
API
Standalone factory (import from @dbsp/core)
// doctest: skip — API signature reference (TypeScript function signature, not executable code)
import { batchValues } from '@dbsp/core'
batchValues(
data: readonly unknown[][], // Column-major: one array per column
columns: readonly string[], // Column names for the unnest alias
types: readonly string[], // PostgreSQL type names: 'integer', 'text', 'bool', etc.
opts?: BatchValuesOptions, // Optional: alias and ordinality
): BatchValuesRefORM method (identical, attached to orm instance)
// doctest: skip — API signature reference (TypeScript function signature, not executable code)
const batch = orm.batchValues(data, columns, types, opts?)BatchValuesOptions
type BatchValuesOptions = {
alias?: string; // Alias for the unnest source in SQL (default: 'batch')
ordinality?: boolean; // Append a row-number column named 'ord' (default: false)
}BatchValuesRef usage
A BatchValuesRef is a lightweight descriptor — not a QueryBuilder. Pass it to:
| Method | Purpose |
|---|---|
orm.from(batchRef) | Use batch as the primary FROM source |
.join(batchRef, { on: ... }) | Join batch to a table in a SELECT query |
A batch UPDATE takes rows, not a BatchValuesRef: use orm.update('table').batchSet(...) (see example 3).
Note: orm.from(batchRef) returns a QueryBuilder<Record<string, unknown>> — columns are not statically typed because the schema is runtime-defined.
Examples
1. Basic: batch as the primary FROM source
Fetch the batch values as a standalone result set.
// doctest: real-db-only — requires a live PostgreSQL connection
import { batchValues } from '@dbsp/core'
const batch = batchValues(
[['/src/a.ts', '/src/b.ts'], ['a.ts', 'b.ts']],
['path', 'name'],
['text', 'text'],
{ alias: 'requested' },
)
const results = await orm.from(batch).all()Generated SQL:
SELECT requested.*
FROM (SELECT pg_catalog.unnest(CAST($1 AS text[])) AS path,
pg_catalog.unnest(CAST($2 AS text[])) AS name) AS requestedParameters: [['/src/a.ts', '/src/b.ts'], ['a.ts', 'b.ts']]
2. JOIN with an existing table
Filter rows in a real table against a set of in-memory values.
import { schema, createOrm, batchValues, eq, ref } from '@dbsp/core';
import { createPgCompileOnlyAdapter } from '@dbsp/adapter-pgsql';
const __batchCallsDb = schema({
calls: {
id: 'integer',
callee_id: 'integer',
},
} as const);
const __batchCallsOrm = createOrm({ schema: __batchCallsDb, adapter: createPgCompileOnlyAdapter() });
const batch = batchValues(
[[1, 2, 3], [10, 20, 30]],
['id', 'callee_id'],
['integer', 'integer'],
{ alias: 'batch' },
);
const rows = await __batchCallsOrm.select('calls')
.join(batch, {
on: eq('calls.id', ref('batch.id')),
type: 'inner',
})
.dump();Generated SQL:
SELECT calls.*
FROM calls
JOIN (SELECT pg_catalog.unnest(CAST($1 AS integer[])) AS id,
pg_catalog.unnest(CAST($2 AS integer[])) AS callee_id) AS batch
ON calls.id = batch.idParameters: [[1, 2, 3], [10, 20, 30]]
3. Batch UPDATE FROM
Update multiple rows in one query. batchSet() takes the rows and builds the batch itself; a BatchValuesRef is a read source, and orm.modify() has no join().
import { schema, createOrm } from '@dbsp/core';
import { createPgCompileOnlyAdapter } from '@dbsp/adapter-pgsql';
const __batchUpdateDb = schema({
calls: {
id: 'integer',
callee_id: 'integer',
},
} as const);
const __batchUpdateOrm = createOrm({ schema: __batchUpdateDb, adapter: createPgCompileOnlyAdapter() });
const update = __batchUpdateOrm.update('calls')
.batchSet('id', [
{ id: 101, callee_id: 201 },
{ id: 102, callee_id: 202 },
{ id: 103, callee_id: 203 },
])
.dump();Generated SQL:
UPDATE calls
SET callee_id = t.callee_id
FROM (SELECT pg_catalog.unnest(CAST($1 AS int4[])) AS id,
pg_catalog.unnest(CAST($2 AS int4[])) AS callee_id) AS t
WHERE calls.id = t.idParameters: [[101, 102, 103], [201, 202, 203]]
4. Ordinality — row number column
Use ordinality: true to get an ord column numbering the batch rows from 1 (bigint). Useful for preserving caller-defined ordering in a JOIN or SELECT.
import { schema, createOrm, batchValues } from '@dbsp/core';
import { createPgCompileOnlyAdapter } from '@dbsp/adapter-pgsql';
const __batchOrdDb = schema({ files: { path: 'text' } } as const);
const __batchOrdOrm = createOrm({ schema: __batchOrdDb, adapter: createPgCompileOnlyAdapter() });
const requestedPaths = ['/src/c.ts', '/src/a.ts', '/src/b.ts']
const requested = batchValues(
[requestedPaths],
['path'],
['text'],
{ alias: 'requested', ordinality: true },
)
const ordered = __batchOrdOrm.from(requested)
.orderBy('requested.ord')
.dump()Generated SQL:
SELECT requested.*
FROM (SELECT pg_catalog.unnest(CAST($1 AS text[])) AS path,
pg_catalog.unnest(ARRAY(SELECT g
FROM pg_catalog.generate_series(CAST(1 AS bigint),
GREATEST(pg_catalog.cardinality(CAST($1 AS text[])))) AS g
ORDER BY g)) AS ord) AS requested
ORDER BY requested.ord ASCThe ord column is automatically appended after all named columns when ordinality: true. It numbers the rows of the longest array.
5. Filtering via join (IN-list alternative)
Use an inner join against a batch as a scalable alternative to WHERE id IN (...) for large value sets.
// doctest: real-db-only — requires a live PostgreSQL connection
import { batchValues, eq, ref } from '@dbsp/core'
const activeIds = [/* potentially thousands of ids */]
const batch = batchValues(
[activeIds],
['id'],
['uuid'],
{ alias: 'filter' },
)
const users = await orm.select('users')
.join(batch, {
on: eq('users.id', ref('filter.id')),
type: 'inner',
})
.all()This avoids the PostgreSQL IN-list limit and keeps parameters as a single typed array.
Key Files
packages/core/src/dx/batch-values.ts—batchValues()factory,BatchValuesReftype,BatchValuesOptionstype,isBatchValuesRef()guardpackages/core/src/dx/orm-instance.ts—orm.batchValues()method +orm.from(batchRef)dispatchpackages/core/src/dx/query-builder.ts—QueryBuilder.join(batchRef, { on })overloadpackages/adapter-pgsql/src/__tests__/batch-values.test.ts— canonical compilation tests
Gotchas
- Column-major, not row-major —
datais an array of column arrays, not an array of row objects.[[ids...], [names...]]not[{id, name}, ...]. A read pads the shorter arrays with NULL; an insert or upsert from a batch refuses arrays of unequal length. - Type names are validated at construction time — a type name is an identifier (
[a-zA-Z0-9_]), optionally schema-qualified (app.my_type), with an optional(N)or(N,M)modifier and at most one trailing[]('int4[]'and'int4'compile the same cast); a few multi-word built-ins such as'character varying'are accepted as written. Any other punctuation throws. - JSON array cells — in a column declared
jsonorjsonb(unquoted, any case, optionally inpg_catalog), a JavaScript array cell is one JSON value: it is bound as itsJSON.stringifytext, one element of that column's array. In any other column an array cell is passed as given, andunnestflattens it, so a row per cell holds only when every column contributes one element per cell. onis required for.join(batchRef, ...)— unlike relation joins, a BatchValues join has no schema relationship to infer an ON clause from. Omittingonthrows an error at build time.- Compiled SQL uses
CAST($N AS type[])form — the pgsql deparser normalizes PostgreSQL's$N::type[]shorthand toCAST($N AS type[]). Both are equivalent but tests must match this form. - An explicit type is kept as written —
'integer'compiles asCAST($N AS integer[]),'int4'asint4[]; assertions against generated SQL must match the spelling passed intypes. orm.from(batchRef)returnsQueryBuilder<Record<string, unknown>>— columns are not statically typed. Downstream code must cast or validate results at runtime.- No schema validation — column names and types are not cross-checked against any ModelIR table. Typos in column names surface as runtime SQL errors, not TypeScript errors.
- Default alias is
'batch'— if you use multiple batch sources in one query, pass an explicitaliasfor each to avoid ambiguous references.