Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

CHANGELOG.md

1,617 lines95.8 KB

@tanstack/query-db-collection

1.4.4

Patch Changes

  • Recover persisted on-demand Electric and Query collections after cache claim loss by rotating their SQLite cache and reloading active subsets. Fence retired provider work and expired claims, preserve warm runs on their claimed cache generation, and forward claim lifetime options through SQLite host factories. Require explicit eager or claim-bound managed targets for SQLite adapter data operations, and forward them through Electron IPC protocol v6. Bare collection IDs no longer work at this lower-level adapter boundary. (#2069)

  • Prevent direct writes from automatically refetching active Query subsets. On-demand writes patch changed keys already present in active raw arrays or directly selected response arrays, except when the Query is shared with another Collection. Eager writes patch representable rows in a shared Query cache, so Collections using the same Query project those edits. In both modes, cache patches preserve Query error, invalidation, and freshness state; an idle eager cache seed moves from pending to success without advancing its freshness timestamp. Direct writes no longer clear a prior fetch error or mark stale data fresh. Older in-flight or queued results cannot undo an accepted write, and derived cache responses are not replayed over it on resubscribe. A later-started successful subset fetch controls a shared row's value over an older request that settles afterward. Callers choose when to request current server rows; a complete matching on-demand result can remove an omitted ownerless direct row. Query Core 5.90.15 or later is required for post-write refetch replacement and error-state recovery. (#2065)

    An eager Collection that later joins a Query patched by another eager Collection projects the cached edit without starting a request, including when disabled. An on-demand Collection still revalidates an unverified cache edit before accepting it for a subset. A fresh persisted Collection refetches on a cached-row collision when it cannot recover the order of its stored direct write and that Query result. Inactive Query entries under the Collection key prefix may be removed after a direct write. A physical Query whose stored key is outside that prefix remains in the cache, even when a custom hash aliases it with a Collection key; callers can explicitly evict or refetch that entry.

  • A completed, active full-source Query Collection load can now serve later (#2135) filtered or windowed live queries when the collection uses a static query key. The narrower queries retain the full Query until their final owner releases, so the original full view can unmount without dropping their rows or stopping later invalidation updates. Incomplete full loads and explicit subset refetches keep their own request paths. A narrower scope with retained persisted ownership makes an exact request to revalidate its rows and owners.

  • Updated dependencies [cda9d6a, 2f928e6, dfec42e, 1a65c2c, 1b4ee8d, bbbf017, bc6f30e, fade2e2, bbe9327, b34a579, 6fa60aa, f84387c, be4a3d6, 0dc696a, fd13e3c]:

    • @tanstack/db@0.14.0

1.4.3

Patch Changes

1.4.2

Patch Changes

  • Updated dependencies [487c5a6]:
    • @tanstack/db@0.12.3

1.4.1

Patch Changes

1.4.0

Minor Changes

  • Validate a Query Collection direct write against every earlier sync commit, and order it before later refetch results. (#2044)

    Breaking: validation errors from writeInsert, writeUpdate, writeDelete, writeUpsert and writeBatch now reject the returned promise. Before, they were thrown synchronously. Await the promise and catch the error.

    In a persisted collection, a direct write can now wait for an earlier sync commit's durable write before it applies. Before, a refetch could wait behind the persistence lock, and a direct write in that window validated against older rows: writeUpdate and writeDelete of a key that only the refetch held failed, and writeInsert of that key replaced it. A refetch that returns while the write waits is handled after the write. It keeps the write's rows if it started before the write was called, and it replaces them if it started after.

    In a persisted collection, writeInsert of a key that is already in the synced store now rejects with DuplicateKeySyncError, as it does without persistence. Before, it silently replaced the row.

Patch Changes

1.3.5

Patch Changes

  • Correct query key builder examples and clarify how static and custom keys distinguish on-demand requests in the cache. (#2028)

  • Drop a transaction's optimistic state when its mutation function settles. A sync transaction committed while the transaction is persisting is accepted and held. It publishes together with that drop, and isPersisted settles after that publication. A mutation function that returns before its server row arrives shows the previous synced row until that row applies. A sync write is attributed $origin: 'local' only if it was accepted before the optimistic state dropped. A sync transaction still open at that point is not counted. (#2030)

    Breaking: remove the begin({ immediate }) option from the sync API. Writes made while a mutation persists now queue behind it instead of applying at once.

    Each sync transaction now has two moments: accepted and visible. commit() receipts and subset loads resolve when the rows are visible. Collection readiness (preload, stateWhenReady, toArrayWhenReady) resolves once the startup rows are accepted, so a mutation handler that awaits its own collection's readiness during startup settles. An accepted transaction always applies. Handler-facing writes resolve at acceptance, so a mutation handler can await them: Query Collection direct writes, persisted mutation confirmation, and the PowerSync mutation path. A handler that awaits an on-demand load of its own collection waits for itself.

    A subset load whose caller aborts rejects with AbortError at every point: before the fetch, when the fetch fails because of the abort, after the fetch but before the commit, and between pages. Pages that were already accepted still apply, and a TrailBase load waits until they are visible.

    Query Collection direct writes read and validate the accepted rows and update the Query cache after acceptance. A refetch no longer cancels an accepted result, so overlapping refetches of a persisted collection apply in order (#1990). An eager fetch that started before a direct write keeps the server's rows for every key the write did not touch and the accepted row for each key it did, in both the collection and the Query cache.

    A DbClient hydration chunk is accepted ahead of a still-open source transaction, so readers of accepted rows see it and the source's commit() still commits its own writes.

    Partial sync updates now keep an own __proto__ field. Metadata-only sync writes no longer publish a spurious insert when they apply with a held transaction. A rollback keeps its delete event when a sync transaction for the same key is still open. When two completed transactions hold one key, the newer transaction's row stays visible. Canceling any sync transaction other than the open last one throws SyncQueueInvariantError.

  • Updated dependencies [2806da0, 7c516ce, eac6e8b, a21f4a4, cfb03f2]:

    • @tanstack/db@0.12.0

1.3.4

Patch Changes

  • Updated dependencies [06cab6f]:
    • @tanstack/db@0.11.3

1.3.3

Patch Changes

1.3.2

Patch Changes

  • Return an applied receipt promise from Query Collection direct writes and batches. Mutation handlers can await the write to store server responses before they return. (#1984)

  • Fix SSR serialization of on-demand Query collections while keeping subset request options available to query functions. (#1969)

  • Updated dependencies [a18f63d, e706483, 18abcee, d2690bf, 5b85af0, 1dbf5f9, 7ab48d8, d2690bf, 7ca38db, f2f92c5]:

    • @tanstack/db@0.11.1

1.3.1

Patch Changes

1.3.0

Minor Changes

  • Deprecation: Mutation handler return values and QueryCollection auto-refetch behavior. (#843)

    What's changed:

    • Handler return values remain type-compatible during the deprecation window
    • Deprecation warnings are logged when deprecated patterns are used

    QueryCollection changes:

    • Auto-refetch after handlers is deprecated and will be removed in v1.0
    • To skip auto-refetch now, return { refetch: false } from your handler
    • To migrate to explicit refetch now, await collection.utils.refetch() and return { refetch: false } to prevent a second fetch; remove the return in v1.0
    • In v1.0, call await collection.utils.refetch() explicitly when needed, or omit it to skip

    ElectricCollection changes:

    • Returning { txid } is deprecated - use await collection.utils.awaitTxId(txid) instead
    • The default awaitTxId and awaitMatch timeouts increase to 15 seconds

    Migration guide:

    // QueryCollection - skip refetch (current)
    onInsert: async ({ transaction }) => {
      await api.create(transaction.mutations[0].modified)
      return { refetch: false } // Opt out of auto-refetch
    }
    
    // QueryCollection - migrate to explicit refetch now
    onInsert: async ({ transaction, collection }) => {
      await api.create(transaction.mutations[0].modified)
      await collection.utils.refetch() // Explicit refetch
      return { refetch: false } // Prevent a second pre-1.0 refetch; remove in v1.0
    }
    
    // ElectricCollection - before
    onInsert: async ({ transaction }) => {
      const result = await api.create(transaction.mutations[0].modified)
      return { txid: result.txid } // Deprecated
    }
    
    // ElectricCollection - after
    onInsert: async ({ transaction, collection }) => {
      const result = await api.create(transaction.mutations[0].modified)
      await collection.utils.awaitTxId(result.txid) // Explicit
    }
  • Preserve collection key and adapter utility types throughout mutation handlers and nested transaction mutations. Mutation keys now use the collection's declared key type instead of any; collections that use the default key type expose string | number. Prevent Query and Electric collections from exposing nonexistent cross-adapter utilities. (#1849)

Patch Changes

  • Add createCursorPager to fulfill offset/limit requests from endpoints with opaque continuation tokens. Reuse fresh backend pages through the existing QueryClient, with Query-managed expiry, invalidation and garbage collection, while retaining the existing UI peek-ahead behavior. (#1824)

    Keep manual raw-row writes from overwriting other cache formats or marking them fresh. Preserve wrapped-response writes and seeding of empty row caches.

  • Wait for asynchronous adapter cleanup before a collection reaches cleaned-up or starts a replacement sync run. Preserve cleanup settlement through SQLite persistence, PowerSync, and Query Collection wrappers, including cleanup hooks acquired before cleanup starts and resource disposal failures. (#1895)

  • Repair invalidated ordered queries with authoritative provider refetches and keep publication behind the repair. Revalidate active and cached Query Collection observers before applying repaired results. (#1886)

  • Fail-stop persisted collections when hydration or durability fails, and replay authoritative source transactions through one persistence-owned FIFO. Electric collections keep optimistic state immediate while surfacing durable failures through the collection error state instead of continuing from an incomplete baseline. (#1853)

    Query collections retain ownership metadata that the persisted wrapper already published instead of restoring stale ownership after the publication boundary.

  • Keep on-demand Query cache ownership and post-write readiness isolated across collections, co-owners, deferred cleanup, errors, and custom query hashes. Active enabled scopes revalidate from post-write provider results, while inactive collection-owned entries are removed without disturbing unrelated or foreign-observed Queries. (#1826)

  • Start idle collections only after locally decidable mutation validation succeeds, and publish authoritative Query Collection refetch results without stale intermediate snapshots. (#1840)

  • Fix explicit refetches so calls normally wait for accepted results to reach Collection rows. If a mutation overlaps the call in either start order, use the Query fetch boundary to prevent circular waits and unrelated persistence delays. Mutation handlers preserve the real Collection, transaction, and mutation identities. Cancelled fetches now retire their causal application records without waiting for another fetch. (#1885)

  • Reject successful query results that cannot be applied, and keep deferred refetches pending until their replacement result is applied or cancelled. (#1881)

  • Fix queryCollectionOptions to accept selectors that materialize transforming schema outputs from wrapped responses while preserving schema input types for mutations. (#1861)

  • Preserve persisted resume integrity with atomic SQLite baseline evidence and stale-writer rejection, expose persistence sync metadata as one versioned capability, and refresh uncertified Electric baselines before publishing resumed data. (#1846)

    This changes the public persistence contracts: custom PersistenceAdapter implementations must now implement loadResumeSnapshot, and SyncMetadataApi.persistence is required with null explicitly representing no persistence. Custom sync wrappers that receive metadata must forward metadata.persistence unchanged so consumers receive either that sentinel or the complete versioned capability. A direct sync invocation may still omit the optional metadata object entirely, which consumers treat as no persistence. The Electron bridge now transports the atomic resume snapshot through IPC protocol v2; Electron main and renderer integrations must upgrade together because mixed v1/v2 peers fail closed. Node and React Native persistence instances that wrap one database handle now share transaction admission so concurrent collection startup cannot overlap transactions on that connection.

  • Preserve synchronous initial readiness for ordered and limited live queries when every required source acquisition applies synchronously. Avoid redundant ordered acquisition when sibling sources add synchronous graph input. Keep warm Query Collection results synchronous and return one aggregate fetch status from Query Collection utilities. (#1896)

  • Updated dependencies [2ad6834, b528a61, 84fc44b, 9351f46, 5108acf, afbeb44, 2775082, fef53f8, b44a50a, 19dd9a2, 3096b8f, 1ab1cd3, e5fe2ea, 3eb5b2b, 7c62bf5, 63362dc, 7f6b643, c479fdc, 91a2cbf, 144c6b1, 5218f0c, 76d766e, 1e54c6a, d698b90, 04a1a81, 3ad64a4, 4c5a8de, b72b5d1, fc1adde, 2781581, 40a5aea, e16d46c, 9cbc885, 23ae52d, 7917ef9, 1ca838b, 34a999d, 825acc5, febd4bc, b7a7d10, 510cb53, efb84d8, 236d77b, 71ad428]:

    • @tanstack/db@0.10.0

1.2.15

Patch Changes

  • Updated dependencies [3c4c35d]:
    • @tanstack/db@0.9.2

1.2.14

Patch Changes

1.2.13

Patch Changes

  • Fix on-demand load settlement, ordered pagination, and replay to preserve coherent results across cancellation, failure, cleanup, and restart. Preserve subset results and ownership across Electric, PowerSync, Query, and SQLite persistence adapters. Correct live-query grouping, include projections, value identity, and indexed comparisons. D2 hashing now rejects structural cycles and excessive traversal depth or work with an explicit error; Collection handles retain object-reference identity without traversing their mutable contents. (#1797)

    Remove the unused public subset-algebra helpers: isWhereSubset, unionWherePredicates, minusWherePredicates, isOrderBySubset, isLimitSubset, isOffsetLimitSubset, isPredicateSubset, and isLoadSubsetRequestSubsumedBy. Apps that import these helpers must remove those imports; normal queries and adapters are unaffected. DeduplicatedLoadSubset remains available and shares only exact demand identities.

    Reject compiled Collection-valued includes as fn.select() inputs, including nested descendants, before invoking the callback. Use toArray() or materialize() in the upstream .select() for child-value calculations. To keep live child Collections, use expression .select() or perform parent-only functional work before adding the includes. Ordinary Collection-valued includes remain supported.

    Remove proxy DEBUG logging and automatic index timing statistics to avoid diagnostic work on reads and writes. Remove getStats() and IndexStats; use index.keyCount for the current entry count, and instrument index methods externally when profiling. Custom index subclasses must remove calls to the retired trackLookup() and updateTimestamp() helpers.

    Fix mutation drafts so Map/Set forEach calls each callback once and read-only iteration reports no changes. Track nested Map for...of edits through collection.update(). Keep Set entries in place during nested edits, preserving live iteration and usable has, delete, and add handles without duplicate entries or repeated visits. Reverting one entry no longer discards another entry's pending changes.

    Preserve shared values within a row's draft. Newly supplied objects use normal shared references during the update callback, including Map values and Set members; editing through either handle changes the same new object. Copy completed changes at callback return so later caller edits cannot mutate stored data. Existing collection values remain isolated. Copy a new caller-owned value before insertion if it must remain untouched during the callback.

    Keep rejected local-storage mutations out of later successful saves. Stage insert, update, delete, and manual transaction writes before persisting, then promote the shared cache only after storage succeeds.

    Deliver live-query observer publications to peer listeners even when one listener throws. Preserve queued publication order and stop delivery on disposal; report the first listener failure after delivery.

    Wait for PowerSync demands admitted during tracking finalization before reporting them loaded. Preserve untouched object and array key identity when they contain NaN. Retire every failed ordered acquisition on explicit retry, while retaining a full-source demand repaired by replay.

    After authoritative ordered recovery succeeds, retire settled page and tie demands so later truncate replay fetches only the full-source replacement. Keep unfinished requests observed until settlement and preserve independent query ownership.

    Remove the live-query utils.getRunCount() diagnostic and its runtime counter. Apps that call this diagnostic must remove those calls. Query scheduling and results are unchanged.

    Remove test-only index inspection getters (indexedKeysSet, valueMapData, orderedEntriesArray, and orderedEntriesArrayReversed) and unused scheduler diagnostics. ReverseIndex now exposes only the IndexReader lookup, range, and forward traversal surface returned by findIndexForField; mutate the original index instead. Export IndexReader for callers that name this return type. Remove the unused subscription releaseLoadSubset() method; request owners use the release callback supplied by onLoadSubsetResult. Ordinary query and adapter APIs remain unchanged by these removals.

    Remove unused internal helpers and the unused public error classes WhereClauseConversionError, SubscriptionNotFoundError, and AggregateNotSupportedError. These classes have no remaining runtime throw sites; remove any imports of them. Keep the existing query and index behavior and exercise identity/evaluation tests through the production entry points.

    Ensure failed mutations roll back even when their rejection value cannot be converted to a string. Preserve ordinary Error instances; report unprintable rejection values as Unknown error.

    Make reentrant effect disposal share the active cleanup result, including calls from abort listeners or source release callbacks. A release failure reaches every waiting disposer while each source still receives one release attempt.

    Reject starting or preloading a collection from inside its active cleanup callbacks with a clear CollectionStateError. Nested cleanup cannot admit replacement work that the old teardown would discard. Restart after cleanup completes, or from its final cleaned-up status event, remains supported.

    Prevent older page or tie-boundary completions from clearing a newer full-source failure or starting redundant loading. Failed window moves retain their settled public snapshot; an explicit retry releases the failed acquisition once and publishes the completed replacement.

    Restrict direct subscription requestLimitedSnapshot() cursor inputs to one order term and one minValues entry. Composite and partial-composite cursor inputs now throw before local delivery or adapter work. Use normal live-query ordering and window APIs for multi-column pagination; those remain supported through prefix-and-tie loading. Existing adapters need no changes.

    Treat LoadSubsetOptions and their nested request data as immutable from submission onward. Core no longer copies expression trees or mutable constant payloads at the sync and deduplication boundaries. Create a new Date, byte array, membership array, or options object when changing a demand instead of mutating submitted data. Adapters must also leave request data unchanged. Use stable data properties rather than stateful getters. AbortSignal cancellation and subscription release remain live.

    Replace replay acquisitions sequentially: release the prior physical lease before starting its replacement. The logical demand and last complete public result remain retained. A failed release prevents replacement startup; failed startup leaves demand available for a later authoritative replay. Custom adapters must support a release/load gap and preserve resources still held by other owners; a sole underlying resource may stop and restart.

  • Updated dependencies [cfb01ce]:

    • @tanstack/db@0.9.0

1.2.12

Patch Changes

  • Updated dependencies [bbc9edf]:
    • @tanstack/db@0.8.7

1.2.11

Patch Changes

  • Updated dependencies [ae2fe74]:
    • @tanstack/db@0.8.6

1.2.10

Patch Changes

  • Canonicalize equivalent loadSubset queries to one demand identity while preserving observable output aliases, exact projected values, and distinct ordered windows. Query DB now reuses the same canonical identity for its on-demand cache keys. (#1768)

  • Settle subset loads only after their committed rows and events are visible. A (#1769) commit receipt now rejects with AbortError when cancellation wins before application and ignores later aborts. Preserve causal publication, cancellation, persistence, and error handling across the affected sync adapters.

  • Updated dependencies [d8defd2, 9ad882f, 8c5838d]:

    • @tanstack/db@0.8.5

1.2.9

Patch Changes

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

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 https://github.com/TanStack/db/issues/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 loading → ready 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