Skip to content

Latest commit

 

History

History
1321 lines (814 loc) · 60.5 KB

File metadata and controls

1321 lines (814 loc) · 60.5 KB

@tanstack/query-db-collection

1.2.8

Patch Changes

1.2.7

Patch Changes

  • Propagate initial query sync failures through dependent live queries and readiness promises, including recovery and late subscribers, while preserving a ready cached snapshot on later refetch failures. Let sync adapters pass the original failure to markError(error) so readiness promises reject with that cause. Isolate adapter callbacks by sync session, preserve synchronous startup errors, and prevent rejected deduplicated subset requests from creating detached promise rejections. (#1751)

  • Updated dependencies [c521b5d]:

    • @tanstack/db@0.8.2

1.2.6

Patch Changes

  • Rebuild correlated include materialization as one D2 graph, fixing stale or missing nested results across route changes, batching, lazy loading, optimistic updates, and layered queries. Add canonical structural relation keys, abortable subset demand, and coherent publication for Collection-valued includes. Dispose delayed PowerSync subset hooks after cleanup, and prevent released Query Collection cache results from reaching the collection. (#1740)

  • Updated dependencies [5d9335d, a20352a]:

    • @tanstack/db@0.8.1

1.2.5

Patch Changes

  • Add SSR through request-scoped DbClient instances, collection descriptors, (#1564) explicit collection-row hydration, live-query result snapshots, adapter sync metadata, and React and Svelte descriptor resolution.

    React live queries now derive identity from structured query IR. Opaque queries can provide queryKey; legacy dependency arrays and unkeyed opaque queries keep working with development warnings until 1.0.

    Add TanStack Router integration that streams live queries discovered during a Suspense render as pending promises which resolve to ordered result snapshots. The browser starts normal source sync and atomically replaces the snapshot when its live result is ready.

  • Updated dependencies [4b9e8cd]:

    • @tanstack/db@0.8.0

1.2.4

Patch Changes

  • Updated dependencies [5f63996]:
    • @tanstack/db@0.7.2

1.2.3

Patch Changes

  • Updated dependencies [424382b]:
    • @tanstack/db@0.7.1

1.2.2

Patch Changes

1.2.1

Patch Changes

  • Updated dependencies [8ee783d]:
    • @tanstack/db@0.6.17

1.2.0

Minor Changes

  • Add eager collection support for TanStack Query initialData and initialDataUpdatedAt, including wrapped response projection and collection-local initialization on shared QueryClient instances. (#1683)

    QueryClient-default placeholderData no longer materializes as collection rows, and QueryClient-default initialData no longer seeds on-demand subset observers.

Patch Changes

  • Clean up empty query ownership state while preserving authoritative empty results and retained-row lifecycle behavior. (#1672)

1.1.0

Minor Changes

  • Add top-level Query Collection support for additional Query observer options while preserving QueryClient defaultOptions behavior. (#1665)

Patch Changes

  • Fix temporary query readiness listeners so subset unload and collection cleanup release them correctly during in-flight requests. (#1673)

  • Extract internal query row ownership helpers to make lifecycle cleanup paths easier to reason about while preserving existing behavior. (#1664)

  • Updated dependencies [8258d09, 286964d]:

    • @tanstack/db@0.6.16

1.0.48

Patch Changes

  • Clarify that select extracts rows for DB materialization while preserving the wrapped TanStack Query cache response. (#1654)

  • Document the current TanStack Query option compatibility surface for Query Collections, including forwarded options, QueryClient defaults, adapter-owned fields, and common options that are not currently exposed. (#1653)

  • Add coverage for query invalidation behavior across eager and on-demand query collections. (#1655)

  • Updated dependencies [eabcea7, 6d4c096]:

    • @tanstack/db@0.6.15

1.0.47

Patch Changes

  • Keep on-demand load subset subscription state out of TanStack Query metadata so dehydrated query state remains safe to persist with structured-clone based persisters. (#1644)

1.0.46

Patch Changes

  • Updated dependencies [397e12a]:
    • @tanstack/db@0.6.14

1.0.45

Patch Changes

1.0.44

Patch Changes

  • Updated dependencies [2b27dd1]:
    • @tanstack/db@0.6.12

1.0.43

Patch Changes

1.0.42

Patch Changes

  • Updated dependencies [307fdf8]:
    • @tanstack/db@0.6.10

1.0.41

Patch Changes

1.0.40

Patch Changes

  • Forward gcTime from queryCollectionOptions to the underlying TanStack Query observer. The gcTime option was previously documented in the config shape but silently dropped before reaching the observer, leaving consumers stuck on the queryClient default. Closes #1546. (#1568)

1.0.39

Patch Changes

  • Updated dependencies [3827b62]:
    • @tanstack/db@0.6.8

1.0.38

Patch Changes

1.0.37

Patch Changes

  • Updated dependencies [4e9ab39]:
    • @tanstack/db@0.6.6

1.0.36

Patch Changes

1.0.35

Patch Changes

  • Updated dependencies [1e69dd6]:
    • @tanstack/db@0.6.4

1.0.34

Patch Changes

1.0.33

Patch Changes

1.0.32

Patch Changes

  • Updated dependencies [8b7fb1a]:
    • @tanstack/db@0.6.1

1.0.31

Patch Changes

  • fix: prevent stale query refreshes from overwriting optimistic offline changes on reconnect (#1390)

    When reconnecting with pending offline transactions, query-backed collections now defer processing query refreshes until queued writes finish replaying, avoiding temporary reverts to stale server data.

  • fix: default persisted query retention to gcTime when omitted (#1400)

    When persistedGcTime is not provided, query collections now use the query's effective gcTime as the persisted retention TTL. This prevents unexpectedly early cleanup of persisted rows.

  • fix: Prevent stale query cache from re-inserting deleted items when a destroyed observer is recreated with gcTime > 0. (#1387)

  • Updated dependencies [f60384b, b8abc02, 09c7afc, bb09eb1, 179d666, 43ecbfa, 055fd94, 055fd94, 055fd94, 055fd94, 85f5435, b65d8f7, e0df07e, 9952921, d351c67]:

    • @tanstack/db@0.6.0

1.0.30

Patch Changes

  • Updated dependencies [c3e6a96]:
    • @tanstack/db@0.5.33

1.0.29

Patch Changes

1.0.28

Patch Changes

  • Updated dependencies [bf1d078]:
    • @tanstack/db@0.5.31

1.0.27

Patch Changes

  • Updated dependencies [e9d0fd8]:
    • @tanstack/db@0.5.30

1.0.26

Patch Changes

  • Improve queryCollectionOptions type compatibility with TanStack Query option objects. (#1289)

    • Accept queryFn return types of T | Promise<T> instead of requiring Promise<T>.
    • Align enabled, staleTime, refetchInterval, retry, and retryDelay with QueryObserverOptions typing.
    • Support tagged queryKey values (DataTag) from queryOptions(...) spread usage.
    • Preserve runtime safety: query collections still require an executable queryFn, and wrapped responses still require select.
  • Updated dependencies [77b815e, ac4ce67]:

    • @tanstack/db@0.5.29

1.0.25

Patch Changes

  • Updated dependencies [46450e7]:
    • @tanstack/db@0.5.28

1.0.24

Patch Changes

1.0.23

Patch Changes

  • Make loadSubsetOptions optional in QueryCollectionMeta to fix query-core interface pollution (#1061) (#1238)

  • Updated dependencies [85c373e, 9184dcc, 83d5ac8]:

    • @tanstack/db@0.5.26

1.0.22

Patch Changes

  • Fix isReady tracking for on-demand live queries without orderBy. Previously, non-ordered live queries using syncMode: 'on-demand' were incorrectly marked as ready before data finished loading. Also fix preload() promises hanging when cleanup occurs before the collection becomes ready. Additionally, fix concurrent live queries subscribing to the same source collection - each now independently tracks loading state. (#1192)

  • Updated dependencies [43c7c9d, 284ebcc]:

    • @tanstack/db@0.5.25

1.0.21

Patch Changes

  • Updated dependencies [7099459]:
    • @tanstack/db@0.5.24

1.0.20

Patch Changes

  • Updated dependencies [05130f2]:
    • @tanstack/db@0.5.23

1.0.19

Patch Changes

  • Fix updating all active query caches on directWrite for on-demand collections.Previously directWrite operations (e.g. writeUpdate/writeInsert) only updated the cache at the base query key for on-demand collections, leading to stale data when components remounted. This change ensures all active query cache keys are updated so data persists correctly. (#1155)

  • Updated dependencies [f9b741e]:

    • @tanstack/db@0.5.22

1.0.18

Patch Changes

  • Fix syncedData not updating when manual write operations (writeUpsert, writeInsert, etc.) are called after async operations in mutation handlers. Previously, the sync transaction would be blocked by the persisting user transaction, leaving syncedData stale until the next sync cycle. (#1130)

  • Updated dependencies [6745ed0, 1b22e40, 7a2cacd, bdf9405]:

    • @tanstack/db@0.5.21

1.0.17

Patch Changes

  • Fix refetch such that it returns the query observer results instead of undefined. (#1132)

1.0.16

Patch Changes

  • Updated dependencies []:
    • @tanstack/db@0.5.20

1.0.15

Patch Changes

1.0.14

Patch Changes

  • Updated dependencies [c1247e8]:
    • @tanstack/db@0.5.18

1.0.13

Patch Changes

  • Fix on-demand sync behavior so the full TanStack Query lifecycle is respected. (#1007)

    This patch resolves an issue where using on-demand synchronization could break the query lifecycle, including the error reported in #998.

  • Updated dependencies [f795a67, d542667, 6503c09, b1cc4a7]:

    • @tanstack/db@0.5.17

1.0.12

Patch Changes

  • Updated dependencies [41308b8]:
    • @tanstack/db@0.5.16

1.0.11

Patch Changes

  • Updated dependencies [32ec4d8]:
    • @tanstack/db@0.5.15

1.0.10

Patch Changes

  • Updated dependencies [26ed0aa]:
    • @tanstack/db@0.5.14

1.0.9

Patch Changes

1.0.8

Patch Changes

  • Fix writeInsert/writeUpsert throwing error when collection uses select option (#1023)

    When a Query Collection was configured with a select option to extract items from a wrapped API response (e.g., { data: [...], meta: {...} }), calling writeInsert() or writeUpsert() would corrupt the query cache and trigger the error: "select() must return an array of objects".

    The fix routes cache updates through a new updateCacheData function that preserves the wrapper structure by using the select function to identify which property contains the items array (via reference equality), then updates only that property while keeping metadata intact.

1.0.7

Patch Changes

  • Enhanced LoadSubsetOptions with separate cursor expressions and offset for flexible pagination. (#960)

    ⚠️ Breaking Change for Custom Sync Layers / Query Collections:

    LoadSubsetOptions.where no longer includes cursor expressions for pagination. If you have a custom sync layer or query collection that implements loadSubset, you must now handle pagination separately:

    • Cursor-based pagination: Use the new cursor property (cursor.whereFrom and cursor.whereCurrent) and combine them with where yourself
    • Offset-based pagination: Use the new offset property

    Previously, cursor expressions were baked into the where clause. Now they are passed separately so sync layers can choose their preferred pagination strategy.

    Changes:

    • Added CursorExpressions type with whereFrom, whereCurrent, and optional lastKey properties
    • Added cursor to LoadSubsetOptions for cursor-based pagination (separate from where)
    • Added offset to LoadSubsetOptions for offset-based pagination support
    • Electric sync layer now makes two parallel requestSnapshot calls when cursor is present:
      • One for whereCurrent (all ties at boundary, no limit)
      • One for whereFrom (rows after cursor, with limit)
    • Query collection serialization now includes offset for query key generation
    • Added truncate event to collections, emitted when synced data is truncated (e.g., after must-refetch)
    • Fixed setWindow pagination: cursor expressions are now correctly built when paging through results
    • Fixed offset tracking: loadNextItems now passes the correct window offset to prevent incorrect deduplication
    • CollectionSubscriber now listens for truncate events to reset cursor tracking state

    Benefits:

    • Sync layers can choose between cursor-based or offset-based pagination strategies
    • Electric can efficiently handle tie-breaking with two targeted requests
    • Better separation of concerns between filtering (where) and pagination (cursor/offset)
    • setWindow correctly triggers backend loading for subsequent pages in multi-column orderBy queries
    • Cursor state is properly reset after truncation, preventing stale cursor data from being used
  • Updated dependencies [b3b1940, 09da081, 86ad40c]:

    • @tanstack/db@0.5.12

1.0.6

Patch Changes

  • fix(query-db-collection): use deep equality for object field comparison in query observer (#967)

    Fixed an issue where updating object fields (non-primitives) with refetch: false in onUpdate handlers would cause the value to rollback to the previous state every other update. The query observer was using shallow equality (===) to compare items, which compares object properties by reference rather than by value. This caused the observer to incorrectly detect differences and write stale data back to syncedData. Now uses deepEquals for proper value comparison.

  • Use regular dependency for @tanstack/db instead of peerDependency to match the standard pattern used by other TanStack DB packages and prevent duplicate installations (#952)

  • Updated dependencies [c4b9399, a1a484e]:

    • @tanstack/db@0.5.11

1.0.5

Patch Changes

  • fix: ensure ctx.meta.loadSubsetOptions type-safety works automatically (#869)

    The module augmentation for ctx.meta.loadSubsetOptions is now guaranteed to load automatically when importing from @tanstack/query-db-collection. Previously, users needed to explicitly import QueryCollectionMeta or use @ts-ignore to pass ctx.meta?.loadSubsetOptions to parseLoadSubsetOptions.

    Additionally, QueryCollectionMeta is now an interface (instead of a type alias), enabling users to safely extend meta with custom properties via declaration merging:

    declare module '@tanstack/query-db-collection' {
      interface QueryCollectionMeta {
        myCustomProperty: string
      }
    }
  • Updated dependencies [c8a2c16]:

    • @tanstack/db@0.5.6

1.0.4

Patch Changes

  • Fix data loss on component remount by implementing reference counting for QueryObserver lifecycle (#870)

    What changed vs main:

    Previously, when live query subscriptions unsubscribed, there was no tracking of which rows were still needed by other active queries. This caused data loss during remounts.

    This PR adds reference counting infrastructure to properly manage QueryObserver lifecycle:

    1. Pass same predicates to unloadSubset that were passed to loadSubset
    2. Use them to compute the queryKey (via generateQueryKeyFromOptions)
    3. Use existing machinery (queryToRows map) to find rows that query loaded
    4. Decrement the ref count
    5. GC rows where count reaches 0 (no longer referenced by any active query)

    Impact:

    • Navigation back to previously loaded pages shows cached data immediately
    • No unnecessary refetches during quick remounts (< gcTime)
    • Multiple live queries with identical predicates correctly share QueryObservers
    • Proper row-level cleanup when last subscriber leaves
    • TanStack Query's cache lifecycle (gcTime) is fully respected
    • No data leakage from in-flight requests when unsubscribing
  • Updated dependencies [077fc1a]:

    • @tanstack/db@0.5.5

1.0.3

Patch Changes

  • Improved the type of the queryFn's ctx.meta property of the Query Collection to include the loadSubsetOptions (#857)

  • Fixed bug where optimistic state leaked into syncedData when using writeInsert inside onInsert handlers. Previously, when syncing server-generated fields (like IDs or timestamps) using writeInsert within an onInsert handler, the QueryClient cache was updated with combined visible state (including optimistic changes), which triggered the query observer to write optimistic values back to syncedData. Now the cache is correctly updated with only server-confirmed state, ensuring syncedData maintains separation from optimistic state. (#879)

  • Updated dependencies [acb3e4f, 464805d, 2c2e4db, 15c772f]:

    • @tanstack/db@0.5.4

1.0.2

Patch Changes

  • Automatically append predicates to static queryKey in on-demand mode. (#800)

    When using a static queryKey with syncMode: 'on-demand', the system now automatically appends serialized LoadSubsetOptions to create unique cache keys for different predicate combinations. This fixes an issue where all live queries with different predicates would share the same TanStack Query cache entry, causing data to be overwritten.

    Before:

    // This would cause conflicts between different queries
    queryCollectionOptions({
      queryKey: ['products'], // Static key
      syncMode: 'on-demand',
      queryFn: async (ctx) => {
        const { where, limit } = ctx.meta.loadSubsetOptions
        return fetch(`/api/products?...`).then((r) => r.json())
      },
    })

    With different live queries filtering by category='A' and category='B', both would share the same cache key ['products'], causing the last query to overwrite the first.

    After: Static queryKeys now work correctly in on-demand mode! The system automatically creates unique cache keys:

    • Query with category='A'['products', '{"where":{...A...}}']
    • Query with category='B'['products', '{"where":{...B...}}']

    Key behaviors:

    • ✅ Static queryKeys now work correctly with on-demand mode (automatic serialization)
    • ✅ Function-based queryKeys continue to work as before (no change)
    • ✅ Eager mode with static queryKeys unchanged (no automatic serialization)
    • ✅ Identical predicates correctly reuse the same cache entry

    This makes the documentation example work correctly without requiring users to manually implement function-based queryKeys for predicate push-down.

  • Updated dependencies [846a830, 8e26dcf]:

    • @tanstack/db@0.5.3

1.0.1

Patch Changes

  • Temporarily remove loadSubset call deduplication in query collection. We need to revisit our approach to deduplication to ensure correctness. See #836 for discussion on the proper implementation strategy. (#840)

  • Updated dependencies [a83a818]:

    • @tanstack/db@0.5.1

1.0.0

Patch Changes

  • Add expression helper utilities for parsing LoadSubsetOptions in queryFn. (#763)

    When using syncMode: 'on-demand', TanStack DB now provides helper functions to easily parse where clauses, orderBy, and limit predicates into your API's format:

    • parseWhereExpression: Parse where clauses with custom handlers for each operator
    • parseOrderByExpression: Parse order by into simple array format
    • extractSimpleComparisons: Extract simple AND-ed filters
    • parseLoadSubsetOptions: Convenience function to parse all options at once
    • walkExpression, extractFieldPath, extractValue: Lower-level helpers

    Example:

    import { parseLoadSubsetOptions } from '@tanstack/db'
    // or from "@tanstack/query-db-collection" (re-exported for convenience)
    
    queryFn: async (ctx) => {
      const { where, orderBy, limit } = ctx.meta.loadSubsetOptions
    
      const parsed = parseLoadSubsetOptions({ where, orderBy, limit })
    
      // Build API request from parsed filters
      const params = new URLSearchParams()
      parsed.filters.forEach(({ field, operator, value }) => {
        if (operator === 'eq') {
          params.set(field.join('.'), String(value))
        }
      })
    
      return fetch(`/api/products?${params}`).then((r) => r.json())
    }

    This eliminates the need to manually traverse expression AST trees when implementing predicate push-down.

  • Handle pushed-down predicates (#763)

  • Updated dependencies [243a35a, f9d11fc, 7aedf12, 28f81b5, 28f81b5, f6ac7ea, 01093a7]:

    • @tanstack/db@0.5.0

0.3.0

Minor Changes

  • Add QueryObserver state utilities and convert error utils to getters (#742)

    Exposes TanStack Query's QueryObserver state through QueryCollectionUtils, providing visibility into sync status beyond just error states. Also converts existing error state utilities from methods to getters for consistency with TanStack DB/Query patterns.

    Breaking Changes:

    • lastError(), isError(), and errorCount() are now getters instead of methods
      • Before: collection.utils.lastError()
      • After: collection.utils.lastError

    New Utilities:

    • isFetching - Check if query is currently fetching (initial or background)
    • isRefetching - Check if query is refetching in background
    • isLoading - Check if query is loading for first time
    • dataUpdatedAt - Get timestamp of last successful data update
    • fetchStatus - Get current fetch status ('fetching' | 'paused' | 'idle')

    Use Cases:

    • Show loading indicators during background refetches
    • Implement "Last updated X minutes ago" UI patterns
    • Better understanding of query sync behavior

    Example Usage:

    const collection = queryCollectionOptions({
      // ... config
    })
    
    // Check sync status
    if (collection.utils.isFetching) {
      console.log('Syncing with server...')
    }
    
    if (collection.utils.isRefetching) {
      console.log('Background refresh in progress')
    }
    
    // Show last update time
    const lastUpdate = new Date(collection.utils.dataUpdatedAt)
    console.log(`Last synced: ${lastUpdate.toLocaleTimeString()}`)
    
    // Check error state (now using getters)
    if (collection.utils.isError) {
      console.error('Sync failed:', collection.utils.lastError)
      console.log(`Failed ${collection.utils.errorCount} times`)
    }

Patch Changes

  • Fix dependency bundling issues by moving @tanstack/db to peerDependencies (#766)

    What Changed:

    Moved @tanstack/db from regular dependencies to peerDependencies in:

    • @tanstack/offline-transactions
    • @tanstack/query-db-collection

    Removed @opentelemetry/api dependency from @tanstack/offline-transactions.

    Why:

    These extension packages incorrectly declared @tanstack/db as both a regular dependency AND a peerDependency simultaneously. This caused lock files to develop conflicting versions, resulting in multiple instances of @tanstack/db being installed in consuming applications.

    The fix removes @tanstack/db from regular dependencies and keeps it only as a peerDependency. This ensures only one version of @tanstack/db is installed in the dependency tree, preventing version conflicts.

    For local development, @tanstack/db remains in devDependencies so the packages can be built and tested independently.

  • Updated dependencies [6c55e16, 7805afb, 1367756]:

    • @tanstack/db@0.4.20

0.2.42

Patch Changes

  • Updated dependencies [75470a8]:
    • @tanstack/db@0.4.19

0.2.41

Patch Changes

0.2.40

Patch Changes

  • Updated dependencies [49bcaa5]:
    • @tanstack/db@0.4.17

0.2.39

Patch Changes

0.2.38

Patch Changes

  • Updated dependencies [6738247]:
    • @tanstack/db@0.4.15

0.2.37

Patch Changes

  • Behavior change: utils.refetch() now uses exact query key targeting (previously used prefix matching). This prevents unintended cascading refetches of related queries. For example, refetching ['todos', 'project-1'] will no longer trigger refetches of ['todos'] or ['todos', 'project-2']. (#552)

    Additionally, utils.refetch() now bypasses enabled: false to support manual/imperative refetch patterns (matching TanStack Query hook behavior) and returns QueryObserverResult instead of void for better DX.

0.2.36

Patch Changes

  • Updated dependencies [970616b]:
    • @tanstack/db@0.4.14

0.2.35

Patch Changes

  • Updated dependencies [3c9526c]:
    • @tanstack/db@0.4.13

0.2.34

Patch Changes

  • Fix queryCollectionOptions to respect QueryClient defaultOptions when not overridden (#707)

    Previously, when creating a QueryClient with defaultOptions (e.g., staleTime, retry, refetchOnWindowFocus), these options were ignored by queryCollectionOptions unless explicitly specified again in the collection config. This required duplicating configuration and prevented users from setting global defaults.

    Now, queryCollectionOptions properly respects the QueryClient's defaultOptions as fallbacks. Options explicitly provided in queryCollectionOptions will still override the defaults.

    Example - this now works as expected:

    const dbQueryClient = new QueryClient({
      defaultOptions: {
        queries: {
          refetchOnWindowFocus: false,
          staleTime: Infinity,
        },
      },
    })
    
    queryCollectionOptions({
      id: 'wallet-accounts',
      queryKey: ['wallet-accounts'],
      queryClient: dbQueryClient,
      // staleTime: Infinity is now inherited from defaultOptions
    })
  • Fix writeDelete/writeUpdate validation to check synced store only (#708)

    Fixed issue where calling writeDelete() or writeUpdate() inside mutation handlers (like onDelete) would throw errors when optimistic updates were active. These write operations now correctly validate against the synced store only, not the combined view (synced + optimistic).

    This allows patterns like calling writeDelete() inside an onDelete handler to work correctly, enabling users to write directly to the synced store while the mutation is being persisted to the backend.

    Fixes #706

0.2.33

Patch Changes

0.2.32

Patch Changes

  • Updated dependencies [5566b26]:
    • @tanstack/db@0.4.11

0.2.31

Patch Changes

0.2.30

Patch Changes

0.2.29

Patch Changes

0.2.28

Patch Changes

  • Updated dependencies [6692aad]:
    • @tanstack/db@0.4.7

0.2.27

Patch Changes

0.2.26

Patch Changes

  • Updated dependencies [7556fb6]:
    • @tanstack/db@0.4.5

0.2.25

Patch Changes

  • Fix collection.preload() hanging when called without startSync or subscribers. The QueryObserver now subscribes immediately when sync starts (from preload(), startSync, or first subscriber), while maintaining the staleTime behavior by dynamically unsubscribing when subscriber count drops to zero. (#635)

  • Updated dependencies [56b870b, f623990, 5f43d5f, 05776f5, d27d32a]:

    • @tanstack/db@0.4.4

0.2.24

Patch Changes

  • Updated dependencies [32f2212]:
    • @tanstack/db@0.4.3

0.2.23

Patch Changes

  • Fix staleTime behavior by automatically subscribing/unsubscribing from TanStack Query based on collection subscriber count. (#462)

    Previously, query collections kept a QueryObserver permanently subscribed, which broke TanStack Query's staleTime and window-focus refetch behavior. Now the QueryObserver properly goes inactive when the collection has no subscribers, restoring normal staleTime/gcTime semantics.

  • query-collection now supports a select function to transform raw query results into an array of items. This is useful for APIs that return data with metadata or nested structures, ensuring metadata remains cached while collections work with the unwrapped array. (#551)

  • Updated dependencies [51c6bc5, 248e2c6, ce7e2b2, 1b832ff]:

    • @tanstack/db@0.4.2

0.2.22

Patch Changes

  • Updated dependencies [8cd0876]:
    • @tanstack/db@0.4.1

0.2.21

Patch Changes

  • Refactor the main Collection class into smaller classes to make it easier to maintain. (#560)

  • Updated dependencies [2f87216, ac6250a, 2f87216]:

    • @tanstack/db@0.4.0

0.2.20

Patch Changes

  • Updated dependencies [cacfca2]:
    • @tanstack/db@0.3.2

0.2.19

Patch Changes

  • Updated dependencies [5f51f35]:
    • @tanstack/db@0.3.1

0.2.18

Patch Changes

0.2.17

Patch Changes

  • Refactor of the types of collection config factories for better type inference. (#530)

  • Define BaseCollectionConfig interface and let all collections extend it. (#531)

  • Updated dependencies [b03894d, 3968087]:

    • @tanstack/db@0.2.5

0.2.16

Patch Changes

  • Add error tracking and retry methods to query collection utils. (#441)

  • Updated dependencies [92febbf, b487430]:

    • @tanstack/db@0.2.4

0.2.15

Patch Changes

  • Updated dependencies [b162556]:
    • @tanstack/db@0.2.3

0.2.14

Patch Changes

  • Updated dependencies [33515c6]:
    • @tanstack/db@0.2.2

0.2.13

Patch Changes

  • Updated dependencies [620ebea]:
    • @tanstack/db@0.2.1

0.2.12

Patch Changes

0.2.11

Patch Changes

  • fix: race condition creating a collection from a query that has already loaded (#495)

  • Updated dependencies [cc4c34a]:

    • @tanstack/db@0.1.12

0.2.10

Patch Changes

  • Updated dependencies [b869f68]:
    • @tanstack/db@0.1.11

0.2.9

Patch Changes

0.2.8

Patch Changes

  • Updated dependencies [d64b4a8]:
    • @tanstack/db@0.1.9

0.2.7

Patch Changes

0.2.6

Patch Changes

0.2.5

Patch Changes

  • Updated dependencies [ad33e9e]:
    • @tanstack/db@0.1.6

0.2.4

Patch Changes

  • Add type inference of the collection type from the query collection config queryFn return type (#403)

  • Updated dependencies [9a5a20c]:

    • @tanstack/db@0.1.5

0.2.3

Patch Changes

0.2.2

Patch Changes

  • Updated dependencies [0cb7699]:
    • @tanstack/db@0.1.3

0.2.1

Patch Changes

  • Ensure that you can use optional properties in the select and join clauses of a query, and fix an issue where standard schemas were not properly carried through to live queries. (#377)

  • Updated dependencies [bb5d50e, 97b595e]:

    • @tanstack/db@0.1.2

0.2.0

Minor Changes

  • Improve writeBatch API to use callback pattern (#378)
    • Changed writeBatch from accepting an array of operations to accepting a callback function
    • Write operations called within the callback are automatically batched together
    • This provides a more intuitive API similar to database transactions
    • Added comprehensive documentation for Query Collections including direct writes feature

0.1.3

Patch Changes

  • Add meta support to QueryCollectionConfig to allow passing additional context to queryFn. (#363)

  • Updated dependencies [bc2f204, bda3f24]:

    • @tanstack/db@0.1.1

0.1.2

Patch Changes

  • Move @tanstack/query-core from dependencies to peerDependencies to avoid version conflicts when users already have react-query or query-core installed. This is a non-breaking change as the package will continue to work with any 5.x version of query-core. (#351)

0.1.1

Patch Changes

  • Add manual write methods to QueryCollectionUtils interface to enable direct state updates from external sources. Introduces writeInsert, writeUpdate, writeDelete, writeUpsert, and writeBatch methods that bypass the normal optimistic update flow for WebSocket/real-time scenarios. All methods include proper transaction handling, data validation, and automatic query cache synchronization. (#303)

0.1.0

Minor Changes

  • 0.1 release - first beta 🎉 (#332)

Patch Changes

0.0.15

Patch Changes

  • Updated dependencies [6e8d7f6]:
    • @tanstack/db@0.0.33

0.0.14

Patch Changes

  • Fix LiveQueryCollection hanging when source collections have no data (#309)

    Fixed an issue where LiveQueryCollection.preload() would hang indefinitely when source collections call markReady() without data changes (e.g., when queryFn returns empty array).

    The fix implements a proper event-based solution:

    • Collections now emit empty change events when becoming ready with no data
    • WHERE clause filtered subscriptions now correctly pass through empty ready signals
    • Both regular and WHERE clause optimized LiveQueryCollections now work correctly with empty source collections
  • Updated dependencies [e04bd12]:

    • @tanstack/db@0.0.32

0.0.13

Patch Changes

  • Updated dependencies [3e9a36d]:
    • @tanstack/db@0.0.31

0.0.12

Patch Changes

  • Updated dependencies [6bdde55]:
    • @tanstack/db@0.0.30

0.0.11

Patch Changes

  • feat: Replace string-based errors with named error classes for better error handling (#297)

    This comprehensive update replaces all string-based error throws throughout the TanStack DB codebase with named error classes, providing better type safety and developer experience.

    New Features

    • Root TanStackDBError class - all errors inherit from a common base for unified error handling
    • Named error classes organized by package and functional area
    • Type-safe error handling using instanceof checks instead of string matching
    • Package-specific error definitions - each adapter has its own error classes
    • Better IDE support with autocomplete for error types

    Package Structure

    Core Package (@tanstack/db)

    Contains generic errors used across the ecosystem:

    • Collection configuration, state, and operation errors
    • Transaction lifecycle and mutation errors
    • Query building, compilation, and execution errors
    • Storage and serialization errors

    Adapter Packages

    Each adapter now exports its own specific error classes:

    • @tanstack/electric-db-collection: Electric-specific errors
    • @tanstack/trailbase-db-collection: TrailBase-specific errors
    • @tanstack/query-db-collection: Query collection specific errors

    Breaking Changes

    • Error handling code using string matching will need to be updated to use instanceof checks
    • Some error messages may have slight formatting changes
    • Adapter-specific errors now need to be imported from their respective packages

    Migration Guide

    Core DB Errors

    Before:

    try {
      collection.insert(data)
    } catch (error) {
      if (error.message.includes('already exists')) {
        // Handle duplicate key error
      }
    }

    After:

    import { DuplicateKeyError } from '@tanstack/db'
    
    try {
      collection.insert(data)
    } catch (error) {
      if (error instanceof DuplicateKeyError) {
        // Type-safe error handling
      }
    }

    Adapter-Specific Errors

    Before:

    // Electric collection errors were imported from @tanstack/db
    import { ElectricInsertHandlerMustReturnTxIdError } from '@tanstack/db'

    After:

    // Now import from the specific adapter package
    import { ElectricInsertHandlerMustReturnTxIdError } from '@tanstack/electric-db-collection'

    Unified Error Handling

    New:

    import { TanStackDBError } from '@tanstack/db'
    
    try {
      // Any TanStack DB operation
    } catch (error) {
      if (error instanceof TanStackDBError) {
        // Handle all TanStack DB errors uniformly
        console.log('TanStack DB error:', error.message)
      }
    }

    Benefits

    • Type Safety: All errors now have specific types that can be caught with instanceof
    • Unified Error Handling: Root TanStackDBError class allows catching all library errors with a single check
    • Better Package Separation: Each adapter manages its own error types
    • Developer Experience: Better IDE support with autocomplete for error types
    • Maintainability: Error definitions are co-located with their usage
    • Consistency: Uniform error handling patterns across the entire codebase

    All error classes maintain the same error messages and behavior while providing better structure and package separation.

  • Updated dependencies [ced0657, dcfef51, 360b0df, 608be0c, 5260ee3]:

    • @tanstack/db@0.0.29

0.0.10

Patch Changes

0.0.9

Patch Changes

  • Updated dependencies [bec8620]:
    • @tanstack/db@0.0.27

0.0.8

Patch Changes

  • Add initial release of TrailBase collection for TanStack DB. TrailBase is a blazingly fast, open-source alternative to Firebase built on Rust, SQLite, and V8. It provides type-safe REST and realtime APIs with sub-millisecond latencies, integrated authentication, and flexible access control - all in a single executable. This collection type enables seamless integration with TrailBase backends for high-performance real-time applications. (#228)

  • Updated dependencies [09c6995]:

    • @tanstack/db@0.0.26

0.0.7

Patch Changes

  • Add explicit collection readiness detection with isReady() and markReady() (#270)

    • Add isReady() method to check if a collection is ready for use
    • Add onFirstReady() method to register callbacks for when collection becomes ready
    • Add markReady() to SyncConfig interface for sync implementations to explicitly signal readiness
    • Replace onFirstCommit() with onFirstReady() for better semantics
    • Update status state machine to allow loadingready transition for cases with no data to commit
    • Update all sync implementations (Electric, Query, Local-only, Local-storage) to use markReady()
    • Improve error handling by allowing collections to be marked ready even when sync errors occur

    This provides a more intuitive and ergonomic API for determining collection readiness, replacing the previous approach of using commits as a readiness signal.

  • Updated dependencies [1758eda, 20f810e]:

    • @tanstack/db@0.0.25

0.0.6

Patch Changes

0.0.5

Patch Changes

  • Updated dependencies [056609e]:
    • @tanstack/db@0.0.23

0.0.4

Patch Changes

  • Updated dependencies [aeee9a1]:
    • @tanstack/db@0.0.22

0.0.3

Patch Changes

  • Move Collections to their own packages (#252)

    • Move local-only and local-storage collections to main @tanstack/db package
    • Create new @tanstack/electric-db-collection package for ElectricSQL integration
    • Create new @tanstack/query-db-collection package for TanStack Query integration
    • Delete @tanstack/db-collections package (removed from repo)
    • Update example app and documentation to use new package structure

    Why?

    • Better separation of concerns
    • Independent versioning for each collection type
    • Cleaner dependencies (electric collections don't need query deps, etc.)
    • Easier to add more collection types moving forward
  • Updated dependencies [8e23322]:

    • @tanstack/db@0.0.21