@softr/sdk
record-queries
>-
Boundary. ds lives on @softr/sdk/server and runs only inside a createServerFn handler or a server-side route hook — importing it into a component fails the build. The same holds for any helper that calls ds: declare it inside the handler. A function at module level that calls ds keeps the server-only import in the browser bundle, and every page stops loading until it moves. defineQuery and every type come from @softr/sdk and can be imported anywhere.
Reading records
ds reads records out of a Softr datasource, from the server only.
Setup
import { createServerFn } from '@tanstack/react-start'
import { defineQuery } from '@softr/sdk'
import { ds } from '@softr/sdk/server'ds is server-only. defineQuery only declares a read, so it ships on the root entrypoint and the declaration can sit anywhere.
Declare the read
Every read takes a query: which datasource, which fields, who it is for.
const publishedPosts = defineQuery({
id: 'publishedPosts',
datasourceId: '00000000-0000-0000-0000-000000000000',
fields: {
title: 'fZk3Qm9pLw2Xa1', // SINGLE_LINE_TEXT
published: 'Ru7bVx2cNq0Ed9', // CHECKBOX
publishedAt: 'Xp2dLh6vKz9Fa3',// DATETIME
views: 'mB4kQ8yTn1sWc7', // NUMBER
},
permissions: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] },
})- id is the name the person building the app sees, so publishedPosts, not q1. It must be unique across the app: no two declarations may share one, queries and mutations counted together.
- datasourceId is the opaque UUID from the table's registration on the application (Softr Studio's Data tab, or the application_register_data_source tool when an agent does it). It is not the table id and is never derived from the table's name.
- The keys of fields are names you choose. The values are field ids, opaque strings the table's schema gives you: database_get_table returns them for a Softr table, integration_list_table_fields for a table on a connected database. Everything downstream speaks your names: the returned records, where, orderBy.
- permissions declares who may run the query, and the SDK enforces it:
- { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] }: everyone, signed out included. customGroups narrows only the signed-in half.
- { userGroupTypes: ['NON_LOGGED_IN_USERS'] }: signed-out visitors only.
- { userGroupTypes: ['LOGGED_IN_USERS'] }: any signed-in visitor, narrowed to particular groups with customGroups: ['00000000-0000-0000-0000-00000000000a']. customGroups is added to userGroupTypes, never written in place of it.
- Write each group id as a literal in permissions. An id taken from a const is a lint error.
- Write the object inline in the defineQuery call. Passing the declaration or its fields through a variable, or spreading one in, widens the field ids to string and the types stop checking.
A query fixes the table and the columns. A filter also fixes the rows a role may read, for a privacy rule that never changes: see Keep each visitor to their own records. The filters the user picks, sorting and paging stay at the call site, because a list screen changes them as the user types. Declare as many queries over one datasource as the app needs, each carrying the fields its own screen touches.
Core Patterns
List records
const listPublishedPosts = createServerFn().handler(async () => {
return await ds
.list(publishedPosts)
.where((q) => q.published.is(true))
.orderBy((q) => q.publishedAt.desc)
.limit(50)
})Returns { records, total, nextOffset }. Each record is { id, fields }, with fields keyed by the query's own names: every declared field is present, null when empty, and a field the query does not declare is not returned. ds.list(publishedPosts) with no calls chained returns the first 20 records. limit is clamped to 100, so more than a hundred records means paginating.
Filter with the where callback
q is the argument the callback is handed, not an import. It carries one handle per declared field, offering only the operators that field's type supports, plus $and and $or:
await ds.list(publishedPosts).where((q) =>
q.$and(
q.published.is(true),
q.views.gte(100),
q.$or(q.title.contains('cafe'), q.title.startsWith('The')),
),
)Calling .where more than once ands the filters together, and the query's filter too, so a where only narrows the rows. Only the query's own fields can be filtered or sorted on, so a field you need in a where belongs in fields even when the page never displays it. Load references/filters-and-sorting.md when you need an operator this page does not show, or when a filter is rejected.
Sort
.orderBy((q) => q.publishedAt.desc)
.orderBy((q) => [q.views.desc, q.title.asc]) // array for tie-breakersGet one record
const post = await ds.get(publishedPosts, { id: postId })
if (post === null) throw notFound()A record that does not exist comes back as null, not an error. A chained .where narrows which record the id may resolve to, and a record that does not match reads as null too:
const post = await ds
.get(publishedPosts, { id: postId })
.where((q) => q.published.is(true))There is no orderBy, limit or offset on a get. To find a record by a field instead of its id, use ds.list with a limit of 1.
Paginate
const first = await ds.list(publishedPosts).limit(50)
if (first.nextOffset !== null) {
const second = await ds.list(publishedPosts).limit(50).offset(first.nextOffset)
}nextOffset is null when there are no more pages. total is the count of all matching records, not the count returned.
Populate a control from a linked table
A LINKED_RECORD field on a record answers with { id, label } — the label is the linked record's primary field, and the id is what a write or a where filter takes. To fill a filter dropdown or form select with all options from the linked table (not just the values already referenced by existing records), query the linked table's own datasource:
// "status" on the products table is a LINKED_RECORD pointing to the Product Statuses table
const productStatuses = defineQuery({
id: 'productStatuses',
datasourceId: '00000000-0000-0000-0000-000000000001', // the linked table's datasource id
fields: { name: 'fZk3Qm9pLw2Xa1' },
permissions: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] },
})
const listProductStatuses = createServerFn().handler(async () => {
return await ds.list(productStatuses).limit(100)
})Each returned record is one option: record.id is the value a where filter and a mutation payload take; record.fields.name is what you display.
// Filter dropdown
{statuses.map((s) => (
<option key={s.id} value={s.id}>{s.fields.name}</option>
))}
// Filtering the main table by the selected linked record
ds.list(products).where((q) => q.status.is(selectedStatusId))For a picker that searches and pages, ds.options answers the shape a linked-record picker's load takes, { options: [{ id, label }], nextOffset }, searched on the label field when a term is given:
const loadProductStatuses = createServerFn()
.validator(z.object({ term: z.string(), offset: z.number().nullable() }))
.handler(({ data }) => ds.options(productStatuses, { label: 'name', ...data }))ds.options takes no where, but it reads through the query's filter. A picker over a filtered table takes the filtered query.
Skip this request when the options are predefined and fixed — hardcode them instead.
A SELECT field's options are its choices, and the builder can add and rename them in Studio after the app is built. When a dropdown should follow those changes, read them with ds.choices. When the app means a fixed choice, such as a "Done" tab, use its id directly. A mistyped id is not caught at compile time, and a write with an id the field lacks adds it as a new choice. ds.choices takes any query or mutation that declares the field and answers [{ id, label, color }] as the field holds them now. Each id is what a where and a write take, for a filter dropdown and a form select alike:
// `products` declares `category`, a SELECT field
const loadCategories = createServerFn().handler(() => ds.choices(products, 'category'))A read the datasource turns down throws rather than coming back empty, and it throws a plain Error carrying the status, followed by the reason the datasource gives when it sends one. There is no typed predicate to narrow it with. Handle it where you would handle any other failed fetch: an errorComponent on the route, or a check in the handler.
Keep each visitor to their own records
permissions decides who may run a query. filter decides which rows it reads. A visitor can call every server function with any arguments, so a privacy rule from the builder's prompt, such as "clients see only their own bookings", goes into the filter of the table's queries, never into the code of one server function. ds applies the filter on every ds.list, ds.get, ds.options, ds.chart and ds.metric of the query, and a where cannot widen it. Keep where for the filters the visitor picks at runtime: a search, a tab, a dropdown.
The examples below use bookings, a table where staff read every booking and a client reads only their own.
Declare the filter
// `client` links to Users. 'Rk2mVx9pQa4Lz7' is the Record ID field of the users table,
// declared in softr.json under user.properties.
const myBookings = defineQuery({
id: 'myBookings',
datasourceId: '00000000-0000-0000-0000-000000000002',
fields: { title: 'Lb7yQe3vXa9Ns1', date: 'Xp2dLh6vKz9Fa3', status: 'Ru7bVx2cNq0Ed9' },
filterFields: { client: 'Pc8vNm3kTq6Wz2' },
filter: { client: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})
const getMyBooking = createServerFn()
.validator(z.object({ id: z.string() }))
.handler(({ data }) => ds.get(myBookings, { id: data.id }))- The keys of filter are aliases of filterFields, with the same operators as where. Declare the two together. A read returns only fields, so a field that only the filter needs, such as the owner, never reaches the browser. A field that the page shows and the filter reads goes in both. A where names aliases of fields only.
- The keys of one object combine with AND. $and and $or take a list of filters. A filter has at most 4 group levels.
- A get of an id that the filter excludes reads as null, the same as a missing record.
- Write the filter inline, as literals, like the rest of the declaration.
Write a token in the form the Studio condition builder stores:
| Token | Value |
|---|---|
| {USER:::EMAIL}, {USER:::EMAIL_DOMAIN} | The visitor's email, and its domain. With braces |
| USER:::<field id> | A field of the visitor's row in the users table, declared in user.properties. No braces |
| PREDEFINED:TODAY, PREDEFINED:YESTERDAY, PREDEFINED:TOMORROW | That day |
| FIXED_DATE:DAYS_AGO:<n>, FIXED_DATE:DAYS_FROM_NOW:<n> | A day relative to today |
There are no other tokens: a value from the URL, the page or a form goes into a where. A filter can only compare a field of this table: it cannot follow a link to the owner of another table (see A table that belongs to the visitor through its parent).
A link to Users
A link to the users table holds the id of the visitor's row in that table, not context.user.id. Compare it with a Record ID field of the users table:
Find a RECORD_ID field in the users table's datasource doc. When the table has none, add a field of type RECORD_ID to it.
Declare that field in softr.json under user.properties. The key is an alias you choose, and the value is the field id:
json"user": { "properties": { "recordId": "Rk2mVx9pQa4Lz7" } }Compare the link with USER:::<that field id>, here USER:::Rk2mVx9pQa4Lz7.
A token on a field that user.properties does not declare throws. An email field that holds the owner's email compares with {USER:::EMAIL} and needs no declaration. See current-user for user.properties.
A field that holds several values
Compare a field of the visitor that can hold several values, such as a link to their teams, with isOneOf. With is, a visitor in two teams reads no rows.
// 'Tm6cBq1wZe8Ys4' is the teams link of the users table, declared in user.properties.
filter: { team: { isOneOf: ['USER:::Tm6cBq1wZe8Ys4'] } }A field of the record that holds several values takes isOneOf too: members: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } keeps the projects the visitor is a member of.
Signed out, or no value
A condition on a user token matches no rows for a visitor who is signed out, or for a user whose field is empty, such as a user in no team. The read answers an empty list, and a get answers null. In an $or, the other branches still match:
// `ownerEmail` is in filterFields only, so public rows do not show it.
filter: { $or: [{ ownerEmail: { is: '{USER:::EMAIL}' } }, { visibility: { is: 'public' } }] }Every query over the table takes the filter
A privacy rule belongs to the table, not to the page where it came up. Every query that a role reads the table with carries the same filter: the list, the detail, a search, a picker, a count and a chart. This includes a query you add later for a new page or widget. A query without the filter is a second path to the same rows. Reuse the table's queries where you can. A new query with other fields copies filter and filterFields:
// Wrong: no filter. Every client reads every booking through this query.
const nextBookings = defineQuery({
id: 'nextBookings',
datasourceId: '00000000-0000-0000-0000-000000000002',
fields: { date: 'Xp2dLh6vKz9Fa3' },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})
// Right: the same filter as every other query of bookings for clients.
const nextBookings = defineQuery({
id: 'nextBookings',
datasourceId: '00000000-0000-0000-0000-000000000002',
fields: { date: 'Xp2dLh6vKz9Fa3' },
filterFields: { client: 'Pc8vNm3kTq6Wz2' },
filter: { client: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})
const loadNext = createServerFn().handler(() =>
ds.list(nextBookings).where((q) => q.date.gte(new Date().toISOString())).orderBy((q) => q.date.asc).limit(3),
)The update and the delete of these records take the same filter: see record-mutations. A count or a chart reads through the filter of its query: see charts-and-metrics.
One query per role
When roles read a table by different rules, or see different fields of it, declare one query per role. Each one has its own customGroups, fields and filter. A filtered query names the groups of its role in customGroups, never every signed-in user. Only when one rule holds for every signed-in user, keep LOGGED_IN_USERS with no groups. Pick the query on the server by the visitor's groups, never by an argument:
const bookingsForStaff = defineQuery({
id: 'bookingsForStaff',
datasourceId: '00000000-0000-0000-0000-000000000002',
fields: { title: 'Lb7yQe3vXa9Ns1', date: 'Xp2dLh6vKz9Fa3', status: 'Ru7bVx2cNq0Ed9', client: 'Pc8vNm3kTq6Wz2' },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000a'] },
})
const listBookings = createServerFn().handler(async ({ context }) => {
if (!context.user) throw new Error('Not signed in')
if (context.user.userGroupIds.includes('00000000-0000-0000-0000-00000000000a')) {
return await ds.list(bookingsForStaff).limit(50)
}
return await ds.list(myBookings).limit(50)
})bookingsForStaff has no filter: staff read every booking. Its customGroups names staff only, so a client cannot run it.
A list of other people, such as a directory or the members of a chat, declares only the fields its role needs: no email or phone unless the role needs them. Everything a server function returns reaches the browser, also when the page does not show it. A USER field reads back with the person's email, so a list that must not show emails does not declare one either. Here members see names and job titles, and staff see emails too:
const peopleForMembers = defineQuery({
id: 'peopleForMembers',
datasourceId: '00000000-0000-0000-0000-000000000003',
fields: { name: 'Hn4tRw8kPz2Mc5', jobTitle: 'Lb7yQe3vXa9Ns1' },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})
const peopleForStaff = defineQuery({
id: 'peopleForStaff',
datasourceId: '00000000-0000-0000-0000-000000000003',
fields: { name: 'Hn4tRw8kPz2Mc5', jobTitle: 'Lb7yQe3vXa9Ns1', email: 'Td2kWm6pFs8Jq4' },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000a'] },
})A table that belongs to the visitor through its parent
Some tables have no field to compare with the visitor. Chat messages belong to a chat, and only the chat links to its members. A filter on messages cannot say "the messages of my chats", because it cannot follow the link to the chat's members. The same goes for the players of a game room. Only for such a table, read the parent first through its filtered query. Read or post the children only when that read answers, and filter them on the parent that it answered. Here myChats filters chats with members: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] }, and messages has a chat link to chats:
const listMessages = createServerFn()
.validator(z.object({ chatId: z.string() }))
.handler(async ({ data }) => {
const chat = await ds.get(myChats, { id: data.chatId })
if (chat === null) throw new Error('Chat not found')
return await ds
.list(messages)
.where((q) => q.chat.isOneOf([chat.id]))
.orderBy((q) => q.sentAt.desc)
.limit(100)
})Every server function that reads or posts messages reads the chat this way first. The read sorts newest first, so the limit keeps the newest 100 messages. Reverse them in the page to show the oldest on top.
Use this step only when the rule is about the parent. When it is about the row's own owner, such as "a user sees only the requests they sent", the table filters its own link to Users.
Typing
Queries you write are type safe and a type error is shown when there's a mistake. The records a read returns are typed the same way, so never validate them again with a zod schema of your own. A schema guesses each field's shape, and one value it misses, such as a person with no email, throws for the whole read and the page stops loading. Show each field with a fallback instead: record.fields.owner?.name ?? '—'. For an in depth reference on what fields every datasource has, read docs/datasources/README.md first — it lists every registered datasource with a link to its file. Follow those links to get field ids, types, and constraints. Do not guess filenames from table names.
References
- references/filters-and-sorting.md: every filter operator by field type, group nesting and the sort handles. Load it when the operator you want is not in this file, or when a filter is rejected.
- references/field-types.md: the value shape every Softr field type reads back as. Load it when rendering a field whose shape you are unsure of, or when a value is not the string you expected.
- current-user/SKILL.md: reading the visitor off context, and the user.properties a filter compares with
- routes-and-visibility/SKILL.md: deciding who sees the page the records land on
- charts-and-metrics/SKILL.md: aggregating records instead of listing them
- record-mutations/SKILL.md: creating, updating and deleting them