Repository navigation
Description
- I've validated the bug against the latest version of DB packages
Versions
@tanstack/db-sqlite-persistence-core1.0.0-rc.1.5 (mainat ee11302)@tanstack/dbfrommain, tested with and without fix(db): compare value classes with toJSON() by their serialized value #2460 applied- Node 22 (
node:sqlite) for the repro; the same behavior seen in a browser app with@tanstack/browser-db-sqlite-persistence
Describe the bug
SQLite persistence stores class instances as their own enumerable fields and decodes them as plain objects. encodePersistedJsonValue (sqlite-core-adapter.ts) walks Object.entries for any object that is not one of the built-in tagged types:
- A class with public fields, shaped like SurrealDB's
RecordId(_id, plus a nestedTableclass in_table, withtoString()andtoJSON()), is stored as{"id":{"_id":"a","_table":{"_name":"user"}}}. - A class that keeps its state in private
#fields(e.g. a money/decimal type) is stored as{"price":{}}, so every instance collapses to the same value. - On read, both decode as plain objects.
String(row.id)is"[object Object]".
Filtering on a class-valued field never matches. adapter.loadSubset on a real SQLiteCorePersistenceAdapter over node:sqlite:
where |
Rows (with or without #2460) |
|---|---|
eq(id, new RecordId('user', 'a')) |
0 |
eq(id, { _table: { _name: 'user' }, _id: 'a' }) (plain object of the stored shape) |
0 |
eq(price, new Money(100)) |
0 |
eq(id, 'user:a'), rows with string ids |
1 |
eq(key, 'a'), string field next to a class-valued id |
1 |
no where |
all rows |
Mechanism: an object literal is not an isSafeEqualityLiteral, so loadSubsetInternal emits no SQL WHERE. It scans the table, decodes each row (decodePersistedJsonValue gives a plain object), and filters in memory with compileSingleRowExpression. A plain object never equals the class instance. Under #2460 a distinct instance with the same toJSON() would compare equal, but a plain object does not.
The persisted wrapper's demand coverage (readDemandRows / nextCoverageRecord in persisted.ts) records that same loadSubset count, so the subset is recorded as covered with rows: 0. Offline rows are served by the same call.
User-visible effect:
- An on-demand persisted collection with
initialRender: { strategy: 'network-first', networkTimeoutMs }cannot answer a query that filters on a record-id field while offline. The query settles with no rows. - Even eager hydration (no
where) returns plain objects instead of instances, so ids and decimal values lose their type and methods after a reload.
To Reproduce
import { DatabaseSync } from 'node:sqlite'
import { IR } from '@tanstack/db'
import { SQLiteCorePersistenceAdapter } from '@tanstack/db-sqlite-persistence-core'
class RecordId {
constructor(public table: string, public id: string) {}
toString() { return `${this.table}:${this.id}` }
toJSON() { return this.toString() }
}
class Money {
#cents: number
constructor(cents: number) { this.#cents = cents }
toJSON() { return String(this.#cents) }
}
const database = new DatabaseSync(':memory:')
const driver = {
exec: async (sql: string) => { database.exec(sql) },
query: async (sql: string, params: Array<any> = []) =>
database.prepare(sql).all(...params),
run: async (sql: string, params: Array<any> = []) => {
database.prepare(sql).run(...params)
},
transaction: async (task: any) => {
database.exec('BEGIN IMMEDIATE')
try { const r = await task(driver); database.exec('COMMIT'); return r }
catch (e) { database.exec('ROLLBACK'); throw e }
},
}
const adapter = new SQLiteCorePersistenceAdapter({ driver } as any)
const target = { kind: 'eager', collectionId: 'items' } as const
await adapter.applyCommittedTx(target, {
txId: 't1', term: 1, seq: 1, rowVersion: 1,
mutations: [
{ type: 'insert', key: 'a', value: { id: new RecordId('user', 'a'), price: new Money(100) } },
{ type: 'insert', key: 'b', value: { id: new RecordId('user', 'b'), price: new Money(200) } },
],
})
const byId = await adapter.loadSubset(target, {
where: new IR.Func('eq', [new IR.PropRef(['id']), new IR.Value(new RecordId('user', 'a'))]),
})
byId.length // 0, expected 1
const all = await adapter.loadSubset(target, {})
all[0].value.id instanceof RecordId // false: a plain object
String(all[0].value.id) // "[object Object]"
JSON.stringify(all[0].value.price) // "{}": every Money instance is stored the same wayExpected behavior
A value that the app can identify should survive a write and a reopen as the same kind of value, and an equality where on it should match the stored row. This is the persistence-side counterpart of #2459 / #2460, which make the in-memory eq compare such classes by value.
Proposal for discussion: valueCodecs
An app-supplied list of codecs on persistence creation:
createBrowserWASQLitePersistence({
database,
valueCodecs: [
{
name: 'recordId',
test: (value) => value instanceof RecordId,
serialize: (value) => value.toString(),
deserialize: (text) => RecordId.parse(text),
},
],
})- Encode: a value claimed by a codec is stored as a tagged value holding the codec name and the serialized string, next to the existing
bigint/date/ Temporal tags. Built-in types keep precedence. - Decode: a tagged value goes through the matching codec's
deserialize, so the app gets real instances back in rows, row and collection metadata, and replay. - Query literals: encoded the same way, so SQL comparisons and the in-memory filter agree.
The library would hold no knowledge of any particular class.
Scope and open questions I found while reading the code:
- Encode/decode sites.
serialize/deserializePersistedRowValueare module-level and reached from about 30 sites in the adapter.toSqliteParameterValue,compileSqlExpressionandtoSqliteExpressionLiteralare module-level compile functions with no adapter instance, so codecs would have to be passed through them or the functions moved onto the adapter. Index-expression literals end up in index DDL and signatures. - Host plumbing.
SQLiteCoreAdapterOptionswould gain the option, and each host package would pass it through: browser (resolveAdapterBaseOptionscopies a fixed list today), node, electron, capacitor, expo, react-native, tauri and cloudflare. Electron's main process and renderers would each need the same codecs, since functions cannot cross IPC. - Multi-tab wire.
remote-subset-wire.tsrejects class instances (projectWireRecord→requirePlainRecord), so a follower's on-demandwhereholding such a value would presumably throwRemoteSubsetWireValueError(I have not run this). Codecs would need to apply on the wire too. - SQL prefilter. Codec values could be treated as safe equality literals, since their encoding is deterministic, so equality can use the SQL
WHEREand indexes instead of a full scan. - Ordering.
gt/lt,ORDER BYand cursor prefilters would otherwise compare the text of the tagged JSON, which can disagree with any meaningful order ("10" < "9"). Options: declare codec values unordered in SQL and leave ordering to the in-memory comparator, or let a codec supply its own comparator. - Unknown codec names on reopen. Old rows tagged with a codec that is no longer registered should fail loudly or force a reset (
schemaVersion), not decode silently as raw tagged objects. - Interaction with fix(db): compare value classes with toJSON() by their serialized value #2460. A revived instance equals the query literal in memory only with fix(db): compare value classes with toJSON() by their serialized value #2460, or if
deserializereturns interned instances. - Oracle. A codec kind fits the typed-value owner (
sqlite-persistence.typed-value-reopen) for rows, metadata, replay andeq. Itsgtand ordered-page checks need the ordering rule from point 5.
Would you accept this shape, or prefer another hook, before I open a PR?
Additional context
Until something like this exists, an app can wrap the persistence adapter: it stores such values as marked strings (a private-use character plus the value's text form) and revives them on read, converting query literals in loadSubset/scanRows options the same way. I've done this in a real browser app (wrapping loadSubset, scanRows, loadResumeSnapshot, loadCollectionMetadata, pullSince, applyCommittedTx, reconcileCommittedTx, the hydration and regular scopes, and the persistences returned by resolvePersistenceForCollection/resolvePersistenceForMode). With it, an on-demand query on a record-id field answers from the cache offline with real class instances, live updates keep persisting, and three tabs load correctly; writes from a follower tab are not specifically tested. It works, but it depends on internal adapter interfaces and may break across versions, which is why a supported hook seems worthwhile. A string side field (e.g. the key part of the id) also matches offline, but rows still decode with plain-object ids.
For record ids specifically, an adapter can also avoid this by handing TanStack DB plain strings instead of class instances. @surrealdb/tanstack-db has an opt-in proposal for that (surrealdb/tanstack-db#14, recordIds: 'string'); strings round-trip through every persistence option unchanged. That doesn't cover value classes in general (decimals, money types, classes with private fields), so a persistence-level hook like valueCodecs would still be needed for those.
Related, from reading code only (not tested): the localStorage collection already accepts parser: { parse, stringify }, which lets an app revive class instances, so there is precedent for a value hook. The IndexedDB collection stores rows with the structured clone algorithm and has no serializer option, so class instances there likely come back as plain objects with private fields lost. The codec question may apply beyond SQLite.
Activity