Defined in: packages/db/src/collection.ts:204
• T extends object = Record<string, unknown>
• TKey extends string | number = string | number
• TUtils extends UtilsRecord = {}
• TSchema extends StandardSchemaV1 = StandardSchemaV1
• TInsertInput extends object = T
new CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>(config): CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>
new CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>(config): CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>
Defined in: packages/db/src/collection.ts:407
Creates a new Collection instance
CollectionConfig<T, TKey, TSchema, TInsertInput>
Configuration object for the collection
CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>
Error if sync config is missing
config: CollectionConfig<T, TKey, TSchema, TInsertInput>;
config: CollectionConfig<T, TKey, TSchema, TInsertInput>;
Defined in: packages/db/src/collection.ts:211
id: string;
id: string;
Defined in: packages/db/src/collection.ts:331
optimisticDeletes: Set<TKey>;
optimisticDeletes: Set<TKey>;
Defined in: packages/db/src/collection.ts:221
optimisticUpserts: Map<TKey, T>;
optimisticUpserts: Map<TKey, T>;
Defined in: packages/db/src/collection.ts:220
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
Defined in: packages/db/src/collection.ts:215
syncedData: Map<TKey, T> | SortedMap<TKey, T>;
syncedData: Map<TKey, T> | SortedMap<TKey, T>;
Defined in: packages/db/src/collection.ts:216
syncedMetadata: Map<TKey, unknown>;
syncedMetadata: Map<TKey, unknown>;
Defined in: packages/db/src/collection.ts:217
transactions: SortedMap<string, Transaction<any>>;
transactions: SortedMap<string, Transaction<any>>;
Defined in: packages/db/src/collection.ts:214
utils: Record<string, Fn> = {};
utils: Record<string, Fn> = {};
Defined in: packages/db/src/collection.ts:238
get indexes(): Map<number, BaseIndex<TKey>>
get indexes(): Map<number, BaseIndex<TKey>>
Defined in: packages/db/src/collection.ts:1439
Get resolved indexes for query optimization
Map<number, BaseIndex<TKey>>
get size(): number
get size(): number
Defined in: packages/db/src/collection.ts:995
Get the current size of the collection (cached)
number
get state(): Map<TKey, T>
get state(): Map<TKey, T>
Defined in: packages/db/src/collection.ts:2038
Gets the current state of the collection as a Map
const itemsMap = collection.state
console.log(`Collection has ${itemsMap.size} items`)
for (const [key, item] of itemsMap) {
console.log(`${key}: ${item.title}`)
}
// Check if specific item exists
if (itemsMap.has("todo-1")) {
console.log("Todo 1 exists:", itemsMap.get("todo-1"))
}
const itemsMap = collection.state
console.log(`Collection has ${itemsMap.size} items`)
for (const [key, item] of itemsMap) {
console.log(`${key}: ${item.title}`)
}
// Check if specific item exists
if (itemsMap.has("todo-1")) {
console.log("Todo 1 exists:", itemsMap.get("todo-1"))
}
Map<TKey, T>
Map containing all items in the collection, with keys as identifiers
get status(): CollectionStatus
get status(): CollectionStatus
Defined in: packages/db/src/collection.ts:336
Gets the current status of the collection
get toArray(): T[]
get toArray(): T[]
Defined in: packages/db/src/collection.ts:2071
Gets the current state of the collection as an Array
T[]
An Array containing all items in the collection
iterator: IterableIterator<[TKey, T]>
iterator: IterableIterator<[TKey, T]>
Defined in: packages/db/src/collection.ts:1046
Get all entries (virtual derived state)
IterableIterator<[TKey, T]>
cleanup(): Promise<void>
cleanup(): Promise<void>
Defined in: packages/db/src/collection.ts:583
Clean up the collection by stopping sync and clearing data This can be called manually or automatically by garbage collection
Promise<void>
commitPendingTransactions(): void
commitPendingTransactions(): void
Defined in: packages/db/src/collection.ts:1082
Attempts to commit pending synced transactions if there are no active transactions This method processes operations from pending transactions and applies them to the synced data
void
createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>
createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>
Defined in: packages/db/src/collection.ts:1344
Creates an index on a collection for faster queries. Indexes significantly improve query performance by allowing binary search and range queries instead of full scans.
• TResolver extends IndexResolver<TKey> = typeof BTreeIndex
The type of the index resolver (constructor or async loader)
(row) => any
Function that extracts the indexed value from each item
IndexOptions<TResolver> = {}
Configuration including index type and type-specific options
IndexProxy<TKey>
An index proxy that provides access to the index when ready
// Create a default B+ tree index
const ageIndex = collection.createIndex((row) => row.age)
// Create a ordered index with custom options
const ageIndex = collection.createIndex((row) => row.age, {
indexType: BTreeIndex,
options: { compareFn: customComparator },
name: 'age_btree'
})
// Create an async-loaded index
const textIndex = collection.createIndex((row) => row.content, {
indexType: async () => {
const { FullTextIndex } = await import('./indexes/fulltext.js')
return FullTextIndex
},
options: { language: 'en' }
})
// Create a default B+ tree index
const ageIndex = collection.createIndex((row) => row.age)
// Create a ordered index with custom options
const ageIndex = collection.createIndex((row) => row.age, {
indexType: BTreeIndex,
options: { compareFn: customComparator },
name: 'age_btree'
})
// Create an async-loaded index
const textIndex = collection.createIndex((row) => row.content, {
indexType: async () => {
const { FullTextIndex } = await import('./indexes/fulltext.js')
return FullTextIndex
},
options: { language: 'en' }
})
currentStateAsChanges(options): ChangeMessage<T, string | number>[]
currentStateAsChanges(options): ChangeMessage<T, string | number>[]
Defined in: packages/db/src/collection.ts:2113
Returns the current state of the collection as an array of changes
CurrentStateAsChangesOptions<T> = {}
Options including optional where filter
ChangeMessage<T, string | number>[]
An array of changes
// Get all items as changes
const allChanges = collection.currentStateAsChanges()
// Get only items matching a condition
const activeChanges = collection.currentStateAsChanges({
where: (row) => row.status === 'active'
})
// Get only items using a pre-compiled expression
const activeChanges = collection.currentStateAsChanges({
whereExpression: eq(row.status, 'active')
})
// Get all items as changes
const allChanges = collection.currentStateAsChanges()
// Get only items matching a condition
const activeChanges = collection.currentStateAsChanges({
where: (row) => row.status === 'active'
})
// Get only items using a pre-compiled expression
const activeChanges = collection.currentStateAsChanges({
whereExpression: eq(row.status, 'active')
})
delete(keys, config?): Transaction<any>
delete(keys, config?): Transaction<any>
Defined in: packages/db/src/collection.ts:1939
Deletes one or more items from the collection
Single key or array of keys to delete
TKey | TKey[]
Optional configuration including metadata
Transaction<any>
A Transaction object representing the delete operation(s)
// Delete a single item
const tx = collection.delete("todo-1")
await tx.isPersisted.promise
// Delete a single item
const tx = collection.delete("todo-1")
await tx.isPersisted.promise
// Delete multiple items
const tx = collection.delete(["todo-1", "todo-2"])
await tx.isPersisted.promise
// Delete multiple items
const tx = collection.delete(["todo-1", "todo-2"])
await tx.isPersisted.promise
// Delete with metadata
const tx = collection.delete("todo-1", { metadata: { reason: "completed" } })
await tx.isPersisted.promise
// Delete with metadata
const tx = collection.delete("todo-1", { metadata: { reason: "completed" } })
await tx.isPersisted.promise
// Handle errors
try {
const tx = collection.delete("item-1")
await tx.isPersisted.promise
console.log('Delete successful')
} catch (error) {
console.log('Delete failed:', error)
}
// Handle errors
try {
const tx = collection.delete("item-1")
await tx.isPersisted.promise
console.log('Delete successful')
} catch (error) {
console.log('Delete failed:', error)
}
entries(): IterableIterator<[TKey, T]>
entries(): IterableIterator<[TKey, T]>
Defined in: packages/db/src/collection.ts:1034
Get all entries (virtual derived state)
IterableIterator<[TKey, T]>
forEach(callbackfn): void
forEach(callbackfn): void
Defined in: packages/db/src/collection.ts:1055
Execute a callback for each entry in the collection
(value, key, index) => void
void
generateGlobalKey(key, item): string
generateGlobalKey(key, item): string
Defined in: packages/db/src/collection.ts:1306
any
any
string
get(key): undefined | T
get(key): undefined | T
Defined in: packages/db/src/collection.ts:959
Get the current value for a key (virtual derived state)
TKey
undefined | T
getKeyFromItem(item): TKey
getKeyFromItem(item): TKey
Defined in: packages/db/src/collection.ts:1302
T
TKey
has(key): boolean
has(key): boolean
Defined in: packages/db/src/collection.ts:977
Check if a key exists in the collection (virtual derived state)
TKey
boolean
insert(data, config?):
| Transaction<Record<string, unknown>>
| Transaction<T>
insert(data, config?):
| Transaction<Record<string, unknown>>
| Transaction<T>
Defined in: packages/db/src/collection.ts:1594
Inserts one or more items into the collection
TInsertInput | TInsertInput[]
Optional configuration including metadata
| Transaction<Record<string, unknown>> | Transaction<T>
A Transaction object representing the insert operation(s)
If the data fails schema validation
// Insert a single todo (requires onInsert handler)
const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
await tx.isPersisted.promise
// Insert a single todo (requires onInsert handler)
const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
await tx.isPersisted.promise
// Insert multiple todos at once
const tx = collection.insert([
{ id: "1", text: "Buy milk", completed: false },
{ id: "2", text: "Walk dog", completed: true }
])
await tx.isPersisted.promise
// Insert multiple todos at once
const tx = collection.insert([
{ id: "1", text: "Buy milk", completed: false },
{ id: "2", text: "Walk dog", completed: true }
])
await tx.isPersisted.promise
// Insert with metadata
const tx = collection.insert({ id: "1", text: "Buy groceries" },
{ metadata: { source: "mobile-app" } }
)
await tx.isPersisted.promise
// Insert with metadata
const tx = collection.insert({ id: "1", text: "Buy groceries" },
{ metadata: { source: "mobile-app" } }
)
await tx.isPersisted.promise
// Handle errors
try {
const tx = collection.insert({ id: "1", text: "New item" })
await tx.isPersisted.promise
console.log('Insert successful')
} catch (error) {
console.log('Insert failed:', error)
}
// Handle errors
try {
const tx = collection.insert({ id: "1", text: "New item" })
await tx.isPersisted.promise
console.log('Insert successful')
} catch (error) {
console.log('Insert failed:', error)
}
isReady(): boolean
isReady(): boolean
Defined in: packages/db/src/collection.ts:294
Check if the collection is ready for use Returns true if the collection has been marked as ready by its sync implementation
boolean
true if the collection is ready, false otherwise
if (collection.isReady()) {
console.log('Collection is ready, data is available')
// Safe to access collection.state
} else {
console.log('Collection is still loading')
}
if (collection.isReady()) {
console.log('Collection is ready, data is available')
// Safe to access collection.state
} else {
console.log('Collection is still loading')
}
keys(): IterableIterator<TKey>
keys(): IterableIterator<TKey>
Defined in: packages/db/src/collection.ts:1002
Get all keys (virtual derived state)
IterableIterator<TKey>
map<U>(callbackfn): U[]
map<U>(callbackfn): U[]
Defined in: packages/db/src/collection.ts:1067
Create a new array with the results of calling a function for each entry in the collection
• U
(value, key, index) => U
U[]
onFirstReady(callback): void
onFirstReady(callback): void
Defined in: packages/db/src/collection.ts:272
Register a callback to be executed when the collection first becomes ready Useful for preloading collections
() => void
Function to call when the collection first becomes ready
void
collection.onFirstReady(() => {
console.log('Collection is ready for the first time')
// Safe to access collection.state now
})
collection.onFirstReady(() => {
console.log('Collection is ready for the first time')
// Safe to access collection.state now
})
onTransactionStateChange(): void
onTransactionStateChange(): void
Defined in: packages/db/src/collection.ts:2271
Trigger a recomputation when transactions change This method should be called by the Transaction class when state changes
void
preload(): Promise<void>
preload(): Promise<void>
Defined in: packages/db/src/collection.ts:544
Preload the collection data by starting sync if not already started Multiple concurrent calls will share the same promise
Promise<void>
startSyncImmediate(): void
startSyncImmediate(): void
Defined in: packages/db/src/collection.ts:450
Start sync immediately - internal method for compiled queries This bypasses lazy loading for special cases like live query results
void
stateWhenReady(): Promise<Map<TKey, T>>
stateWhenReady(): Promise<Map<TKey, T>>
Defined in: packages/db/src/collection.ts:2052
Gets the current state of the collection as a Map, but only resolves when data is available Waits for the first sync commit to complete before resolving
Promise<Map<TKey, T>>
Promise that resolves to a Map containing all items in the collection
subscribeChanges(callback, options): () => void
subscribeChanges(callback, options): () => void
Defined in: packages/db/src/collection.ts:2158
Subscribe to changes in the collection
(changes) => void
Function called when items change
SubscribeChangesOptions<T> = {}
Subscription options including includeInitialState and where filter
Function
Unsubscribe function - Call this to stop listening for changes
void
// Basic subscription
const unsubscribe = collection.subscribeChanges((changes) => {
changes.forEach(change => {
console.log(`${change.type}: ${change.key}`, change.value)
})
})
// Later: unsubscribe()
// Basic subscription
const unsubscribe = collection.subscribeChanges((changes) => {
changes.forEach(change => {
console.log(`${change.type}: ${change.key}`, change.value)
})
})
// Later: unsubscribe()
// Include current state immediately
const unsubscribe = collection.subscribeChanges((changes) => {
updateUI(changes)
}, { includeInitialState: true })
// Include current state immediately
const unsubscribe = collection.subscribeChanges((changes) => {
updateUI(changes)
}, { includeInitialState: true })
// Subscribe only to changes matching a condition
const unsubscribe = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
includeInitialState: true,
where: (row) => row.status === 'active'
})
// Subscribe only to changes matching a condition
const unsubscribe = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
includeInitialState: true,
where: (row) => row.status === 'active'
})
// Subscribe using a pre-compiled expression
const unsubscribe = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
includeInitialState: true,
whereExpression: eq(row.status, 'active')
})
// Subscribe using a pre-compiled expression
const unsubscribe = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
includeInitialState: true,
whereExpression: eq(row.status, 'active')
})
subscribeChangesKey(
key,
listener,
__namedParameters): () => void
subscribeChangesKey(
key,
listener,
__namedParameters): () => void
Defined in: packages/db/src/collection.ts:2197
Subscribe to changes for a specific key
TKey
ChangeListener<T, TKey>
boolean = false
Function
void
toArrayWhenReady(): Promise<T[]>
toArrayWhenReady(): Promise<T[]>
Defined in: packages/db/src/collection.ts:2081
Gets the current state of the collection as an Array, but only resolves when data is available Waits for the first sync commit to complete before resolving
Promise<T[]>
Promise that resolves to an Array containing all items in the collection
update<TItem>(key, callback): Transaction
update<TItem>(key, callback): Transaction
Defined in: packages/db/src/collection.ts:1725
Updates one or more items in the collection using a callback function
• TItem extends object = T
unknown[]
(drafts) => void
A Transaction object representing the update operation(s)
If the updated data fails schema validation
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.isPersisted.promise
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}
// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.isPersisted.promise
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}
update<TItem>(
keys,
config,
callback): Transaction
update<TItem>(
keys,
config,
callback): Transaction
Defined in: packages/db/src/collection.ts:1731
Updates one or more items in the collection using a callback function
• TItem extends object = T
unknown[]
Single key or array of keys to update
(drafts) => void
A Transaction object representing the update operation(s)
If the updated data fails schema validation
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.isPersisted.promise
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}
// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.isPersisted.promise
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}
update<TItem>(id, callback): Transaction
update<TItem>(id, callback): Transaction
Defined in: packages/db/src/collection.ts:1738
Updates one or more items in the collection using a callback function
• TItem extends object = T
unknown
(draft) => void
A Transaction object representing the update operation(s)
If the updated data fails schema validation
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.isPersisted.promise
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}
// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.isPersisted.promise
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}
update<TItem>(
id,
config,
callback): Transaction
update<TItem>(
id,
config,
callback): Transaction
Defined in: packages/db/src/collection.ts:1744
Updates one or more items in the collection using a callback function
• TItem extends object = T
unknown
(draft) => void
A Transaction object representing the update operation(s)
If the updated data fails schema validation
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.isPersisted.promise
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}
// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.isPersisted.promise
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}
values(): IterableIterator<T>
values(): IterableIterator<T>
Defined in: packages/db/src/collection.ts:1022
Get all values (virtual derived state)
IterableIterator<T>