Extensions
$extend layers virtuals and omit onto a new client without changing the original; both share the adapter's connections. Connection and runtime options stay on createClient.
Extending
const db = createClient({ connection: "mysql://root:test_password@127.0.0.1:3306/app" });
const extended = db.$extend({
virtuals: {
user: {
displayName: {
needs: { name: true, email: true },
compute: (row) => row.name ?? row.email,
},
},
},
omit: { user: { name: true } },
});
const rows = await extended.user.findMany();
rows[0].displayName; // computed on the client2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| Option | Description |
|---|---|
virtuals | Virtual fields added on top of the ones already configured |
omit | Global omit entries layered on top of the current ones |
The compute argument of an inline definition is typed as the full model row, but only needs fields are exposed at runtime; see Virtual Fields.
omit suits fields that should never be returned by default, such as password hashes. It applies to every method that returns records (and nested relations); bring fields back with query-level select or omit: { field: false }. Filtering, ordering, and unique lookups are unaffected:
const db = createClient({ connection: "mysql://root:test_password@127.0.0.1:3306/app" }).$extend({
omit: { user: { name: true } },
});
await db.user.findUnique({ where: { id: 1 } }); // without name
await db.user.findUnique({ where: { id: 1 }, omit: { name: false } });2
3
4
5
Semantics
- Layered, not replaced. New entries are added on top of the current ones; redefining a virtual field name overrides the earlier definition.
- Immutable. The original client keeps its own behavior; queries on
dbnever returndisplayName. - Chainable. Every
$extendcall returns another client, so modules can layer independently (sharedis defined in Virtual Fields):
const withShared = db.$extend({ virtuals: { user: shared, post: shared } });
const withProfile = withShared.$extend({ omit: { user: { name: true } } });2
- Validated per model.
needsis checked against physical scalar fields when$extendis called; a missing field or a dependency on another virtual field is an error.
Internal relation checks retain physical keys regardless of global omission.
Shared Lifecycle
An extended client shares connections, logging, and lifecycle state with the original:
- Queries on the extended client inside a
$transactioncallback join the same transaction and roll back with it, and$closeon either client closes the connection for all of them.
await db.$transaction(async () => {
await extended.user.create({ data: { email: "in-tx@example.com" } });
}); // extended-client writes belong to the transaction
await extended.$close(); // closes db too2
3
4
Next Steps
- Virtual Fields: defining and sharing computed fields
- Client Overview: the options a base client is created with