# Tags that render SQL

> Turn on row access policies, a keyset list function, an idempotency index, an id lookup function, a stored rollup, a row copy function and a date bucket count for your own tables with tags.

Source: https://bettersupabase.com/docs/repository/rendered-tags

Seven `@bsb` tags in a table comment write SQL for you. `better-supabase table <name> enable <tag>`
reads the tag's arguments from the comment and writes the statements into the table's own file, between
`-- @bsb-tag <name> begin` and `-- @bsb-tag <name> end`. Running it again replaces the block, and
`disable` removes it. Run `db diff` afterwards to write the migration.

```sql
comment on table public.projects is
  'Projects. @bsb access read=projects.read create=projects.write update=projects.write delete=projects.write actor-guard; list search=name,code sort=created_at:desc filter=status; idempotency';
```

```bash
pnpm better-supabase table projects enable access
pnpm better-supabase table projects enable list
pnpm better-supabase table projects enable idempotency
```

## access [#access]

`access` renders row level security for a table with a tenant column. Each of `read`, `create`,
`update` and `delete` takes a permission key and becomes one policy named `bsb_access_<table>_<operation>`
for the `authenticated` role. At least one is required.

| Argument      | Meaning                                                                       |
| ------------- | ----------------------------------------------------------------------------- |
| `read`        | The permission that lets a member select rows of their tenant.                |
| `create`      | The permission for inserts.                                                   |
| `update`      | The permission for updates, checked before and after the change.              |
| `delete`      | The permission for deletes.                                                   |
| `tenant`      | The tenant column. Default `tenant_id`.                                       |
| `actor-guard` | Also requires that the session may write, so read-only support sessions fail. |

The check comes from your authorization provider. With a `canIn` template
([provider contract](/docs/extending/authorization-providers)) it is that template, with
`{permission}` and `{tenant}` filled. Without one it is
`tenant_id in (select better_supabase.tenant_ids_with('<permission>'))`, which every provider answers
through `idsWith`, so a provider written before `canIn` existed needs no change. The write guard uses
`actorMayWrite` when the provider sets it, and `better_supabase.actor_may_write()` otherwise.

## list [#list]

`list` renders `list_<table>(tenant, filters)`, a `security invoker` function that returns a
keyset page, so row level security decides the rows. It also writes the sort index (the tenant
column, the sort columns and the id) and a trigram index for each search column; the trigram
index needs `pg_trgm` in the `extensions` schema.

| Argument | Meaning                                                                                  |
| -------- | ---------------------------------------------------------------------------------------- |
| `search` | Comma list of text columns matched with `ilike` by the `search` filter.                  |
| `sort`   | Comma list of `column:direction[:type]`. Default `created_at:desc`. Keep these not null. |
| `filter` | Comma list of `column[:type]` equality filters, passed only when the caller sets them.   |
| `tenant` | The tenant column, or `false` for none. Default `tenant_id`.                             |
| `id`     | The unique tiebreaker column. Default `id`; `id-type` sets its type.                     |
| `name`   | The function name. Default `list_<table>`.                                               |

Column types follow the name (`*_id` is `uuid`, `*_at` is `timestamptz`, `*_on` is `date`, a few
counters are `bigint`, anything else is `text`); the third segment of `sort` and `filter` overrides it.

The function takes the same filters as the block lists. By default it returns the rows as an array.
`{ "paged": true }` returns `{ items, hasMore, nextCursor }`, and `{ "total": true }` adds `total` and
`totalCapped`, counted up to `totalCap` rows (default 10,000), so a large table is not counted in
full. Pass the previous `nextCursor` as `after` for the next page. `offset` pages by number for a
caller that shows page numbers, at the cost of reading and discarding every skipped row; `after` and
`offset` do not combine.

```ts
const page = await db
  .$rpc("list_projects", {
    tenant: organizationId,
    filters: { status: "open", limit: 25, paged: true, total: true },
  })
  .orThrow();

const next = await db
  .$rpc("list_projects", {
    tenant: organizationId,
    filters: { limit: 25, paged: true, after: page.nextCursor },
  })
  .orThrow();
```

