Quick Start
This page takes you from nothing to a working program with an entity collection and its store slot, an index, a sorted view, a subscription and a flush. Each step links to the page that covers that piece in full.
The steps add up to one program. The blocks marked setup hold its declarations, in
order, and every example builds on them and on the writes the earlier steps made.
The comment after a call shows what it logs.
The short version
With React and a database with schemas, a collection and a component that renders one of its entities:
import { OIMDB, createOIMEntitySlotCollectionStoreAggregate } from '@oimdb/core';
import { OIMDBProvider, useOIMDB, useOIMSelector } from '@oimdb/react';
type TTodo = { id: string; title: string; done: boolean };
const createTodoSchema = (db: OIMDB) => ({ todos: createOIMEntitySlotCollectionStoreAggregate<TTodo>(db) });
const createAppDB = () => new OIMDB({ createSchemas: (db) => ({ default: createTodoSchema(db) }) });
const useAppDB = useOIMDB.withTypes<ReturnType<typeof createAppDB>>();
const db = createAppDB();
db.schemas.default.todos.writeSlotContentByKey('t1', { id: 't1', title: 'Buy milk', done: false });
db.schemas.default.todos.writeSlotContentByKey('t2', { id: 't2', title: 'Call mum', done: false });
function Todo({ id }: { id: string }) {
const db = useAppDB();
const { todos } = db.schemas.default;
const todo = useOIMSelector(() => todos.getSlotByKey(id).entity);
if (todo === undefined) return null;
const toggle = () => {
todos.getSlotByKey(id).updateEntity({ done: !todo.done });
db.flush();
};
return <li onClick={toggle}>{todo.done ? '✓ ' : ''}{todo.title}</li>;
}
export const App = () => <OIMDBProvider db={db}><ul><Todo id="t1" /><Todo id="t2" /></ul></OIMDBProvider>;
Clicking a todo re-renders that one Todo and nothing else, at the db.flush() the handler calls: a
database delivers only when it is flushed, every write since the last flush at once.
The steps below take the same engine apart: the runtime, the collection service under the aggregate, subscriptions, indexes and sorted views.
1. The runtime
Setup shared by the examples on this page
import { OIMDB, OIMEffectService, OIMSlotMapStoreService, OIMSetBucketContentService, type TOIMStoreKey } from '@oimdb/core';
const db = new OIMDB();
const effectService = OIMEffectService.INSTANCE;
OIMDB holds what every collection on a page has to share: the clock, the default channel slot
(db.defaultChannelSlot) and the unused-slot collector slot (db.collectorSlot). The
optional strategies (entityWriter, slotReleasePolicy, slotStamp, indexKeysService) are an
OIMDefaults passed as defaults to each factory (createOIMSlotCollectionService,
createOIMSlotCollectionIndexService, …). Every service is stateless: the state lives on the store slots and the
slots, so OIMEffectService.INSTANCE is the one effect service there is.
Collections that are meant to wake each other's subscribers have to share a channel slot.
Creating every store slot with createStoreSlot(db) guarantees that, so you never wire a
channel by hand.
The channel is the clock and the delivery pass. A frame delivers
every write made since the previous frame: each effect those writes scheduled runs
once, then the after-each-frame handlers run (see the
glossary). With no options, nothing is delivered until
you call db.flush(). A write marks what it changed and asks for a frame. The
frame runs when you flush, and every effect whose sources moved runs once in it,
however many writes landed before it. A test flushes where it wants to assert. An
application hands the flush to its orchestrator: with cnstra that is one line,
and every synchronous turn of a stimulation becomes one frame. See
OIMDB with cnstra.
To have the channel decide when to deliver, give it a scheduler:
const scheduledDb = new OIMDB({
channelScheduler: (flush) => { void Promise.resolve().then(flush); },
});
// the first write of a turn schedules one flush in a microtask; no db.flush() call is needed
The model behind the frame is on The model. The rules for writing during a frame are under The frame.
2. An entity collection and its store slot
Setup shared by the examples on this page
type Card = { id: string; deck: string; title: string; rank: number };
const cardService = createOIMSlotCollectionService({ slotContentService: createOIMEntityContentService<Card>() });
const cards = cardService.createStoreSlot(db);
console.log(cardService.hasSlotContentByKey(cards, 'c1')); // false: nothing is written yet, and the read mints nothing
An entity collection files entities by the key you write them under. The collection service holds no data: you make it once per entity type, and
each createStoreSlot(db) is one collection of that type, a store slot carrying its own
store. The collection service has the reads (getSlotByKey, holdSlotByKey, peekSlotByKey,
getSlots, the column doors); its slotContentService has the writes. A door that works on the
store takes the store slot first; a door that works on a slot it is handed takes only the slot.
createOIMSlotCollectionService is a convenience wrapper over the base layer (section 9). It also accepts
entityWriter (how a write lands: in place or replacing, see
The two writers) and slotReleasePolicy
(when a slot goes, see
Releasing an identity).
Both are picked here, at construction, so no write branches on them later.
Collections and keys (scalar and composite) are covered on Collections and identities.
3. Write
Setup shared by the examples on this page
const first = cardService.writeSlotContentByKey(cards, 'c1', { id: 'c1', deck: 'd1', title: 'alpha', rank: 1 });
const second = cardService.writeSlotContentByKey(cards, 'c2', { id: 'c2', deck: 'd1', title: 'beta', rank: 2 });
console.log(first.entity?.title); // alpha
console.log(first === cardService.getSlotByKey(cards, 'c1')); // true: the key resolves to the same identity
writeSlotContentByKey returns the slot, which is the entity's identity. Keep it. Every
later operation that goes through the slot (slot.updateEntity(patch),
slot.clearSlotContent(), a subscription) does no lookup to find the entity.
Getting the slot back later with cardService.getSlotByKey(cards, 'c1') costs a map read.
writeSlotContentByKey is the only write that takes a key: resolve the slot once, then write
through it.
A key is resolved to an identity once, and everything after goes through the identity. See The model and Writing.
After this step the store slot cards holds c1 (deck d1, title alpha, rank 1) and
c2 (deck d1, title beta, rank 2).
4. Subscribe and flush
const effect = effectService.createEffect(db, () => {
console.log('card is now', first.entity?.title);
}, [first]);
first.updateEntity({ title: 'ALPHA' });
first.updateEntity({ title: 'ALPHA!' });
db.flush(); // -> "card is now ALPHA!" — once, for both writes
effectService.disposeEffect(effect);
An effect is a plain object, built and disposed by OIMEffectService.INSTANCE.
effectService.createEffect(db, body, sourceSlots?, sourceComputeds?, sourceTrackingComputeds?) builds an effect. Its body
runs in the next frame after one of its sources moved, once per frame. It only reacts to writes
made after it was created. effectService.createAndRunEffect(…) is the same, but also runs
the body once at creation. effectService.subscribeEffect(…) is createEffect that hands back a
disposer. effectService.disposeEffect(effect) gives the subscription back.
A subscription is an effect over slots rather than a selector over the whole
state, so a write to c1 does not call anything subscribed to another entity. See
Reading and subscribing.
Now c1 has the title ALPHA!.
5. Watch one column
const titleColumn = first.holdColumnSlot('title');
const titleEffect = effectService.createEffect(db, () => {
console.log('title is now', first.entity?.title);
}, [titleColumn]);
first.updateEntity({ rank: 5 }); // does not run it
db.flush(); // logs nothing
first.updateEntity({ title: 'alpha' }); // does
db.flush(); // -> "title is now alpha"
effectService.disposeEffect(titleEffect);
titleColumn.unholdSlot();
Every column of an entity can have a slot of its own. Use it when a consumer
renders a single field of an entity whose other fields change often.
The root of the column form is the column slot.
Getting it is a separate call on the collection service: holdColumnSlot(slot, name) creates it and
holds it, unholdColumnSlot(column) gives the hold back, and the column slot is
released once its last effect is disposed and nothing holds it. See
Subscribing to one column.
Now c1 has the title alpha and rank 5.
6. An index
Setup shared by the examples on this page
import { createOIMSlotCollectionIndexService } from '@oimdb/core';
const cardsByDeckService = createOIMSlotCollectionIndexService({
entityService: cardService,
selectKey: (card: Card) => card.deck,
});
const cardsByDeck = cardsByDeckService.createIndexStoreSlot(cards);
const deckOne = cardsByDeckService.holdSlotByKey(cardsByDeck, 'd1');
const onDeckOne = effectService.createEffect(db, () => {
console.log('d1 has', deckOne.getBucketMemberSlotCount(), 'card(s)');
}, [deckOne]);
console.log(deckOne.getBucketMemberSlotCount()); // 2: c1 and c2, filed when the bucket was minted
cardService.writeSlotContentByKey(cards, 'c3', { id: 'c3', deck: 'd1', title: 'gamma', rank: 1 });
db.flush(); // -> "d1 has 3 card(s)"
first.updateEntity({ title: 'Alpha' });
db.flush(); // logs nothing: c1 is still in d1
second.updateEntity({ deck: 'd2' });
db.flush(); // -> "d1 has 2 card(s)"
effectService.disposeEffect(onDeckOne);
deckOne.unholdSlot();
An index files the entities of one entity store slot into buckets by the key
selectKey derives from each entity. Use it when an entity's place follows from
its own columns ("the cards of a deck"). Moving a card is then a write to
the card. The index service is made once per entity collection type; its
createIndexStoreSlot(cards) returns the index's bucket store slot for that one
entity store slot, and disposeIndexStoreSlot takes it down.
- The index store slot listens to the source store slot itself; the entity collection does not know about indexes.
- A bucket wakes on membership only: an entity joining or leaving it. A write to an entity that stays in the bucket wakes the entity's own subscribers and leaves the bucket's alone.
- A bucket is minted on its first
getSlotByKey/holdSlotByKeyand is filled from the entities written before that, without a flush. - The bucket strategy is the index's
slotContentServiceoption: array-driven (arrival order) by default,new OIMSetBucketContentService()for no order. The array-driven one is what a sorted view reconciles against.
holdSlotByKey takes a counted reference on the bucket. Give it back with
slot.unholdSlot() once you are done. That count, plus the effects on the bucket, is all
that keeps the bucket alive. See
Indexes,
and Why an index looks like this for why membership is
pushed.
Now deck d1 holds c1 (Alpha, rank 5) and c3 (gamma, rank 1); c2 is in d2.
7. A sorted view
Setup shared by the examples on this page
import { createOIMSortedComputedService } from '@oimdb/core';
const cardsByRankService = createOIMSortedComputedService({
indexService: cardsByDeckService,
sortColumns: [{ columnName: 'rank', direction: 'asc' }],
});
const cardsByRank = cardsByRankService.createSortedStoreSlot(cardsByDeck);
const sortedDeckOne = cardsByRankService.holdSlotByKey(cardsByRank, 'd1');
const onSorted = effectService.createAndRunEffect(db, () => {
console.log(sortedDeckOne.value.map((slot) => slot.entity?.title));
}, [], [sortedDeckOne]);
// -> [ 'gamma', 'Alpha' ]
first.updateEntity({ title: 'ALPHA' });
db.flush(); // logs nothing: no member arrived or left, and no rank changed
first.updateEntity({ rank: 0 });
db.flush(); // -> [ 'ALPHA', 'gamma' ]
second.updateEntity({ deck: 'd1' });
db.flush(); // -> [ 'ALPHA', 'gamma', 'beta' ]
effectService.disposeEffect(onSorted);
sortedDeckOne.unholdSlot();
A sorted view is a computed store slot over an index store slot: one computed slot per
bucket key, whose value is that bucket's entity slots in order. The sorted service takes no
db: its store slots run on the channel slot of the index store slot they sort.
- Its sources decide when it re-sorts: the bucket slot (membership) plus one
bucket column slot for each column in
sortColumns. A write to a column that is not listed does not re-derive it. Acomparatorreplaces the column order. Given withoutsortColumns, it re-sorts on any write to a member. - The order is derived by the read that asks for it (
slot.value), never ahead of time. The effect above names it in the third argument,sourceComputeds, and the channel refreshes it before it decides whether to run the body.slot.valueis a getter that settles the computed before answering. - A re-sort that yields the same sequence keeps the previous array, so a consumer that compares by reference needs no comparison of its own.
A bucket does not sort. The order lives in this derivation over the index, because the order belongs to the read and membership belongs to the write. See Ordering and The compute graph.
8. A bucket you fill yourself
Setup shared by the examples on this page
import { type TOIMEntitySlot, createOIMEntityContentService, createOIMSlotCollectionService, OIMPositionalArrayBucketContentService, OIMBucketCommands } from '@oimdb/core';
const searchResultService = createOIMSlotCollectionService({ slotContentService: new OIMPositionalArrayBucketContentService<TOIMEntitySlot<Card>>({ bucketCommands: new OIMBucketCommands({ maxCommandsPerSlot: undefined }) }) });
const searchResults = searchResultService.createStoreSlot(db);
const alphaQuery = searchResultService.holdSlotByKey(searchResults, 'q:alpha');
alphaQuery.writeSlotContent([first]);
db.flush();
const onResults = effectService.createEffect(db, () => {
console.log('q:alpha has', alphaQuery.getBucketMemberSlotCount(), 'result(s)');
}, [alphaQuery]);
alphaQuery.writeSlotContent([first, second]);
db.flush(); // -> "q:alpha has 2 result(s)"
effectService.disposeEffect(onResults);
alphaQuery.unholdSlot();
A bucket collection without an index is manual: what a bucket holds is yours to write. Use it when membership is a fact about a response rather than about the entity: a search result, a page of server ids, a selection. No column can express "the server did not return these three", so the code that received the response is the only place that can say which slots belong. When membership follows from a column, use the index from step 6 instead.
writeSlotContent(bucket, slots) states the whole list; there are also position
writes and delta writes. See
Writing a bucket's slots.
9. The same, from the base layer
A collection is a content service — the strategy for what a slot holds — and a collection service over it, with a store service of your choice:
import { type TOIMBucketSlotsSetStore } from '@oimdb/core';
const baseCardService = createOIMSlotCollectionService({
slotContentService: createOIMEntityContentService<Card>(),
slotStoreService: new OIMSlotMapStoreService<TOIMEntitySlot<Card, TOIMStoreKey>>(),
});
const baseCards = baseCardService.createStoreSlot(db);
const unorderedService = createOIMSlotCollectionService({ slotContentService: new OIMSetBucketContentService<TOIMEntitySlot<Card>>() });
const unordered = unorderedService.createStoreSlot(db);
const alpha = baseCardService.writeSlotContentByKey(baseCards, 'c1', { id: 'c1', deck: 'd1', title: 'alpha', rank: 1 });
const beta = baseCardService.writeSlotContentByKey(baseCards, 'c2', { id: 'c2', deck: 'd1', title: 'beta', rank: 2 });
const all = unorderedService.holdSlotByKey(unordered, 'all');
all.writeSlotContent([beta, alpha]);
db.flush();
console.log(all.getBucketMemberSlotCount()); // 2
all.unholdSlot();
The entity content service has no required option; slotStoreService
defaults to a Map store, and the optional ones (entityWriter, slotEmptinessPolicy,
slotReleasePolicy, columnSlotStoreService or columnNames) fall back to the defaults option
(an OIMDefaults) and then to the built-in defaults. The bucket content service is the strategy: an
OIMPositionalArrayBucketContentService keeps the order you wrote and has the positional
writes; an OIMSetBucketContentService has no positions to write. See
Architecture
for every strategy picked at construction.
What to know before you go further
- A read mints, and the collector takes the mint back.
cardService.getSlotByKey(cards, pk)always returns a slot. For a key that has none it mints one and hands it to the unused-slot collector, which gives it back at the nextflush(). To keep a key whose value has not arrived yet, usecardService.holdSlotByKey(cards, pk). See The four doors. - A slot with content stays until you clear it. With no
slotReleasePolicy, a collection is built withOIMSlotAtEmptyReleasePolicy.INSTANCE: an empty slot goes once nothing holds it, and a slot with content is kept. Policies that drop content nobody is looking at are opt-in. See Releasing an identity. - A write anywhere inside a flush throws: in an effect body, in
onBeforeFlush, and in every after-each-frame handler. To write in response to a change, write afterflush()has returned. AOIMChannelService.INSTANCE.subscribeAfterEachFrame(channelSlot, fn)handler still runs inside the flush. See The rules. slot.clearSlotContent()removes the value and keeps the identity. Existing subscribers stay subscribed, and a manual bucket that holds the slot still holds it. Taking it out is your job.- The stored object is the one you passed in. The default insert strategy
(
insertOIMEntityWithoutCopy) keeps it, and the in-place writer patches that same object afterwards. PassentityInserter: insertOIMEntityWithCopyif you must keep your object untouched.