Custom fields
Field definitions, options and typed values, with a permission check for sensitive values.
custom-fields stores definitions (entity, key, label, type, required, sensitive, permission) and one typed value per subject.
better-supabase add custom-fieldsServer code calls the custom-fields instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useCustomFields } = defineDataHooks(
"customFields",
(db: AppDb) => db.customFields,
);import {
CUSTOM_FIELD_TYPES,
createCustomFields,
} from "better-supabase/blocks/custom-fields";
const customer = { type: "customer", id: customerId };
const tier = await db.customFields
.saveDefinition("customer", "tier", "Tier", "option")
.orThrow();
await db.customFields.setValue(customer, tier.id, "gold").orThrow();
const values = await db.customFields.readValues(customer).orThrow();"use client";
import { useCustomFields } from "@/lib/supabase/hooks";
const rows = useCustomFields({ limit: 50 });Definitions belong to an entity (listDefinitions(entity),
saveDefinition(entity, key, label, type, sensitive?)), and values to a
subject, a RecordRef ({ type, id }): readValues(subject) and
setValue(subject, definitionId, value). Every call acts in the block's
tenant, which createBlocks and createBlockClient pass from the request;
a call without one fails with invalid_request and the hint
TENANT_REQUIRED.
Setting a value again replaces it, so setValue never fails on the key of
record and field, and an encrypted value is sealed once. updateValue({ id, value }) changes one value row by its id and deleteValue(id) removes it. Both
need custom_fields.manage and the record's fields action, and fail with
CUSTOM_FIELD_VALUE_NOT_FOUND for an unknown id; updateValue also fails with
CUSTOM_FIELD_VALUE_INVALID for a value the field's format refuses. The SQL functions
are update_field_value(value_id, value) and delete_field_value(value_id).
Retire a field without losing what people entered:
await db.customFields.archiveDefinition(definition.id).orThrow();
await db.customFields.restoreDefinition(definition.id).orThrow();An archived field leaves listDefinitions(entity), and saveDefinition and
setValue refuse it with CUSTOM_FIELD_ARCHIVED until you restore it. Its
values stay and readValues still returns them.
listDefinitions({ entity, includeArchived: true }) lists archived fields too
and reports archivedAt. purgeDefinition(id) deletes a field for good with
every value stored under it; it needs permissions.purge, which falls back to
custom_fields.manage. The SQL functions are archive_field_definition,
restore_field_definition and purge_field_definition, and
list_field_definitions takes include_archived as a third argument. The
inline and keyed layouts have no definition rows, so they have no archive.
Types
CUSTOM_FIELD_TYPES lists the types a definition takes. A value is stored as text whatever the type; the type tells the form and the UI what it holds. The names match the app table formats, so a field and a column that hold the same thing use the same word.
| Type | Holds | Forms field type |
|---|---|---|
text, number, date, bool, json | the value | the same name |
option | one option value | option |
multi_option | a JSON array of option values | multi |
email, url | an address | email, url |
user | a user id | text |
rating | 1 to 5 | integer, bounded 1 to 5 |
currency | an integer of minor units | integer |
bsn | a Dutch citizen service number | text |
iban | a bank account number | text |
phone_e164 | a phone number in E.164 form | text |
set_field_value checks the value of the last three before it stores it and
fails with CUSTOM_FIELD_VALUE_INVALID (SQLSTATE 22023) when it doesn't pass:
| Type | Passes |
|---|---|
bsn | 9 digits whose elfproef sum is a multiple of 11, checked by bsb_valid_bsn(text) |
iban | the electronic form of ISO 13616 (uppercase, no spaces) whose mod 97 check is 1, by bsb_valid_iban(text) |
phone_e164 | a +, a country code that doesn't start with 0, and at most 15 digits |
Store the value in that form: strip the spaces from an IBAN and uppercase it
before you call setValue.
A form field that names a customField answers with the forms field type in the last column, and a form field's own min, max or options win over the definition's. The check on type is named bsb_field_definitions_type; upgrade drops the inline check an older install created and adds the named one.
A sensitive value is returned only when can passes for the field's permission, or custom_fields.read_sensitive when the field names none. A provider implements field-level grants behind that key.
Encrypted fields
With the field-encryption block
installed, encryptDefinition(id) stores a text, email, url, bsn,
iban or phone_e164 field's values as ciphertext under the tenant's data key, and encrypts the values it
already has. It needs custom_fields.manage, and there is no way back.
listDefinitions reports encrypted on each definition. setValue and
readValues work as before: the definer functions encrypt on write and
decrypt for callers that pass custom_fields.read (and the sensitive
permission for a sensitive field).
options.auditReads: true writes one field_value.viewed entry with the
category read to the audit log for each
readValues call that returns an encrypted or sensitive value, with the
subject and the value ids. It needs the audit block.
blocks: {
"field-encryption": {},
"custom-fields": { options: { auditReads: true } },
},options.layout is normalized (the default), inline or keyed (below). Inline layout stores the definition columns on the value row and skips the definitions table, which fits an existing table that keeps one value per row.
Entities are registered subject types
In the normalized layout, entity names a subject type that the app registers: a key of config.recordTypes or a type an installed block registers (blocks.custom-fields.on narrows the list). upsert_field_definition and install_field_pack fail with CUSTOM_FIELD_ENTITY_UNKNOWN (SQLSTATE 22023) for any other value. Without registered types the entity stays free text, so a project that has no subjects keeps working.
The list of registered types is one function, better_supabase.subject_types(), which returns text[]. Code that needs to ask the database which types exist calls it instead of keeping its own list.
Definitions that were saved with a free-text entity need a registered name before the block upgrades. blocks.custom-fields.options.entityMap maps each stored value to its replacement, and the upgrade renames the definitions and the value rows that point at them:
recordTypes: { sales_invoice: { table: "public.invoices", idType: "uuid" } },
blocks: {
"custom-fields": { options: { entityMap: { invoice: "sales_invoice" } } },
},The upgrade leaves a definition alone when its new name already has the same key in the organization. Run better-supabase doctor afterwards to list the entities that still aren't registered.
Field packs
A field pack is a versioned set of definitions for registered subject types. The library ships none: an industry, a team or an app writes its own and installs it per organization.
import { defineFieldPack } from "better-supabase/blocks/custom-fields";
export const contactsPack = defineFieldPack({
apiVersion: 1,
key: "contacts-basics",
version: 1,
recordTypes: {
customer: [
{ key: "tier", label: "Tier", type: "option" },
{ key: "referral_code", label: "Referral code", type: "text" },
{ key: "tax_id", label: "Tax ID", type: "text", sensitive: true },
],
},
});blocks: {
"custom-fields": { options: { packs: [contactsPack] } },
},db.customFields.installPacks() installs every pack of the option in the caller's organization, and installPack(pack) installs one. Both call install_field_pack(tenant, pack jsonb), which needs custom_fields.manage and matches each definition by pack and key:
- A new key creates the definition, ranked after the others of its entity.
- A key the pack owns changes only when the label, type,
required,sensitive,permissionor the pack version differ, so installing the same version twice reportsunchangedfor every field. - A key that a definition outside the pack already uses fails with
CUSTOM_FIELD_PACK_CONFLICT, and a malformed pack fails withCUSTOM_FIELD_PACK_INVALID.
The result is { pack, version, created, updated, unchanged }. listDefinitions reports the pack and packVersion of each definition. Raise version when the fields change and install again. A pack never deletes a definition, because the values behind it belong to the organization.
Packs are a versioned extension interface (apiVersion: 1). testFieldPack(pack, { subjects }) from better-supabase/testing checks one against the contract.
Values per legal entity
With the legal-entities block installed, field_values gains a nullable legal_entity_id. A value without one belongs to the organization, and a value with one belongs to that entity. A record keeps at most one value per field for the organization and one per entity.
readValues(subject, { legalEntity }) returns the entity's value where the entity has one and the organization's value where it doesn't. setValue(subject, definitionId, value, { legalEntity }) stores the entity's value. Without legalEntity both work on the organization's values as before. Without the legal-entities block the column and the extra argument don't exist.
Importing values
With the imports block installed, field_value is an import target. An item's data is { subject: { entity, key }, field, value }, where subject names a record by the external key in the import record map, field is the key of its definition and value is text, a number or a boolean. Items can name the record by subjectType and subjectId instead, and add legalEntityId with the legal-entities block. import_field_value checks the value against the field's type, encrypts it for an encrypted field and writes it with the same event as set_field_value. A row that doesn't pass fails with IMPORT_ITEM_INVALID and a message that names the problem.
Keyed layout
options.layout: "keyed" keeps each field on its value row, the way a table of
attributes per record does: every row carries its key, label and type,
and its value sits in the column of that type (valueNumber for number,
rating and currency, valueDate, valueBool, valueJson for json and
multi_option, valueUrl and valueEmail when you map them, valueText
for the rest). There are no definition or option tables, and the module writes
three functions instead of the definition ones:
| Function | What it does |
|---|---|
set_field_value(tenant, subject_type, subject_id, key, label, type, value jsonb, rank, if_absent) | Sets the field key of the record: a new row, or the existing one with its label, type and value replaced. Every other value column is set to null. if_absent fails with FIELD_EXISTS instead of updating |
get_field_values(tenant, subject_type, subject_id) | The record's fields as { id, subjectType, subjectId, key, label, type, rank, value, createdAt, updatedAt }, ordered by rank and then key |
delete_field_value(value_id) | Removes one value and records field_value.deleted |
The client calls them as setField(record, { key, label, type, value, rank?, ifAbsent? }), readFields(record) and deleteValue(id). Writing needs
custom_fields.manage, a record that exists in the tenant, and the record's
fields action when config.recordTypes
declares one (such as fields: "product.update"); a value that doesn't fit its type fails with
CUSTOM_FIELD_VALUE_INVALID.
A record type can name its own tenant keys in on.<type>.keys, so the people
who edit products also edit product fields without holding
custom_fields.manage. manage replaces the key that writing and deleting
the type's values ask for, and read the key that reading them asks for.
Either can be left out, and types without keys keep the module's keys:
on: {
product: {
table: "public.products",
idType: "uuid",
column: "product_id",
keys: { manage: "products.update", read: "products.read" },
},
},keys applies only to the keyed layout. A type with readAccess: "record"
reads through the record instead, so its keys.read is not checked.
A record type can keep its id in its own column of the values table instead
of subject_type and subject_id, so the table keeps a real foreign key per
record type. Name it in on.<type>.column; when every type in on names one,
map subjectType and subjectId to null. A type column that stores other
labels than the block's, such as boolean for bool, maps them through
values:
export default defineConfig({
blocks: {
"custom-fields": {
tables: { definitions: null, options: null, values: "public.attributes" },
columns: {
values: {
tenant: "organization_id",
definition: null,
optionId: null,
valueJson: null,
valueEmail: null,
rank: null,
subjectType: null,
subjectId: null,
type: "value_type",
valueText: "text_value",
valueNumber: "number_value",
valueDate: "date_value",
valueBool: "boolean_value",
valueUrl: "url_value",
},
},
values: { values: { type: { bool: "boolean" } } },
on: {
product: {
table: "public.products",
idType: "uuid",
column: "product_id",
},
asset: { table: "public.assets", idType: "uuid", column: "asset_id" },
},
options: { layout: "keyed" },
},
},
});Reading needs custom_fields.read in the tenant. With
options.readAccess: "record", get_field_values checks each record instead:
the record is in the tenant and can_subject(type, id, 'read') passes, so the
record's own policies and its read action decide, and permissions.read is
not checked. It needs the subjects block. The keyed layout has no sensitive
values, so permissions.sensitive is not checked either.
To check only some records, set readAccess: "record" on their type in
config.recordTypes (or in on) instead of the option. Values of those types
follow the record's read entry, and the other types keep the tenant key.
A record type that declares no read permission (no permissions.read and no
read entry), or has no tenant column, also keeps the tenant key, because
get_field_values runs as the definer and would otherwise only check that
the record exists in the tenant the caller names.
driveSubject() sets it for drive_node, so a member without a grant on a
node can't read its field values. This works in every layout; in the
normalized and inline layouts, a record-checked value skips
custom_fields.read, and a sensitive value still needs the field's
permission.
rank is a fractional text key by default, ordered with collate "C". With
options.rankType: "integer", the managed table's rank column is an
integer, and over your own table the rank text is cast to the type of the
column rank maps to, so an existing position integer column works. Pass the
rank as a string of digits, such as rank: "3"; reads return it as a string too.
A new field without a rank goes after the record's last one.
rankType applies only to the keyed layout.
"custom-fields": {
columns: { values: { rank: "position" } },
options: { layout: "keyed", rankType: "integer", readAccess: "record" },
},The normalized and inline layouts keep their functions. In them too,
set_field_value asks the record's fields action when its type declares one.
Over your own tables
To run over tables you already have, map tables.definitions, tables.options and tables.values. Set a column to null when the existing table does not have it. For the inline layout, map values.definition to null and set layout to inline.
Order
Field definitions of an entity are ordered by rank, a fractional key (see Rank). A new definition goes after the last one, and reorderDefinition(id, { previous, next }) moves it between the definitions with those keys. listDefinitions(entity) returns an entity's definitions in that order, each with its rank key, for callers with custom_fields.read. Version 2 of the module replaced the integer position column with rank: the upgrade backfills keys in the old order and drops position. moveDefinition({ id, entity, toIndex }) puts a definition at a position (0 is first) and returns its new key. The inline layout has no rank column.
Without the client
db.customFields is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import {
CUSTOM_FIELD_TYPES,
createCustomFields,
} from "better-supabase/blocks/custom-fields";
const fields = createCustomFields({ transport, tenant: organizationId });
const customer = { type: "customer", id: customerId };
const tier = await fields
.saveDefinition("customer", "tier", "Tier", "option")
.orThrow();
await fields.setValue(customer, tier.id, "gold").orThrow();
const values = await fields.readValues(customer).orThrow();Set several values
bulkSet({ subject, inputs }, options) calls setField for each input in order and returns { succeeded, failed } named by field key (ADR 1075). A refused field lands in failed and the others still run. It takes at most 500 inputs, each key once; a repeated key fails with BULK_DUPLICATE_ID.
const report = await customFields
.bulkSet({
subject: { type: "employees", id: employeeId },
inputs: [
{ key: "badge", label: "Badge", type: "number", value: 7 },
{ key: "grade", label: "Grade", type: "text", value: "B" },
],
})
.orThrow();setMany does the same and stops at the first failure. It is deprecated and removed in 0.70.
Paging field definitions
page pages the definitions of the tenant in display order. Sorts are key, label, type and rank. Filters are entity, type, sensitive and archived, facets are entity and type, and q searches the key and the label. getDefinition(id) returns one definition or a not_found error. The page needs the normalized layout. listDefinitions is deprecated. The SQL functions are page_field_definitions and get_field_definition; they check the scope read permission.
const page = await customFields
.page({ filters: { entity: ["customer"] }, limit: 100 })
.orThrow();Last updated on
State machine
Allowed status transitions as the caller, a history row, status events, and an optional lifecycle with pause, flags and a pinned version.
Saved views
Named list views per user, team or organization, with the filter tree, sort, columns, grouping and density checked against the list definition, personal defaults, duplicates, and useSavedViews for nuqs.