Computed Fields
🔋 ZenStack vs Prisma
Prisma client extensions allow you to define computed fields. ZenStack's approach is very different in two aspects:
- Computed fields are evaluated on the database side, not in the client.
- Computed fields are defined in the schema and can be used in most places where regular fields are used.
Computed fields are "virtual" fields that do not physically exist in the database. They are computed on the fly, but other than that, they behave like regular fields. They are returned as part of the query results, can be used for filtering, sorting, etc., and can be used to define access policies.
Defining Computed Fields​
Defining a computed fields involves two steps. First, add the field in the ZModel schema to a model and annotate it with an extra @computed
attribute.
model User {
...
postCount Int @computed
}
Then, when creating a ZenStackClient
, provide the implementation of the field using the Kysely query builder.
import { ZenStackClient } from '@zenstackhq/runtime';
const db = new ZenStackClient(schema, {
...
computedFields: {
User: {
postCount: (eb) =>
eb.selectFrom('Post')
.whereRef('Post.authorId', '=', 'User.id')
.select(({fn}) => fn.countAll<number>().as('count')),
},
},
});
Samples​
- Interactive Sample
- Plain Code
Click here to pop out if the embed doesn't load an interactive terminal.
computed-fields.ts
Loading...