-
-
Notifications
You must be signed in to change notification settings - Fork 98
feat: add Lazy schema for deferred relationship denormalization #3829
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ntucker
wants to merge
6
commits into
master
Choose a base branch
from
cursor/2-test-case-creation-with-synthetic-data-6097
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,073
−1
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8f62d24
feat: add Lazy schema class for deferred relationship denormalization
cursoragent a066011
test: add comprehensive tests for Lazy schema
cursoragent e0d681c
docs: add API documentation for Lazy schema
cursoragent c1424e7
test: rewrite Lazy tests with full scenario coverage
cursoragent 2c9db86
fix: lint errors and add changeset for Lazy schema
cursoragent d6ce627
fix: LazyQuery.queryKey skips delegation for non-keyed schemas (Array…
cursoragent File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| --- | ||
| '@data-client/endpoint': minor | ||
| '@data-client/rest': minor | ||
| '@data-client/graphql': minor | ||
| --- | ||
|
|
||
| Add [schema.Lazy](https://dataclient.io/rest/api/Lazy) for deferred relationship denormalization. | ||
|
|
||
| `schema.Lazy` wraps a relationship field so denormalization returns raw primary keys | ||
| instead of resolved entities. Use `.query` with [useQuery](/docs/api/useQuery) to | ||
| resolve on demand in a separate memo/GC scope. | ||
|
|
||
| New exports: `schema.Lazy`, `Lazy` | ||
|
|
||
| ```ts | ||
| class Department extends Entity { | ||
| buildings: string[] = []; | ||
| static schema = { | ||
| buildings: new schema.Lazy([Building]), | ||
| }; | ||
| } | ||
|
|
||
| // dept.buildings = ['bldg-1', 'bldg-2'] (raw PKs) | ||
| const buildings = useQuery(Department.schema.buildings.query, dept.buildings); | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| --- | ||
| title: Lazy Schema - Deferred Relationship Denormalization | ||
| sidebar_label: Lazy | ||
| --- | ||
|
|
||
| # Lazy | ||
|
|
||
| `Lazy` wraps a schema to skip eager denormalization of relationship fields. During parent entity denormalization, the field retains its raw normalized value (primary keys/IDs). The relationship can then be resolved on demand via [useQuery](/docs/api/useQuery) using the `.query` accessor. | ||
|
|
||
| This is useful for: | ||
| - **Large bidirectional graphs** that would overflow the call stack during recursive denormalization | ||
| - **Performance optimization** by deferring resolution of relationships that aren't always needed | ||
| - **Memoization isolation** — changes to lazy entities don't invalidate the parent's denormalized form | ||
|
|
||
| ## Constructor | ||
|
|
||
| ```typescript | ||
| new schema.Lazy(innerSchema) | ||
| ``` | ||
|
|
||
| - `innerSchema`: Any [Schema](/rest/api/schema) — an [Entity](./Entity.md), an array shorthand like `[MyEntity]`, a [Collection](./Collection.md), etc. | ||
|
|
||
| ## Usage | ||
|
|
||
| ### Array relationship (most common) | ||
|
|
||
| ```typescript | ||
| import { Entity, schema } from '@data-client/rest'; | ||
|
|
||
| class Building extends Entity { | ||
| id = ''; | ||
| name = ''; | ||
| } | ||
|
|
||
| class Department extends Entity { | ||
| id = ''; | ||
| name = ''; | ||
| buildings: string[] = []; | ||
|
|
||
| static schema = { | ||
| buildings: new schema.Lazy([Building]), | ||
| }; | ||
| } | ||
| ``` | ||
|
|
||
| When a `Department` is denormalized, `dept.buildings` will contain raw primary keys (e.g., `['bldg-1', 'bldg-2']`) instead of resolved `Building` instances. | ||
|
|
||
| To resolve the buildings, use [useQuery](/docs/api/useQuery) with the `.query` accessor: | ||
|
|
||
| ```tsx | ||
| function DepartmentBuildings({ dept }: { dept: Department }) { | ||
| // dept.buildings contains raw IDs: ['bldg-1', 'bldg-2'] | ||
| const buildings = useQuery(Department.schema.buildings.query, dept.buildings); | ||
| // buildings: Building[] | undefined | ||
|
|
||
| if (!buildings) return null; | ||
| return ( | ||
| <ul> | ||
| {buildings.map(b => <li key={b.id}>{b.name}</li>)} | ||
| </ul> | ||
| ); | ||
| } | ||
| ``` | ||
|
|
||
| ### Single entity relationship | ||
|
|
||
| ```typescript | ||
| class Department extends Entity { | ||
| id = ''; | ||
| name = ''; | ||
| mainBuilding = ''; | ||
|
|
||
| static schema = { | ||
| mainBuilding: new schema.Lazy(Building), | ||
| }; | ||
| } | ||
| ``` | ||
|
|
||
| ```tsx | ||
| // dept.mainBuilding is a raw PK string: 'bldg-1' | ||
| const building = useQuery( | ||
| Department.schema.mainBuilding.query, | ||
| { id: dept.mainBuilding }, | ||
| ); | ||
| ``` | ||
|
|
||
| When the inner schema is an [Entity](./Entity.md) (or any schema with `queryKey`), `LazyQuery` delegates to its `queryKey` — so you pass the same args you'd use to query that entity directly. | ||
|
|
||
| ### Collection relationship | ||
|
|
||
| ```typescript | ||
| class Department extends Entity { | ||
| id = ''; | ||
| static schema = { | ||
| buildings: new schema.Lazy(buildingsCollection), | ||
| }; | ||
| } | ||
| ``` | ||
|
|
||
| ```tsx | ||
| const buildings = useQuery( | ||
| Department.schema.buildings.query, | ||
| ...collectionArgs, | ||
| ); | ||
| ``` | ||
|
|
||
| ## `.query` | ||
|
|
||
| Returns a `LazyQuery` instance suitable for [useQuery](/docs/api/useQuery). The `LazyQuery`: | ||
|
|
||
| - **`queryKey(args)`** — If the inner schema has a `queryKey` (Entity, Collection, etc.), delegates to it. Otherwise returns `args[0]` directly (for array/object schemas where you pass the raw normalized value). | ||
| - **`denormalize(input, args, unvisit)`** — Delegates to the inner schema, resolving IDs into full entity instances. | ||
|
|
||
| The `.query` getter always returns the same instance (cached). | ||
|
|
||
| ## How it works | ||
|
|
||
| ### Normalization | ||
|
|
||
| `Lazy.normalize` delegates to the inner schema. Entities are stored in the normalized entity tables as usual — `Lazy` has no effect on normalization. | ||
|
|
||
| ### Denormalization (parent path) | ||
|
|
||
| `Lazy.denormalize` is a **no-op** — it returns the input unchanged. When `EntityMixin.denormalize` iterates over schema fields and encounters a `Lazy` field, the `unvisit` dispatch calls `Lazy.denormalize`, which simply passes through the raw PKs. No nested entities are visited, no dependencies are registered in the cache. | ||
|
|
||
| ### Denormalization (useQuery path) | ||
|
|
||
| When using `useQuery(lazyField.query, ...)`, `LazyQuery.denormalize` delegates to the inner schema via `unvisit`, resolving IDs into full entity instances through the normal denormalization pipeline. This runs in its own `MemoCache.query()` scope with independent dependency tracking and GC. | ||
|
|
||
| ## Performance characteristics | ||
|
|
||
| - **Parent denormalization**: Fewer dependency hops (lazy entities excluded from deps). Faster cache hits. No invalidation when lazy entities change. | ||
| - **useQuery access**: Own memo scope with own `paths` and `countRef`. Changes to lazy entities only re-render components that called `useQuery`, not the parent. | ||
| - **No Proxy/getter overhead**: Raw IDs are plain values. Full resolution only happens through `useQuery`, using the normal denormalization path. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| import type { Schema, SchemaSimple } from '../interface.js'; | ||
| import type { | ||
| Denormalize, | ||
| DenormalizeNullable, | ||
| NormalizeNullable, | ||
| } from '../normal.js'; | ||
|
|
||
| /** | ||
| * Skips eager denormalization of a relationship field. | ||
| * Raw normalized values (PKs/IDs) pass through unchanged. | ||
| * Use `.query` with `useQuery` to resolve lazily. | ||
| * | ||
| * @see https://dataclient.io/rest/api/Lazy | ||
| */ | ||
| export default class Lazy<S extends Schema> implements SchemaSimple { | ||
| declare schema: S; | ||
|
|
||
| /** | ||
| * @param {Schema} schema - The inner schema (e.g., [Building], Building, Collection) | ||
| */ | ||
| constructor(schema: S) { | ||
| this.schema = schema; | ||
| } | ||
|
|
||
| normalize( | ||
| input: any, | ||
| parent: any, | ||
| key: any, | ||
| args: any[], | ||
| visit: (...args: any) => any, | ||
| _delegate: any, | ||
| ): any { | ||
| return visit(this.schema, input, parent, key, args); | ||
| } | ||
|
|
||
| denormalize(input: {}, _args: readonly any[], _unvisit: any): any { | ||
| return input; | ||
| } | ||
|
|
||
| queryKey( | ||
| _args: readonly any[], | ||
| _unvisit: (...args: any) => any, | ||
| _delegate: any, | ||
| ): undefined { | ||
| return undefined; | ||
| } | ||
|
|
||
| /** Queryable schema for use with useQuery() to resolve lazy relationships */ | ||
| get query(): LazyQuery<S> { | ||
| if (!this._query) { | ||
| this._query = new LazyQuery(this.schema); | ||
| } | ||
| return this._query; | ||
| } | ||
|
|
||
| private _query: LazyQuery<S> | undefined; | ||
|
|
||
| declare _denormalizeNullable: ( | ||
| input: {}, | ||
| args: readonly any[], | ||
| unvisit: (schema: any, input: any) => any, | ||
| ) => any; | ||
|
|
||
| declare _normalizeNullable: () => NormalizeNullable<S>; | ||
| } | ||
|
|
||
| /** | ||
| * Resolves lazy relationships via useQuery(). | ||
| * | ||
| * queryKey delegates to inner schema's queryKey if available, | ||
| * otherwise passes through args[0] (the raw normalized value). | ||
| */ | ||
| export class LazyQuery<S extends Schema> implements SchemaSimple< | ||
| Denormalize<S>, | ||
| readonly any[] | ||
| > { | ||
| declare schema: S; | ||
|
|
||
| constructor(schema: S) { | ||
| this.schema = schema; | ||
| } | ||
|
|
||
| normalize( | ||
| input: any, | ||
| _parent: any, | ||
| _key: any, | ||
| _args: any[], | ||
| _visit: (...args: any) => any, | ||
| _delegate: any, | ||
| ): any { | ||
| return input; | ||
| } | ||
|
|
||
| denormalize( | ||
| input: {}, | ||
| args: readonly any[], | ||
| unvisit: (schema: any, input: any) => any, | ||
| ): Denormalize<S> { | ||
| return unvisit(this.schema, input); | ||
| } | ||
|
|
||
| queryKey( | ||
| args: readonly any[], | ||
| unvisit: (...args: any) => any, | ||
| delegate: { getEntity: any; getIndex: any }, | ||
| ): any { | ||
| const schema = this.schema as any; | ||
| if (typeof schema.queryKey === 'function' && schema.key) { | ||
| return schema.queryKey(args, unvisit, delegate); | ||
| } | ||
| return args[0]; | ||
| } | ||
|
|
||
| declare _denormalizeNullable: ( | ||
| input: {}, | ||
| args: readonly any[], | ||
| unvisit: (schema: any, input: any) => any, | ||
| ) => DenormalizeNullable<S>; | ||
|
|
||
| declare _normalizeNullable: () => NormalizeNullable<S>; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.