SKILL.md
SKILL.mdBrowse 2 files
4,726 tokens
19,528 bytes
Token encoding: o200k_base
Snapshot 09776a8
1---2name: db-core/live-queries3description: >4 Query builder fluent API: from, where, join, leftJoin, rightJoin, innerJoin,5 fullJoin, select, fn.select, groupBy, having, orderBy, limit, offset, distinct,6 findOne. Operators: eq, gt, gte, lt, lte, like, ilike, inArray, isNull,7 isUndefined, and, or, not. Aggregates: count, sum, avg, min, max. String8 functions: upper, lower, length, concat. Utility: coalesce, caseWhen. Math:9 add, subtract, multiply, divide.10 $selected namespace. createLiveQueryCollection. Derived collections. Predicate push-down.11 Incremental view maintenance via differential dataflow (d2ts). Virtual12 properties ($synced, $origin, $key, $collectionId). Includes subqueries13 for hierarchical data. Collection, toArray, materialize, and14 concat(toArray(...)) include modes.15 queryOnce for one-shot queries. createEffect for reactive side effects16 (onEnter, onUpdate, onExit, onBatch).17type: sub-skill18library: db19library_version: '0.6.17'20sources:21 - 'TanStack/db:docs/guides/live-queries.md'22 - 'TanStack/db:packages/db/src/query/builder/index.ts'23 - 'TanStack/db:packages/db/src/query/compiler/index.ts'24---25 26# Live Queries27 28> This skill builds on db-core.29 30TanStack DB live queries use a SQL-like fluent query builder to create **reactive derived collections** that automatically update when underlying data changes. The query engine compiles queries into incremental view maintenance (IVM) pipelines using differential dataflow (d2ts), so only deltas are recomputed.31 32All operators, string functions, math functions, and aggregates are incrementally maintained. Prefer them over equivalent JS code.33 34## Setup35 36Minimal example using the core API (no framework hooks):37 38```ts39import {40 createCollection,41 createLiveQueryCollection,42 liveQueryCollectionOptions,43 eq,44} from '@tanstack/db'45 46// Assume usersCollection is already created via createCollection(...)47 48// Option 1: createLiveQueryCollection shorthand49const activeUsers = createLiveQueryCollection((q) =>50 q51 .from({ user: usersCollection })52 .where(({ user }) => eq(user.active, true))53 .select(({ user }) => ({54 id: user.id,55 name: user.name,56 email: user.email,57 })),58)59 60// Option 2: full options via liveQueryCollectionOptions61const activeUsers2 = createCollection(62 liveQueryCollectionOptions({63 query: (q) =>64 q65 .from({ user: usersCollection })66 .where(({ user }) => eq(user.active, true))67 .select(({ user }) => ({68 id: user.id,69 name: user.name,70 })),71 getKey: (user) => user.id,72 }),73)74 75// The result is a live collection -- iterate, subscribe, or use as source76for (const user of activeUsers) {77 console.log(user.name)78}79```80 81## Core Patterns82 83### 1. Filtering with where + operators84 85Chain `.where()` calls (ANDed together) using expression operators. Use `and()`, `or()`, `not()` for complex logic.86 87```ts88import { eq, gt, or, and, not, inArray, like } from '@tanstack/db'89 90const results = createLiveQueryCollection((q) =>91 q92 .from({ user: usersCollection })93 .where(({ user }) => eq(user.active, true))94 .where(({ user }) =>95 and(96 gt(user.age, 18),97 or(eq(user.role, 'admin'), eq(user.role, 'moderator')),98 not(inArray(user.id, bannedIds)),99 ),100 ),101)102```103 104Boolean column references work directly:105 106```ts107.where(({ user }) => user.active) // bare boolean ref108.where(({ user }) => not(user.suspended)) // negated boolean ref109```110 111Comparisons follow PostgreSQL semantics. Comparisons involving `null` or112`undefined` are unknown and do not match; use `isNull()` or `isUndefined()`.113`NaN` (and an invalid `Date`) equals itself and sorts after every other114non-null value.115 116### 2. Joining two collections117 118Join conditions **must** use `eq()` (equality only -- IVM constraint). Default join type is `left`. Convenience methods: `leftJoin`, `rightJoin`, `innerJoin`, `fullJoin`.119 120```ts121import { eq } from '@tanstack/db'122 123const userPosts = createLiveQueryCollection((q) =>124 q125 .from({ user: usersCollection })126 .innerJoin({ post: postsCollection }, ({ user, post }) =>127 eq(user.id, post.userId),128 )129 .select(({ user, post }) => ({130 userName: user.name,131 postTitle: post.title,132 })),133)134```135 136Multiple joins:137 138```ts139q.from({ user: usersCollection })140 .join({ post: postsCollection }, ({ user, post }) => eq(user.id, post.userId))141 .join({ comment: commentsCollection }, ({ post, comment }) =>142 eq(post.id, comment.postId),143 )144```145 146### 3. Aggregation with groupBy + having147 148Use `groupBy` to group rows, then aggregate in `select`. Filter groups with `having`. The `$selected` namespace lets `having` and `orderBy` reference fields defined in `select`.149 150```ts151import { count, sum, gt } from '@tanstack/db'152 153const topCustomers = createLiveQueryCollection((q) =>154 q155 .from({ order: ordersCollection })156 .groupBy(({ order }) => order.customerId)157 .select(({ order }) => ({158 customerId: order.customerId,159 totalSpent: sum(order.amount),160 orderCount: count(order.id),161 }))162 .having(({ $selected }) => gt($selected.totalSpent, 1000))163 .orderBy(({ $selected }) => $selected.totalSpent, 'desc')164 .limit(10),165)166```167 168Without `groupBy`, aggregates in `select` treat the entire collection as one group:169 170```ts171const stats = createLiveQueryCollection((q) =>172 q.from({ user: usersCollection }).select(({ user }) => ({173 totalUsers: count(user.id),174 avgAge: avg(user.age),175 })),176)177```178 179### 4. Standalone derived collection with createLiveQueryCollection180 181Derived collections are themselves collections. Use one as a source for another query to cache intermediate results:182 183```ts184// Base derived collection185const activeUsers = createLiveQueryCollection((q) =>186 q.from({ user: usersCollection }).where(({ user }) => eq(user.active, true)),187)188 189// Second query uses the derived collection as its source190const activeUserPosts = createLiveQueryCollection((q) =>191 q192 .from({ user: activeUsers })193 .join({ post: postsCollection }, ({ user, post }) =>194 eq(user.id, post.userId),195 )196 .select(({ user, post }) => ({197 userName: user.name,198 postTitle: post.title,199 })),200)201```202 203Create derived collections once at module scope and reuse them. Do not recreate on every render or navigation.204 205Live query collections default to `gcTime: 5_000`. An explicit `gcTime: 0` is206preserved and disables garbage collection for that derived collection --207including the reclamation of a collection that started syncing and never gained208a subscriber. Note this is the opposite of `gcTime: 0` in TanStack Query, where209it collects as soon as the query goes inactive; use a small positive value if210you want prompt collection here.211 212Sync started without subscribers has a minimum 50ms GC grace period. Pending213`preload()` calls retain the collection until they settle; the unused retention214period then starts. Preloading an already-ready collection refreshes that215period. Explicit `cleanup()` can still abort a pending preload.216 217## Virtual Properties218 219Live query results include computed, read-only virtual properties on every row:220 221- `$synced`: `true` when no pending local optimistic write affects the row;222 `false` while one does. This is local mutation status, not proof that a223 backend uploaded, confirmed, or read back the row.224- `$origin`: `"local"` if the last confirmed change came from this client, otherwise `"remote"`.225- `$key`: the row key for the result.226- `$collectionId`: the source collection ID.227 228These props are added automatically and can be used in `where`, `select`, and `orderBy` clauses. Do not persist them back to storage.229 230## Includes (Subqueries in Select)231 232Embed a correlated subquery inside `select()` to produce hierarchical (nested)233data. The subquery must contain a `where` with an `eq()` that correlates a234parent field with a child field.235 236### Collection includes (default)237 238Return a child `Collection` on each parent row:239 240```ts241import { eq, createLiveQueryCollection } from '@tanstack/db'242 243const projectsWithIssues = createLiveQueryCollection((q) =>244 q.from({ p: projectsCollection }).select(({ p }) => ({245 id: p.id,246 name: p.name,247 issues: q248 .from({ i: issuesCollection })249 .where(({ i }) => eq(i.projectId, p.id))250 .select(({ i }) => ({251 id: i.id,252 title: i.title,253 })),254 })),255)256 257// Each row's `issues` is a live Collection258for (const project of projectsWithIssues) {259 console.log(project.name, project.issues.toArray)260}261```262 263### Array includes with toArray()264 265Wrap the subquery in `toArray()` to get a plain array instead of a Collection:266 267```ts268import { eq, toArray, createLiveQueryCollection } from '@tanstack/db'269 270const messagesWithParts = createLiveQueryCollection((q) =>271 q.from({ m: messagesCollection }).select(({ m }) => ({272 id: m.id,273 contentParts: toArray(274 q275 .from({ c: chunksCollection })276 .where(({ c }) => eq(c.messageId, m.id))277 .orderBy(({ c }) => c.timestamp)278 .select(({ c }) => c.text),279 ),280 })),281)282// row.contentParts is string[]283```284 285### Plain values with materialize()286 287Use `materialize()` when the parent row should hold a plain snapshot rather288than a child collection:289 290```ts291import { eq, materialize, createLiveQueryCollection } from '@tanstack/db'292 293const issuesWithProject = createLiveQueryCollection((q) =>294 q.from({ issue: issuesCollection }).select(({ issue }) => ({295 ...issue,296 project: materialize(297 q298 .from({ project: projectsCollection })299 .where(({ project }) => eq(project.id, issue.projectId))300 .findOne(),301 ),302 })),303)304// row.project is Project | undefined305```306 307For a multi-row subquery, `materialize()` returns `Array<T>` like `toArray()`.308For a subquery ending in `findOne()`, it returns `T | undefined`. In both cases,309the parent row is re-emitted when the child result changes.310 311### Concatenated scalar with concat(toArray())312 313Wrap `toArray()` in `concat()` to join the scalar results into a single string:314 315```ts316import { eq, toArray, concat, createLiveQueryCollection } from '@tanstack/db'317 318const messagesWithContent = createLiveQueryCollection((q) =>319 q.from({ m: messagesCollection }).select(({ m }) => ({320 id: m.id,321 content: concat(322 toArray(323 q324 .from({ c: chunksCollection })325 .where(({ c }) => eq(c.messageId, m.id))326 .orderBy(({ c }) => c.timestamp)327 .select(({ c }) => c.text),328 ),329 ),330 })),331)332// row.content is a single concatenated string333```334 335### Includes rules336 337- The subquery **must** have a `where` clause with an `eq()` correlating a parent alias with a child alias. The library extracts this automatically as the join condition.338- `toArray()` works with both scalar selects (e.g., `select(({ c }) => c.text)` → `string[]`) and object selects (e.g., `select(({ c }) => ({ id: c.id, title: c.title }))` → `Array<{id, title}>`).339- `materialize()` returns an array, or one value for a `findOne()` subquery.340 Like `toArray()`, it must be a top-level value in `select()` and cannot be341 nested inside `coalesce()`, `eq()`, or another expression.342- `concat(toArray())` requires a **scalar** `select` to concatenate into a string.343- Collection includes (bare subquery) require an **object** `select`.344- Includes subqueries are compiled into the same incremental pipeline as the parent query -- they are not separate live queries.345 346## One-Shot Queries with queryOnce347 348For non-reactive, one-time snapshots use `queryOnce`. It creates a live query collection, preloads it, extracts the results, and cleans up automatically.349 350```ts351import { eq, queryOnce } from '@tanstack/db'352 353const activeUsers = await queryOnce((q) =>354 q355 .from({ user: usersCollection })356 .where(({ user }) => eq(user.active, true))357 .select(({ user }) => ({ id: user.id, name: user.name })),358)359 360// With findOne — resolves to T | undefined361const user = await queryOnce((q) =>362 q363 .from({ user: usersCollection })364 .where(({ user }) => eq(user.id, userId))365 .findOne(),366)367```368 369Use `queryOnce` for scripts, loaders, data export, tests, or AI/LLM context building. For UI bindings and reactive updates, use live queries instead.370 371## Reactive Effects (createEffect)372 373Reactive effects respond to query result _changes_ without materializing the full result set. Effects fire callbacks when rows enter, exit, or update within a query result — like a database trigger on an arbitrary live query.374 375```ts376import { createEffect, eq } from '@tanstack/db'377 378const effect = createEffect({379 query: (q) =>380 q381 .from({ msg: messagesCollection })382 .where(({ msg }) => eq(msg.role, 'user')),383 skipInitial: true,384 onEnter: async (event, ctx) => {385 await processNewMessage(event.value, { signal: ctx.signal })386 },387 onExit: (event) => {388 console.log('Message left result set:', event.key)389 },390 onError: (error, event) => {391 console.error(`Failed to process ${event.key}:`, error)392 },393})394 395// Dispose when no longer needed396await effect.dispose()397```398 399| Use case | Approach |400| ------------------------------- | ----------------------------------------------------- |401| Display query results in UI | Live query collection + `useLiveQuery` |402| React to changes (side effects) | `createEffect` with `onEnter` / `onUpdate` / `onExit` |403| Inspect full batch of changes | `createEffect` with `onBatch` |404 405Key options: `id` (optional), `query`, `skipInitial` (skip existing rows on init), `onEnter`, `onUpdate`, `onExit`, `onBatch`, `onError`, `onSourceError`. The `ctx.signal` aborts when the effect is disposed.406 407## Common Mistakes408 409### CRITICAL: Using === instead of eq()410 411JavaScript `===` in a where callback returns a boolean primitive, not an expression object. Throws `InvalidWhereExpressionError`.412 413```ts414// WRONG415q.from({ user: usersCollection }).where(({ user }) => user.active === true)416 417// CORRECT418q.from({ user: usersCollection }).where(({ user }) => eq(user.active, true))419```420 421### CRITICAL: Filtering in JS instead of query operators422 423JS `.filter()` / `.map()` on the result array throws away incremental maintenance -- the JS code re-runs from scratch on every change.424 425```ts426// WRONG -- re-runs filter on every change427const { data } = useLiveQuery({428 query: (q) => q.from({ todos: todosCollection }),429})430const active = data.filter((t) => t.completed === false)431 432// CORRECT -- incrementally maintained433const { data } = useLiveQuery({434 query: (q) =>435 q436 .from({ todos: todosCollection })437 .where(({ todos }) => eq(todos.completed, false)),438})439```440 441### HIGH: Not using the full operator set442 443The library provides string functions (`upper`, `lower`, `length`, `concat`),444math (`add`, `subtract`, `multiply`, `divide`), utility functions (`coalesce`,445`caseWhen`), and aggregates (`count`, `sum`, `avg`, `min`, `max`). All are446incrementally maintained. Prefer them over JS equivalents.447 448```ts449// WRONG450.fn.select((row) => ({451 name: row.user.name.toUpperCase(),452 total: row.order.price + row.order.tax,453}))454 455// CORRECT456.select(({ user, order }) => ({457 name: upper(user.name),458 total: add(order.price, order.tax),459 displayName: coalesce(user.displayName, user.name, 'Unknown'),460}))461```462 463Math expressions also work in `orderBy()`. When a computed expression is used464with `limit()`, lazy-loading optimization is skipped and all matching rows load465before sorting. Literal values such as `Date.now()` are captured when the query466is created; recreate the query when the value must advance.467 468### HIGH: Missing conditional expression helpers469 470Use `coalesce()` for null/undefined fallbacks and `caseWhen()` for conditional471computed fields. JavaScript operators like `||` or ternaries do not build query472expressions inside standard `.select()` callbacks.473 474```ts475// WRONG -- document.title is a query ref, not a runtime string476.select(({ document }) => ({477 displayTitle: document.title || 'Untitled document',478}))479 480// CORRECT -- fallback for null/undefined481.select(({ document }) => ({482 displayTitle: coalesce(document.title, 'Untitled document'),483}))484 485// CORRECT -- fallback for null/undefined and empty string486.select(({ document }) => ({487 displayTitle: caseWhen(488 eq(coalesce(document.title, ''), ''),489 'Untitled document',490 document.title,491 ),492}))493```494 495Use `fn.select()` only when you genuinely need arbitrary JavaScript; it cannot496be optimized like expression-based `.select()`.497 498### HIGH: .distinct() without .select()499 500`distinct()` deduplicates by the selected columns. Without `select()`, throws `DistinctRequiresSelectError`.501 502```ts503// WRONG504q.from({ user: usersCollection }).distinct()505 506// CORRECT507q.from({ user: usersCollection })508 .select(({ user }) => ({ country: user.country }))509 .distinct()510```511 512### HIGH: .having() without .groupBy()513 514`having` filters aggregated groups. Without `groupBy`, there are no groups. Throws `HavingRequiresGroupByError`.515 516```ts517// WRONG518q.from({ order: ordersCollection }).having(({ order }) =>519 gt(count(order.id), 5),520)521 522// CORRECT523q.from({ order: ordersCollection })524 .groupBy(({ order }) => order.customerId)525 .having(({ order }) => gt(count(order.id), 5))526```527 528### HIGH: .limit() / .offset() without .orderBy()529 530Without deterministic ordering, limit/offset results are non-deterministic and cannot be incrementally maintained. Throws `LimitOffsetRequireOrderByError`.531 532```ts533// WRONG534q.from({ user: usersCollection }).limit(10)535 536// CORRECT537q.from({ user: usersCollection })538 .orderBy(({ user }) => user.name)539 .limit(10)540```541 542### HIGH: Join condition using non-eq() operator543 544The differential dataflow join operator only supports equality joins. Using `gt()`, `like()`, etc. throws `JoinConditionMustBeEqualityError`.545 546```ts547// WRONG548q.from({ user: usersCollection }).join(549 { post: postsCollection },550 ({ user, post }) => gt(user.id, post.userId),551)552 553// CORRECT554q.from({ user: usersCollection }).join(555 { post: postsCollection },556 ({ user, post }) => eq(user.id, post.userId),557)558```559 560### MEDIUM: Passing source directly instead of {alias: collection}561 562`from()` and `join()` require sources wrapped as `{alias: collection}`. Passing the collection directly throws `InvalidSourceTypeError`.563 564```ts565// WRONG566q.from(usersCollection)567 568// CORRECT569q.from({ users: usersCollection })570```571 572### MEDIUM: Using unsafe select alias paths573 574Select alias path segments named `__proto__`, `prototype`, or `constructor`575throw `UnsafeAliasPathError`. Use ordinary data-field names; do not suppress576this prototype-pollution guard.577 578## Tension: Query expressiveness vs. IVM constraints579 580The query builder looks like SQL but has constraints that SQL does not:581 582- **Equality joins only** -- `eq()` is the only allowed join condition operator.583- **orderBy required for limit/offset** -- non-deterministic pagination cannot be incrementally maintained.584- **distinct requires select** -- deduplication needs an explicit projection.585- **fn.select() cannot be used with groupBy()** -- the compiler must statically analyze select to discover aggregate functions.586 587These constraints exist because the underlying d2ts differential dataflow engine requires them for correct incremental view maintenance.588 589See also: react-db/SKILL.md for React hooks (`useLiveQuery`, `useLiveSuspenseQuery`, `useLiveInfiniteQuery`).590 591## References592 593- [Query Operators Reference](./references/operators.md) -- full signatures and examples for all operators, functions, and aggregates.594 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.