better-drizzle

This page is PostgreSQL only.

Array updates

Append, prepend, remove, replace, and add unique values to PostgreSQL array columns in one atomic statement.

Added in 0.3.0

Use array updates when you add or remove elements of a PostgreSQL array column (tags, roles, permissions) without reading the row first. Each update is one atomic SQL statement.

Append, prepend, remove, and replace

Array updates work in update, updateMany, updateEach, upsert, and explicit-object or callback upsertMany updates. A field takes either its normal replacement value or one update object.

await client.posts.update({
	where: { id: postId },
	data: {
		tags: { append: ['drizzle', 'orm'] },
		roles: { prepend: 'editor' },
		flags: { remove: ['archived', 'spam'] },
		scores: {
			replace: [
				{ from: 0, to: 1 },
				{ from: -1, to: 0 },
			],
		},
	},
});

Add values only once

addUnique adds only values that are not already present. It is still one SQL statement, preserves the order of the first input occurrence, and leaves duplicates that already exist in the stored array untouched:

await client.posts.update({
	where: { id: postId },
	data: { tags: { addUnique: ['drizzle', 'orm', 'drizzle'] } },
});

Rules

Use exactly one operator per field. Mutation lists must contain at least one non-null item. replace accepts either one { from, to } pair or a list of pairs, which runs from left to right. remove removes every occurrence, as PostgreSQL's array_remove() does. Direct replacement remains available:

await client.posts.update({
	where: { id: postId },
	data: { tags: [] },
});

For a NULL stored array, PostgreSQL's native functions keep their native semantics. addUnique also leaves NULL unchanged rather than treating it as an empty array.

Reference

OperatorEffectPostgreSQL
appendadds values at the endarray_append (one value) / array_cat
prependadds values at the startarray_prepend (one value) / array_cat
removeremoves every occurrence of each valuearray_remove
replacereplaces from with to, pair by pair from left to rightarray_replace
addUniqueappends values that are not present yet, in first-input orderone array_cat with a NOT @> subquery

Other dialects throw ARRAY_MUTATION_UNSUPPORTED. Measured costs are in array indexing and performance.

On this page