Skip to content

Commit 7979a01

Browse files
authored
doc: v2 to v3 migration guide (#503)
* doc: v2 to v3 migration guide * updates * update * update * update
1 parent fbf6940 commit 7979a01

File tree

7 files changed

+365
-19
lines changed

7 files changed

+365
-19
lines changed

src/pages/index.tsx

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,19 @@ function Header() {
3232
A TypeScript toolkit that enhances Prisma ORM with flexible Authorization and
3333
auto-generated, type-safe APIs/hooks, simplifying full-stack development
3434
</p>
35-
<div className={styles.buttons}>
35+
<div className="flex flex-wrap justify-center gap-4">
3636
<Link
3737
className="button button--secondary button--lg lg:text-2xl lg:px-8 lg:py-4"
3838
to="/docs/welcome"
3939
>
4040
Get Started →
4141
</Link>
42+
<a
43+
href="/v3"
44+
className="button button--outline button--lg border-solid lg:text-2xl lg:px-8 lg:py-4 hover:text-gray-200 dark:hover:text-gray-600"
45+
>
46+
Check V3 Beta
47+
</a>
4248
</div>
4349
</div>
4450
</div>

versioned_docs/version-3.x/migrate-prisma.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ export const db = new ZenStackClient(schema, {
260260

261261
A key difference is that ZenStack's computed fields are evaluated on the database side, which much more efficient and flexible than client-side computation. Read more in the [Computed Fields](./orm/computed-fields.md) documentation.
262262

263-
## Feature Gap
263+
## Feature Gaps
264264

265265
Here's a list of Prisma features that are not supported in ZenStack v3:
266266

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,257 @@
1+
---
2+
description: How to migrate from a ZenStack v2 project to v3
3+
sidebar_position: 11
4+
---
5+
6+
import PackageInstall from './_components/PackageInstall';
7+
8+
# Migrating From ZenStack V2
9+
10+
## Overview
11+
12+
ZenStack v3 is a major rewrite of v2, with a focus on simplicity and flexibility. It replaced Prisma ORM with its own ORM component built on top of [Kysely](https://kysely.dev/), resulting in a much more lighter-weight architecture and the level of extensibility that we couldn't achieve in v2.
13+
14+
A few v3 design decisions should make an upgrade much less painful:
15+
16+
- The ZModel schema is compatible with v2.
17+
- The ORM query API is compatible with that of `PrismaClient`, thus compatible with v2.
18+
19+
However, given the architectural changes, some effort is required to adapt to the new system. This guide will help you migrate an existing ZenStack v2 project.
20+
21+
## Compatibility Check
22+
23+
Here are a few essential items to verify before preparing your migration:
24+
25+
- Database support
26+
27+
V3 currently only supports PostgreSQL and SQLite databases. MySQL will be added later.
28+
29+
For PostgreSQL, only the traditional TCP-based connection is supported. Newer HTTP-based protocols, such as those supported by providers like Neon and Prisma PG, are not yet supported, but will be in the future.
30+
31+
- Prisma feature gaps
32+
33+
A few Prisma ORM's features are not implemented or not planned. Please check the [Prisma Feature Gaps](./migrate-prisma.md#feature-gaps) for details.
34+
35+
- V2 feature gaps
36+
37+
A few ZenStack v2 features are not implemented. Some less popular features are planned to be removed. Please check the [Feature Gaps](#feature-gaps) for details.
38+
39+
## Migrating Prisma
40+
41+
Since ZenStack v3 is no longer based on Prisma ORM, the first step is to replace Prisma dependencies with ZenStack and update the code where `PrismaClient` is created. Please follow the [Prisma Migration Guide](./migrate-prisma.md) for detailed instructions.
42+
43+
## Migrating ZModel
44+
45+
### Access Control
46+
47+
Access control functionality has been moved into a self-contained plugin. You need to install the package, add a plugin declaration in ZModel, and then use the plugin at runtime.
48+
49+
1. Install the package
50+
51+
<PackageInstall dependencies={["@zenstackhq/plugin-policy"]} />
52+
53+
2. Add a plugin declaration in ZModel
54+
55+
```zmodel title="schema.zmodel"
56+
57+
// adding the plugin makes attributes like `@@allow` and `@@deny` work
58+
plugin policy {
59+
provider = '@zenstackhq/plugin-policy'
60+
}
61+
62+
```
63+
64+
3. Install the plugin at runtime
65+
66+
```ts title="db.ts"
67+
import { PolicyPlugin } from '@zenstackhq/plugin-policy';
68+
69+
// ORM client without access control
70+
export const db = new ZenStackClient({ ... });
71+
72+
// ORM client with access control
73+
export const authDb = db.$use(new PolicyPlugin());
74+
```
75+
76+
When you need to query the database with a specific user identity, call the `$setAuth()` method on the ORM client (with the access policy plugin installed) to get a user-bound instance.
77+
78+
```ts
79+
async function processRequest(request: Request) {
80+
// get the validated user identity from your auth system
81+
const user = await getCurrentUser(request);
82+
83+
// create a user-bound ORM client
84+
const userDb = authDb.$setAuth(user);
85+
86+
// process the request with `userDb`
87+
...
88+
}
89+
```
90+
91+
The policy rules in ZModel are mostly backward compatible, except for a breaking change about post-update policies. In v3, post-update rules are expressed with their own "post-update" policy type and separate from regular "update" rules. Inside "post-update" rules, by default, fields refer to the entity's "after-update" state, and you can use the `before()` function to refer to the "before-update" state. See [Post Update Rules](./orm/access-control/post-update.md) for more details.
92+
93+
Here's a quick example for how to migrate:
94+
95+
V2:
96+
97+
```zmodel
98+
model Post {
99+
...
100+
ownerId Int
101+
owner User @relation(fields: [ownerId], references: [id])
102+
103+
// update is not allowed to change the owner
104+
@@deny('update', future().ownerId != ownerId)
105+
}
106+
```
107+
108+
V3:
109+
```zmodel
110+
model Post {
111+
...
112+
ownerId Int
113+
owner User @relation(fields: [ownerId], references: [id])
114+
115+
// update is not allowed to change the owner
116+
@@deny('post-update', ownerId != before().ownerId)
117+
}
118+
```
119+
120+
### Abstract Base Models
121+
122+
V2 had the concept of [Abstract Model](/docs/guides/multiple-schema#abstract-model-inheritance) that allows you to define base models that serve purely as base types, but are not mapped to the database. You can use the `extends` keyword to inherit from an abstract model. We found this to be confusing because `extends` is also used for inheriting from a [Polymorphic Model](/docs/guides/polymorphism). The same keyword was used for two very different concepts.
123+
124+
In v3, abstract models are replaced with "types", and the concept of "abstract inheritance" is replaced with [Mixins](./modeling/mixin.md). What you need to do is to change `abstract model` to `type`, and change the `extends` keyword to `with`.
125+
126+
V2:
127+
128+
```zmodel
129+
abstract model Timestamped {
130+
createdAt DateTime @default(now())
131+
updatedAt DateTime @updatedAt
132+
}
133+
134+
model Post extends Timestamped {
135+
id Int @id @default(autoincrement())
136+
title String
137+
}
138+
```
139+
140+
V3:
141+
142+
```zmodel
143+
type Timestamped {
144+
createdAt DateTime @default(now())
145+
updatedAt DateTime @updatedAt
146+
}
147+
148+
model Post with Timestamped {
149+
id Int @id @default(autoincrement())
150+
title String
151+
}
152+
```
153+
154+
## Migrating Server Adapters
155+
156+
Server adapters are mostly backward compatible. One small change needed is that, when creating a server adapter, it's now mandatory to explicitly pass in an API handler instance (RPC or RESTful). The API handlers are now created with the `schema` object as input. See [Server Adapters](./service/server-adapter.md) for more details.
157+
158+
Here's an example with Express.js:
159+
160+
```ts
161+
import { schema } from '~/zenstack/schema';
162+
import { authDb } from '~/db';
163+
164+
app.use(
165+
'/api/model',
166+
ZenStackMiddleware({
167+
// an API handler needs to be explicitly passed in
168+
apiHandler: new RPCApiHandler({ schema }),
169+
170+
// `getPrisma` is renamed to `getClient` in v3
171+
getClient: (request) => getClientForRequest(request),
172+
})
173+
);
174+
175+
function getClientForRequest(request: Request) {
176+
const user = getCurrentUser(request);
177+
return authDb.$setAuth(user);
178+
}
179+
```
180+
181+
## Migrating Client-Side Hooks
182+
183+
V3 introduces a new implementation of [TanStack Query](https://tanstack.com/query) implementation that doesn't require code generation. Instead, TS types are fully inferred from the schema type at compile time, and the runtime logic is based on the interpretation of the schema object. As a result, the new integration becomes a simple library that you call, and no plugin is involved.
184+
185+
To support such an architecture change. Query hooks are now grouped into an object that mirrors the API style of the ORM client. You need to adjust the v2 code (that uses the flat `useFindMany[Model]` style hooks) into this new structure.
186+
187+
V2:
188+
```ts
189+
import { useFindManyUser } from '~/hooks';
190+
191+
export function MyComponent() {
192+
const { data } = useFindManyUser({ ... });
193+
...
194+
}
195+
```
196+
197+
V3:
198+
```ts
199+
import { useClientQueries } from '@zenstackhq/tanstack-query';
200+
import { schema } from '~/zenstack/schema';
201+
202+
export function MyComponent() {
203+
const client = useClientQueries(schema);
204+
const { data } = client.user.useFindMany({ ... });
205+
...
206+
}
207+
```
208+
209+
[SWR](https://swr.vercel.app/) support has been dropped due to low popularity.
210+
211+
## Migration Custom Plugins
212+
213+
V3 comes with a completely revised plugin system that offers greater power and flexibility. You can check the concepts in the [Data Model Plugin](./modeling/plugin.md) and [ORM Plugin](./orm/plugins/) documentation.
214+
215+
The plugin development document is still WIP. This part of the migration guide will be added later when it's ready.
216+
217+
## Feature Gaps
218+
219+
This section lists v2 features that haven't been migrated to v3 yet, or that are planned to be removed in v3. Please feel free to share your thoughts about these decisions in [Discord](https://discord.gg/Ykhr738dUe), and we'll be happy to discuss them.
220+
221+
### Automatic password hashing
222+
223+
The `@password` attribute is removed in v3. We believe most people will use a more sophisticated authentication system than a simple id/password mechanism.
224+
225+
### Field-level access control
226+
227+
Not supported yet, but will be added soon with some design changes.
228+
229+
### Data encryption
230+
231+
Not supported yet, but will be added soon.
232+
233+
### Zod integration
234+
235+
Not supported yet, but will be added soon with some design changes.
236+
237+
### Checking permissions without querying the database
238+
239+
The [check()](/docs/guides/check-permission) feature is removed due to low popularity.
240+
241+
### tRPC integration
242+
243+
[TRPC](https://trpc.io/) is TypeScript-inference heavy, and stacking it over ZenStack generates additional complexities and pressure on the compiler. We're evaluating the best way to integrate it in v3, and no concrete plan is in place yet. At least there's no plan to migrate the code-generation-based approach in v2 directly.
244+
245+
### OpenAPI spec generation
246+
247+
The [OpenAPI plugin](/docs/reference/plugins/openapi) has not migrated to v3 yet and will be added later with some redesign.
248+
249+
### SWR integration
250+
251+
The [SWR plugin](https://swr.vercel.app/) is removed due to low popularity.
252+
253+
## FAQ
254+
255+
### Is data migration needed?
256+
257+
No. From the database schema point of view, v3 is fully backward-compatible with v2.

0 commit comments

Comments
 (0)