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

README.md

58 lines1.9 KB

1# IVM implementation for TanStack DB based on Differential Dataflow
2​
3This is an implementation of differential dataflow used by TanStack DB, forked from [@electric-sql/d2ts](https://github.com/electric-sql/d2ts), but simplified and without the complexities of multi-dimensional versioning.
4​
5It is used internally by the TanStack DB with the live queries compiled to a D2 graph. This library doesn't depend on the TanStack DB and so could be used in other projects.
6​
7The API is almost identical to D2TS, but without the need to specify a version when sending data, or to send a frontier to mark the end of a version.
8​
9### Basic Usage
10​
11Here's a simple example that demonstrates the core concepts:
12​
13```typescript
14import { D2, map, filter, debug, MultiSet } from '@tanstack/db-ivm'
15​
16// Create a new D2 graph
17const graph = new D2()
18​
19// Create an input stream
20// We can specify the type of the input stream, here we are using number.
21const input = graph.newInput<number>()
22​
23// Build a simple pipeline that:
24// 1. Takes numbers as input
25// 2. Adds 5 to each number
26// 3. Filters to keep only even numbers
27// Pipelines can have multiple inputs and outputs.
28const output = input.pipe(
29 map((x) => x + 5),
30 filter((x) => x % 2 === 0),
31 debug('output'),
33​
34// Finalize the pipeline, after this point we can no longer add operators or
35// inputs
36graph.finalize()
37​
38// Send some data
39// Data is sent as a MultiSet, which is a map of values to their multiplicity
40// Here we are sending 3 numbers (1-3), each with a multiplicity of 1
41// The key thing to understand is that the MultiSet represents a *change* to
42// the data, not the data itself. "Inserts" and "Deletes" are represented as
43// an element with a multiplicity of 1 or -1 respectively.
44input.sendData(
45 new MultiSet([
46 [1, 1],
47 [2, 1],
48 [3, 1],
49 ]),
51​
52// Process the data
53graph.run()
54​
55// Output will show:
56// 6 (from 1 + 5)
57// 8 (from 3 + 5)
58```