The built-in `risks` block takes `after` and `limit` through `risks.page({ after, limit })`, with the sort, list filters, facets and count of the [list contract](/docs/extending/blocks#the-list-contract).

## idempotency [#idempotency]

`idempotency` writes a unique index on the tenant column and the `idempotency_key` column
(`column=` names another), only for rows that have a key. A retried insert with the same key
then fails with a unique violation instead of writing twice. The table declares the column.

## rpc [#rpc]

`rpc` renders `get_<table>_by_ids(ids)`, a `security invoker` function that returns the rows for a list
of ids as a jsonb array, in the order of the ids. Ids that match no row, or that row security hides,
are left out. It is the source a list that loads its rows by id reads from.

| Argument  | Meaning                                                                    |
| --------- | -------------------------------------------------------------------------- |
| `name`    | The function name. Default `get_<table>_by_ids`.                           |
| `columns` | Comma list of columns to return. Default every column.                     |
| `id`      | The id column. Default `id`; `id-type` sets its type (default `uuid`).     |
| `max`     | The most ids one call reads, 1 to 5000. Default 500; the rest are dropped. |

```ts
const rows = await db
  .$rpc("get_projects_by_ids", { ids: [idB, idA] })
  .orThrow();
```

## rollup [#rollup]

`rollup stored` keeps a number on a parent row equal to what the child table holds. The trigger
`bsb_rollup_<table>_<column>` runs after insert, update and delete on the child, and a `security
definer` function writes the parent so a member who may only write children still keeps the total
right. One rollup per child table; the tag is always written `rollup stored`.

| Argument     | Meaning                                                                            |
| ------------ | ---------------------------------------------------------------------------------- |
| `to`         | The parent table, as `schema.table`.                                               |
| `key`        | The child column that references the parent.                                       |
| `column`     | The parent column that stores the value. It must be a number, not null, default 0. |
| `sum`        | A child column to add up. Without it the rollup counts rows.                       |
| `parent-key` | The parent's key column. Default `id`.                                             |

```sql
comment on table public.tasks is
  'Tasks. @bsb rollup stored to=public.projects key=project_id column=task_count';
```

The trigger keeps the column right from the moment it exists. Backfill the column once when you turn
the tag on, for example with `better-supabase db backfill`. A row that moves to another parent leaves
the old total and joins the new one.

## copy [#copy]

`copy` renders `copy_<table>(source)`, a `security invoker` function that inserts a copy of one row and
returns it. Row security decides what the caller may read and insert.

| Argument  | Meaning                                                                |
| --------- | ---------------------------------------------------------------------- |
| `columns` | Required. The columns to copy. Leave out the id and generated columns. |
| `suffix`  | Comma list of `column:text` pairs that append text to a copied column. |
| `name`    | The function name. Default `copy_<table>`.                             |
| `id`      | The id column. Default `id`; `id-type` sets its type.                  |

```sql
comment on table public.tasks is
  'Tasks. @bsb copy columns=tenant_id,project_id,title,hours suffix="title: (copy)"';
```

```ts
const copy = await db.$rpc("copy_tasks", { source: taskId }).orThrow();
```

## buckets [#buckets]

`buckets` renders `<table>_date_buckets(unit, tz, from_at, to_at, equals)`, a `security invoker`
function that counts rows per date bucket of one column, for the chart above a list. Row security
decides the rows. `unit` is `hour`, `day`, `week`, `month`, `quarter` or `year`; any other value fails
with `22023`. `tz` is the IANA time zone the buckets start in (default `UTC`), `from_at` and `to_at`
bound the column (`to_at` is exclusive), and `equals` is a jsonb object of column name to a list of
values, applied to the columns the tag's `filter` names.

| Argument | Meaning                                                                |
| -------- | ---------------------------------------------------------------------- |
| `column` | Required. The `date`, `timestamp` or `timestamptz` column to group by. |
| `filter` | Comma list of columns that `equals` may narrow by (compared as text).  |
| `max`    | The most buckets one call returns, 1 to 5000. Default 1000.            |
| `name`   | The function name. Default `<table>_date_buckets`.                     |

```sql
comment on table public.orders is
  'Orders. @bsb buckets column=placed_at filter=status,channel';
```

The function returns `[{ "bucket": "2026-01-01T00:00:00+00:00", "count": 3 }]`. Call it through
`listDateBuckets` from `better-supabase/list/buckets`, which also turns the facet values of a list
query into `equals`:

```ts
import { listDateBuckets } from "better-supabase/list/buckets";

const buckets = await listDateBuckets({
  rpc: (args) => db.$rpc("orders_date_buckets", args),
  unit: "week",
  timeZone: "Europe/Amsterdam",
  from: "2026-01-01",
  list: { facets: orderList.facets, query },
}).orThrow();
// [{ start: "2026-01-04T23:00:00+00:00", count: 12 }, ...]
```

The search text and the filter tree of a list do not reach the function. A facet on a related table, or
the `__unset__` value, makes `listDateBuckets` return an `invalid_request` error instead of a count that
ignores it.