@rocicorp/zero 1.11.0-canary.20 → 1.11.0-canary.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +0 -5
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +1 -1
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zqlite/src/table-source.d.ts +0 -1
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +0 -3
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +1 -1
|
@@ -88,7 +88,6 @@ export declare class TableSource implements Source {
|
|
|
88
88
|
* source's `shouldYield` says to, and must not be interleaved with a push.
|
|
89
89
|
*/
|
|
90
90
|
writePendingChanges(): Stream<'yield'>;
|
|
91
|
-
hasConnections(): boolean;
|
|
92
91
|
connect(sort: Ordering | undefined, filters?: Condition, splitEditKeys?: Set<string>, debug?: DebugDelegate): SourceInput;
|
|
93
92
|
toSQLiteRow(row: Row): Row;
|
|
94
93
|
push(change: SourceChange): Stream<'yield'>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-source.d.ts","sourceRoot":"","sources":["../../../../zqlite/src/table-source.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,+BAA+B,CAAC;AAM7D,OAAO,KAAK,EAAC,SAAS,EAAE,QAAQ,EAAC,MAAM,gCAAgC,CAAC;AACxE,OAAO,KAAK,EAAC,GAAG,EAAQ,MAAM,iCAAiC,CAAC;AA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,MAAM,EAAE,WAAW,CAAC,GACvC,SAAS,OAAO,EAAE,CAEpB;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,SAAS,wCAa/C;AAED,wBAAgB,eAAe,CAC7B,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EACvC,GAAG,EAAE,GAAG,EACR,SAAS,EAAE,MAAM,GAChB,GAAG,CAaL;AAyCD,qBAAa,qBAAsB,SAAQ,KAAK;CAAG"}
|
|
@@ -165,9 +165,6 @@ var TableSource = class {
|
|
|
165
165
|
compareRows: connection.compareRows
|
|
166
166
|
};
|
|
167
167
|
}
|
|
168
|
-
hasConnections() {
|
|
169
|
-
return this.#connections.length > 0;
|
|
170
|
-
}
|
|
171
168
|
connect(sort, filters, splitEditKeys, debug) {
|
|
172
169
|
const transformedFilters = transformFilters(filters);
|
|
173
170
|
const unordered = sort === void 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-source.js","names":["#dbCache","#connections","#connectionIndex","#table","#columns","#uniqueIndexes","#primaryKey","#logConfig","#lc","#shouldYield","#skipUnobservableChanges","#primaryKeySort","#stmts","#getStatementsFor","#delta","#rowsRead","#allColumns","#fetch","#getSchema","#queryRows","#requestToSQL","#withPendingDelta","#overlay","#mapFromSQLiteTypes","#writeChange","#pushEpoch","#writeChangeToDelta","#syncedDeleteKey","#getRowStmtCache","#getRowStmt"],"sources":["../../../../zqlite/src/table-source.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport type {LogContext} from '@rocicorp/logger';\nimport SQLite3Database from '@rocicorp/zero-sqlite3';\nimport type {LogConfig} from '../../otel/src/log-options.ts';\nimport {timeSampled} from '../../otel/src/maybe-time.ts';\nimport {assert, unreachable} from '../../shared/src/asserts.ts';\nimport {getOrInsertComputed} from '../../shared/src/map.ts';\nimport {must} from '../../shared/src/must.ts';\nimport type {Writable} from '../../shared/src/writable.ts';\nimport type {Condition, Ordering} from '../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../zero-protocol/src/primary-key.ts';\nimport type {\n SchemaValue,\n ValueType,\n} from '../../zero-schema/src/table-schema.ts';\nimport type {DebugDelegate} from '../../zql/src/builder/debug-delegate.ts';\nimport {\n createPredicate,\n transformFilters,\n type NoSubqueryCondition as StrictNoSubqueryCondition,\n} from '../../zql/src/builder/filter.ts';\nimport {ChangeType} from '../../zql/src/ivm/change-type.ts';\nimport {ConnectionIndex} from '../../zql/src/ivm/connection-index.ts';\nimport {\n makeComparator,\n type Comparator,\n type Node,\n} from '../../zql/src/ivm/data.ts';\nimport {\n generateWithOverlay,\n generateWithOverlayUnordered,\n generateWithStart,\n genPushAndWriteWithSplitEdit,\n type Connection,\n type Overlay,\n} from '../../zql/src/ivm/memory-source.ts';\nimport {type FetchRequest} from '../../zql/src/ivm/operator.ts';\nimport type {SourceSchema} from '../../zql/src/ivm/schema.ts';\nimport {SourceChangeIndex} from '../../zql/src/ivm/source-change-index.ts';\nimport {\n type Source,\n type SourceChange,\n type SourceInput,\n} from '../../zql/src/ivm/source.ts';\nimport type {Stream} from '../../zql/src/ivm/stream.ts';\nimport {assertOrderingIncludesPK} from '../../zql/src/query/complete-ordering.ts';\nimport type {Database, Statement} from './db.ts';\nimport {compile, format, sql} from './internal/sql.ts';\nimport {StatementCache} from './internal/statement-cache.ts';\nimport {\n generateWithPendingDelta,\n generateWithPendingDeltaUnordered,\n NOT_OVERRIDDEN,\n PendingDelta,\n} from './pending-delta.ts';\nimport {\n buildSelectQueries,\n toSQLiteType,\n type NoSubqueryCondition,\n} from './query-builder.ts';\n\ntype Statements = {\n readonly cache: StatementCache;\n readonly insert: Statement;\n readonly delete: Statement;\n readonly update: Statement | undefined;\n readonly checkExists: Statement;\n readonly getExisting: Statement;\n};\n\nlet eventCount = 0;\n\nexport type TableSourceOptions = {\n /**\n * When set, a pushed change that the filters of every connection reject\n * is neither pushed nor applied to the backing table, on the grounds that\n * no connection can observe it. This departs from the `Source.push`\n * contract (a push commits the change to the source), so it is only\n * appropriate when the caller does not read the table through any other\n * path and replaces the table's contents afterwards, as the view-syncer's\n * pipeline driver does when it advances to the next snapshot.\n */\n skipUnobservableChanges?: boolean | undefined;\n\n /**\n * When set, pushed changes are held in an in-memory {@link PendingDelta}\n * merged into every read instead of being written to the backing table.\n * The delta is dropped when the source moves to the next snapshot. This is\n * the initial mode; see {@link TableSource.setDeferWrites}.\n */\n deferWrites?: boolean | undefined;\n};\n\n/**\n * A source that is backed by a SQLite table.\n *\n * Values are written to the backing table _after_ being vended by the source.\n *\n * This ordering of events is to ensure self joins function properly. That is,\n * we can't reveal a value to an output before it has been pushed to that output.\n *\n * The code is fairly straightforward except for:\n * 1. Dealing with a `fetch` that has a basis of `before`.\n * 2. Dealing with compound orders that have differing directions (a ASC, b DESC, c ASC)\n *\n * See comments in relevant functions for more details.\n */\nexport class TableSource implements Source {\n readonly #dbCache = new WeakMap<Database, Statements>();\n readonly #connections: Connection[] = [];\n // Indexes #connections by the static equality constraints in their filters\n // so that a push can cheaply skip rows that no connection could accept.\n readonly #connectionIndex = new ConnectionIndex<Connection>();\n readonly #table: string;\n readonly #columns: Record<string, SchemaValue>;\n // Maps sorted columns JSON string (e.g. '[\"a\",\"b\"]) to Set of columns.\n readonly #uniqueIndexes: Map<string, Set<string>>;\n readonly #primaryKey: PrimaryKey;\n readonly #logConfig: LogConfig;\n readonly #lc: LogContext;\n readonly #shouldYield: () => boolean;\n readonly #skipUnobservableChanges: boolean;\n readonly #primaryKeySort: Ordering;\n #stmts: Statements;\n #overlay?: Overlay | undefined;\n #pushEpoch = 0;\n /**\n * When present, derivation is read-only: changes accumulate here instead of\n * being written to (and later rolled back out of) the backing snapshot. See\n * {@link PendingDelta}.\n */\n #delta: PendingDelta | undefined;\n #rowsRead = 0;\n\n /**\n * @param shouldYield a function called after each row is read from the database,\n * which should return true if the source should yield the special 'yield' value\n * to yield control back to the caller at the end of the pipeline. Can\n * also throw an error to abort the pipeline processing.\n */\n constructor(\n logContext: LogContext,\n logConfig: LogConfig,\n db: Database,\n tableName: string,\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n shouldYield = () => false,\n options: TableSourceOptions = {},\n ) {\n this.#lc = logContext;\n this.#logConfig = logConfig;\n this.#table = tableName;\n this.#columns = columns;\n this.#uniqueIndexes = getUniqueIndexes(db, tableName);\n this.#primaryKey = primaryKey;\n this.#primaryKeySort = primaryKey.map(k => [k, 'asc']);\n this.#stmts = this.#getStatementsFor(db);\n this.#shouldYield = shouldYield;\n this.#skipUnobservableChanges = options.skipUnobservableChanges ?? false;\n this.#delta = options.deferWrites\n ? new PendingDelta(primaryKey)\n : undefined;\n\n const primaryKeyStr = JSON.stringify(primaryKey.toSorted());\n assert(\n this.#uniqueIndexes.has(primaryKeyStr),\n `primary key ${primaryKeyStr} does not have a UNIQUE index`,\n );\n }\n\n /**\n * The number of rows read from SQLite by fetches, over the lifetime of this\n * source. Rows that SQLite scans and filters out itself are not counted.\n */\n get rowsRead(): number {\n return this.#rowsRead;\n }\n\n get tableSchema() {\n return {\n name: this.#table,\n columns: this.#columns,\n primaryKey: this.#primaryKey,\n };\n }\n\n /**\n * Sets the db (snapshot) to use, to facilitate the Snapshotter leapfrog\n * algorithm for concurrent traversal of historic timelines.\n */\n setDB(db: Database) {\n this.#stmts = this.#getStatementsFor(db);\n // The new snapshot already contains everything the batch was standing in\n // for, so the batch is done.\n this.#delta?.clear();\n }\n\n /**\n * Sets whether the changes pushed from now on are held in memory (see\n * {@link TableSourceOptions.deferWrites}) or written to the backing\n * snapshot. The two must not be mixed within one snapshot, so this may only\n * be called before the first push after construction or {@link setDB}. To\n * switch to writing through partway, see {@link writePendingChanges}.\n */\n setDeferWrites(deferWrites: boolean) {\n assert(\n this.#delta === undefined || this.#delta.isEmpty,\n 'Cannot change how writes are applied while changes are pending',\n );\n if (!deferWrites) {\n this.#delta = undefined;\n } else {\n this.#delta ??= new PendingDelta(this.#primaryKey);\n }\n }\n\n /**\n * Drops the changes held in memory (see {@link setDeferWrites}), for an\n * advancement that has been abandoned. The source then no longer reflects\n * the changes pushed to it, so it must not be read again until it has moved\n * to another snapshot ({@link setDB}), if it is used again at all.\n */\n discardPendingChanges(): void {\n this.#delta?.clear();\n }\n\n /**\n * Writes the changes held in memory (see {@link setDeferWrites}) to the\n * backing snapshot, which is left as if they had been written through (in\n * the source's columns), and writes the changes pushed from then on through\n * to it. Yields when the\n * source's `shouldYield` says to, and must not be interleaved with a push.\n */\n *writePendingChanges(): Stream<'yield'> {\n const delta = this.#delta;\n if (delta === undefined) {\n return;\n }\n // The rows the delta holds satisfy the table's unique keys, but one may\n // take a unique value from another row that the delta also changed. So\n // every row it touched is deleted before any is inserted.\n for (const key of delta.touchedKeys()) {\n this.#stmts.delete.run(\n ...toSQLiteTypes(this.#primaryKey, key, this.#columns),\n );\n if (this.#shouldYield()) {\n yield 'yield';\n }\n }\n const columns = Object.keys(this.#columns);\n for (const row of delta.liveRows()) {\n this.#stmts.insert.run(...toSQLiteTypes(columns, row, this.#columns));\n if (this.#shouldYield()) {\n yield 'yield';\n }\n }\n this.#delta = undefined;\n }\n\n #getStatementsFor(db: Database) {\n const cached = this.#dbCache.get(db);\n if (cached) {\n return cached;\n }\n\n const stmts = {\n cache: new StatementCache(db),\n insert: db.prepare(\n compile(\n sql`INSERT INTO ${sql.ident(this.#table)} (${sql.join(\n Object.keys(this.#columns).map(c => sql.ident(c)),\n ', ',\n )}) VALUES (${sql.__dangerous__rawValue(\n Array.from({length: Object.keys(this.#columns).length})\n .fill('?')\n .join(','),\n )})`,\n ),\n ),\n delete: db.prepare(\n compile(\n sql`DELETE FROM ${sql.ident(this.#table)} WHERE ${sql.join(\n this.#primaryKey.map(k => sql`${sql.ident(k)}=?`),\n ' AND ',\n )}`,\n ),\n ),\n // If all the columns are part of the primary key, we cannot use UPDATE.\n update:\n Object.keys(this.#columns).length > this.#primaryKey.length\n ? db.prepare(\n compile(\n sql`UPDATE ${sql.ident(this.#table)} SET ${sql.join(\n nonPrimaryKeys(this.#columns, this.#primaryKey).map(\n c => sql`${sql.ident(c)}=?`,\n ),\n ',',\n )} WHERE ${sql.join(\n this.#primaryKey.map(k => sql`${sql.ident(k)}=?`),\n ' AND ',\n )}`,\n ),\n )\n : undefined,\n checkExists: db.prepare(\n compile(\n sql`SELECT 1 AS \"exists\" FROM ${sql.ident(\n this.#table,\n )} WHERE ${sql.join(\n this.#primaryKey.map(k => sql`${sql.ident(k)}=?`),\n ' AND ',\n )} LIMIT 1`,\n ),\n ),\n getExisting: db.prepare(\n compile(\n sql`SELECT * FROM ${sql.ident(this.#table)} WHERE ${sql.join(\n this.#primaryKey.map(k => sql`${sql.ident(k)}=?`),\n ' AND ',\n )}`,\n ),\n ),\n };\n this.#dbCache.set(db, stmts);\n return stmts;\n }\n\n get #allColumns() {\n return sql.join(\n Object.keys(this.#columns).map(c => sql.ident(c)),\n sql`,`,\n );\n }\n\n #getSchema(connection: Connection, unordered: boolean): SourceSchema {\n return {\n tableName: this.#table,\n columns: this.#columns,\n primaryKey: this.#primaryKey,\n sort: unordered ? undefined : connection.sort,\n relationships: {},\n isHidden: false,\n system: 'client',\n compareRows: connection.compareRows,\n };\n }\n\n hasConnections(): boolean {\n return this.#connections.length > 0;\n }\n\n connect(\n sort: Ordering | undefined,\n filters?: Condition,\n splitEditKeys?: Set<string>,\n debug?: DebugDelegate,\n ) {\n const transformedFilters = transformFilters(filters);\n const unordered = sort === undefined;\n // PK comparator is used for source-level overlay matching (remove by PK\n // equality) even when no ordering is requested.\n const primaryKeySort: Ordering = this.#primaryKeySort;\n\n const input: SourceInput = {\n getSchema: () => schema,\n fetch: req => this.#fetch(req, connection),\n setOutput: output => {\n connection.output = output;\n },\n destroy: () => {\n const idx = this.#connections.indexOf(connection);\n assert(idx !== -1, 'Connection not found');\n this.#connections.splice(idx, 1);\n this.#connectionIndex.remove(connection);\n },\n fullyAppliedFilters: !transformedFilters.conditionsRemoved,\n };\n\n const connection: Connection = {\n input,\n debug,\n output: undefined,\n sort,\n splitEditKeys,\n filters: transformedFilters.filters\n ? {\n condition: transformedFilters.filters,\n predicate: createPredicate(transformedFilters.filters),\n }\n : undefined,\n compareRows: sort ? makeComparator(sort) : makeComparator(primaryKeySort),\n lastPushedEpoch: 0,\n };\n const schema = this.#getSchema(connection, unordered);\n if (!unordered) {\n assertOrderingIncludesPK(sort, this.#primaryKey);\n }\n\n this.#connections.push(connection);\n this.#connectionIndex.add(connection, transformedFilters.filters);\n return input;\n }\n\n toSQLiteRow(row: Row): Row {\n return Object.fromEntries(\n Object.entries(row).map(([key, value]) => [\n key,\n toSQLiteType(value, this.#columns[key].type),\n ]),\n ) as Row;\n }\n\n *#fetch(req: FetchRequest, connection: Connection): Stream<Node | 'yield'> {\n const {sort, debug} = connection;\n\n const rows = this.#queryRows(\n this.#requestToSQL(req, connection.filters?.condition, sort),\n debug,\n );\n const overlayPredicate = mergeOverlayPredicate(\n connection.filters?.predicate,\n req.filter,\n );\n try {\n if (sort) {\n const comparator = makeComparator(sort, req.reverse);\n yield* generateWithStart(\n generateWithYields(\n generateWithOverlay(\n req.start?.row,\n this.#withPendingDelta(\n rows,\n req,\n overlayPredicate,\n sort,\n comparator,\n ),\n req.constraint,\n this.#overlay,\n connection.lastPushedEpoch,\n comparator,\n // SQL does the ordering and constraining, so the row stream is\n // already in the connection's sort order: the splice comparator\n // and the `startAt` comparator coincide here.\n comparator,\n overlayPredicate,\n req.multiConstraints,\n ),\n this.#shouldYield,\n ),\n req.start,\n comparator,\n );\n } else {\n yield* generateWithYields(\n generateWithOverlayUnordered(\n this.#withPendingDelta(\n rows,\n req,\n overlayPredicate,\n undefined,\n undefined,\n ),\n req.constraint,\n this.#overlay,\n connection.lastPushedEpoch,\n this.#primaryKey,\n overlayPredicate,\n req.multiConstraints,\n ),\n this.#shouldYield,\n );\n }\n } finally {\n // The generators above do not close `rows` when they are abandoned\n // partway, which leaves its statement open.\n rows.return();\n }\n }\n\n /**\n * The rows of `queries`, run one after another as {@link buildSelectQueries}\n * requires. Each statement is run only once the previous one is exhausted,\n * so a fetch that stops early never runs the rest.\n */\n *#queryRows(\n queries: readonly SQLQuery[],\n debug: DebugDelegate | undefined,\n ): Generator<Row, void, undefined> {\n const {cache} = this.#stmts;\n for (const query of queries) {\n const sqlAndBindings = format(query);\n const cachedStatement = cache.get(sqlAndBindings.text);\n cachedStatement.statement.safeIntegers(true);\n const rowIterator = cachedStatement.statement.iterate<Row>(\n ...sqlAndBindings.values,\n );\n try {\n debug?.initQuery(this.#table, sqlAndBindings.text);\n yield* this.#mapFromSQLiteTypes(\n this.#columns,\n rowIterator,\n sqlAndBindings.text,\n debug,\n );\n } finally {\n // Ensure the SQLite iterate() is closed.\n rowIterator.return?.();\n if (debug) {\n let totalNvisit = 0;\n const planLines: string[] = [];\n for (let i = 0; ; i++) {\n const nvisit = cachedStatement.statement.scanStatus(\n i,\n SQLite3Database.SQLITE_SCANSTAT_NVISIT,\n 1,\n );\n if (nvisit === undefined) {\n break;\n }\n totalNvisit += Number(nvisit);\n const explain = cachedStatement.statement.scanStatus(\n i,\n SQLite3Database.SQLITE_SCANSTAT_EXPLAIN,\n 1,\n );\n if (typeof explain === 'string' && explain.length > 0) {\n planLines.push(explain);\n }\n }\n if (totalNvisit !== 0) {\n debug.recordNVisit(this.#table, sqlAndBindings.text, totalNvisit);\n }\n if (planLines.length > 0) {\n debug.recordExplain(this.#table, sqlAndBindings.text, planLines);\n }\n cachedStatement.statement.scanStatusReset();\n }\n cache.return(cachedStatement);\n }\n }\n }\n\n /**\n * Splices the batch overlay into a base row stream, if there is one. When\n * derivation is not deferred, or the batch is empty -- every fetch during\n * hydration, and every fetch before the first change of a pass -- this is\n * the identity and the source behaves exactly as it did before.\n *\n * `predicate` is the connection's filters ANDed with `req.filter`, which\n * SQL applies to the base rows. `sort` and `compare` are absent for\n * unordered fetches, where nothing downstream depends on position.\n */\n #withPendingDelta(\n baseRows: IterableIterator<Row>,\n req: FetchRequest,\n predicate: ((row: Row) => boolean) | undefined,\n sort: Ordering | undefined,\n compare: Comparator | undefined,\n ): IterableIterator<Row> {\n const delta = this.#delta;\n if (delta === undefined || delta.isEmpty) {\n return baseRows;\n }\n const deltaRows = delta.rowsFor(\n sort ?? this.#primaryKeySort,\n req.constraint,\n sort ? req.reverse : false,\n predicate,\n req.multiConstraints,\n sort ? req.start?.row : undefined,\n );\n return compare\n ? generateWithPendingDelta(baseRows, deltaRows, delta, compare)\n : generateWithPendingDeltaUnordered(baseRows, deltaRows, delta);\n }\n\n *#mapFromSQLiteTypes(\n valueTypes: Record<string, SchemaValue>,\n rowIterator: IterableIterator<Row>,\n query: string,\n debug: DebugDelegate | undefined,\n ): IterableIterator<Row> {\n let result;\n do {\n result = timeSampled(\n this.#lc,\n ++eventCount,\n this.#logConfig.ivmSampling,\n () => rowIterator.next(),\n this.#logConfig.slowRowThreshold,\n () =>\n `table-source.next took too long for ${query}. Are you missing an index?`,\n );\n if (result.done) {\n break;\n }\n this.#rowsRead++;\n const row = fromSQLiteTypes(valueTypes, result.value, this.#table);\n debug?.rowVended(this.#table, query, row);\n yield row;\n } while (!result.done);\n }\n\n *push(change: SourceChange): Stream<'yield'> {\n for (const result of this.genPush(change)) {\n if (result === 'yield') {\n yield result;\n }\n }\n }\n\n /**\n * The number of rows held in memory for changes that have been pushed but\n * not written, i.e. with `deferWrites`, since the last {@link setDB}.\n */\n get pendingRows(): number {\n return this.#delta?.size ?? 0;\n }\n\n /** Estimated bytes retained by deferred changes and their indexes. */\n get pendingBytes(): number {\n return this.#delta?.estimatedBytes ?? 0;\n }\n\n *genPush(change: SourceChange): Stream<'yield' | undefined> {\n if (\n this.#skipUnobservableChanges &&\n !this.#connectionIndex.mayAcceptChange(change)\n ) {\n // No connection can observe this row, so only a REMOVE needs to be\n // applied to the snapshot.\n if (change[SourceChangeIndex.TYPE] === ChangeType.REMOVE) {\n this.#writeChange(change);\n }\n return;\n }\n\n const exists = (row: Row) => {\n const delta = this.#delta;\n if (delta !== undefined && !delta.isEmpty) {\n const overridden = delta.get(row);\n if (overridden !== NOT_OVERRIDDEN) {\n return overridden !== undefined;\n }\n }\n return (\n this.#stmts.checkExists.get<{exists: number} | undefined>(\n ...toSQLiteTypes(this.#primaryKey, row, this.#columns),\n )?.exists === 1\n );\n };\n const setOverlay = (o: Overlay | undefined) => (this.#overlay = o);\n const writeChange = (c: SourceChange) => this.#writeChange(c);\n\n yield* genPushAndWriteWithSplitEdit(\n this.#connections,\n change,\n exists,\n setOverlay,\n writeChange,\n () => ++this.#pushEpoch,\n );\n }\n\n #writeChange(change: SourceChange) {\n const delta = this.#delta;\n if (delta !== undefined) {\n this.#writeChangeToDelta(delta, change);\n return;\n }\n switch (change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n this.#stmts.insert.run(\n ...toSQLiteTypes(\n // TODO(arv): Compute this once!\n Object.keys(this.#columns),\n change[SourceChangeIndex.ROW],\n this.#columns,\n ),\n );\n break;\n case ChangeType.REMOVE:\n this.#stmts.delete.run(\n ...toSQLiteTypes(\n this.#primaryKey,\n change[SourceChangeIndex.ROW],\n this.#columns,\n ),\n );\n break;\n case ChangeType.EDIT: {\n // If the PK is the same, use UPDATE.\n if (\n canUseUpdate(\n change[SourceChangeIndex.OLD_ROW],\n change[SourceChangeIndex.ROW],\n this.#columns,\n this.#primaryKey,\n )\n ) {\n const mergedRow = {\n ...change[SourceChangeIndex.OLD_ROW],\n ...change[SourceChangeIndex.ROW],\n };\n const params = [\n ...nonPrimaryValues(this.#columns, this.#primaryKey, mergedRow),\n ...toSQLiteTypes(this.#primaryKey, mergedRow, this.#columns),\n ];\n must(this.#stmts.update).run(params);\n } else {\n this.#stmts.delete.run(\n ...toSQLiteTypes(\n this.#primaryKey,\n change[SourceChangeIndex.OLD_ROW],\n this.#columns,\n ),\n );\n this.#stmts.insert.run(\n ...toSQLiteTypes(\n Object.keys(this.#columns),\n change[SourceChangeIndex.ROW],\n this.#columns,\n ),\n );\n }\n\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n /**\n * Reconciles a set of rows that the caller found in the *backing snapshot*\n * with the changes this source has applied but not written.\n *\n * A view-syncer computes the rows a replicated change collides with -- by\n * change-log key for a delete, by every unique key for a set -- against the\n * snapshot it is reading. When derivation writes through, that snapshot has\n * already absorbed the earlier changes of the same advancement, so the\n * probe sees them. When derivation is deferred they live here instead, and\n * the probe has to be brought up to date or the source is pushed a change\n * that contradicts its own state (a delete of a row the batch already\n * removed, an edit whose old row is stale).\n *\n * Two ways the batch can disagree with the probe, both handled here: a\n * probed row may have been removed, or may have been edited (so the\n * caller's copy is stale, or it no longer collides at all).\n *\n * The batch cannot have edited a row the probe missed *into* collision. The\n * change log keeps one entry per row key, so every row the batch holds is\n * that row's value at the advancement's target version, as is `next`, and\n * two distinct rows of one version cannot share a non-null unique key.\n *\n * Returns `base` untouched when derivation is not deferred, which is what\n * makes this a no-op for the write-through path.\n */\n reconcilePendingConflicts(\n base: readonly Row[],\n next: Row | null,\n rowKey: Row,\n uniqueKeys: readonly (readonly string[])[],\n ): readonly Row[] {\n const delta = this.#delta;\n if (delta === undefined || delta.isEmpty) {\n return base;\n }\n\n // The change-log key uses SQLite values, while pending rows use ZQL\n // values. It is the upstream replica identity, which may include columns\n // the source does not sync. The batch cannot have changed those (nor can a\n // write-through `UPDATE`), so only the synced columns are compared.\n const deleteKey = next === null ? this.#syncedDeleteKey(rowKey) : undefined;\n const out: Row[] = [];\n for (const row of base) {\n const pending = delta.get(row);\n const current = pending === NOT_OVERRIDDEN ? row : pending;\n if (current === undefined) {\n continue; // the batch removed it\n }\n if (\n deleteKey !== undefined\n ? !deleteKey.every(([col, value]) =>\n sqliteValuesEqual(current[col], value, this.#columns[col].type),\n )\n : !collides(\n current,\n must(next),\n uniqueKeys,\n this.#primaryKey,\n this.#columns,\n )\n ) {\n continue; // the batch edited it out of collision\n }\n out.push(current);\n }\n return out;\n }\n\n #syncedDeleteKey(rowKey: Row): [string, Value][] {\n const synced: Writable<Row> = {};\n for (const [col, value] of Object.entries(rowKey)) {\n if (Object.hasOwn(this.#columns, col)) {\n synced[col] = value;\n }\n }\n return Object.entries(fromSQLiteTypes(this.#columns, synced, this.#table));\n }\n\n /**\n * The batch-overlay counterpart of {@link #writeChange}. It must reproduce\n * that method's semantics exactly, including its treatment of an edit that\n * cannot be expressed as an `UPDATE` -- a changed primary key, or a table\n * whose columns are all part of the key -- as a delete followed by an\n * insert.\n */\n #writeChangeToDelta(delta: PendingDelta, change: SourceChange) {\n switch (change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n delta.set(change[SourceChangeIndex.ROW]);\n break;\n case ChangeType.REMOVE:\n delta.delete(change[SourceChangeIndex.ROW]);\n break;\n case ChangeType.EDIT: {\n const oldRow = change[SourceChangeIndex.OLD_ROW];\n const row = change[SourceChangeIndex.ROW];\n if (canUseUpdate(oldRow, row, this.#columns, this.#primaryKey)) {\n // `UPDATE` sets only the non-primary columns, so the row keeps any\n // column the change did not mention.\n delta.set({...oldRow, ...row});\n } else {\n delta.delete(oldRow);\n delta.set(row);\n }\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n #getRowStmtCache = new Map<string, string>();\n\n #getRowStmt(keyCols: string[]): string {\n const keyString = JSON.stringify(keyCols);\n return getOrInsertComputed(this.#getRowStmtCache, keyString, () =>\n compile(\n sql`SELECT ${this.#allColumns} FROM ${sql.ident(\n this.#table,\n )} WHERE ${sql.join(\n keyCols.map(k => sql`${sql.ident(k)}=?`),\n sql` AND`,\n )}`,\n ),\n );\n }\n\n /**\n * Retrieves a row from the backing DB by a unique key, or `undefined` if such a\n * row does not exist. This is not used in the IVM pipeline but is useful\n * for retrieving data that is consistent with the state (and type\n * semantics) of the pipeline. Note that this key may not necessarily correspond\n * to the `primaryKey` with which this TableSource.\n */\n getRow(rowKey: Row): Row | undefined {\n const keyCols = Object.keys(rowKey);\n\n const stmt = this.#getRowStmt(keyCols);\n const raw = this.#stmts.cache.use(stmt, cached =>\n cached.statement\n .safeIntegers(true)\n .get<Row>(...toSQLiteTypes(keyCols, rowKey, this.#columns)),\n );\n const row = raw ? fromSQLiteTypes(this.#columns, raw, this.#table) : raw;\n\n const delta = this.#delta;\n if (delta === undefined || delta.isEmpty) {\n return row;\n }\n if (row !== undefined) {\n // The batch may have edited or removed the base row out from under this\n // lookup. Its own primary key is what identifies it in the batch.\n const overridden = delta.get(row);\n if (overridden === NOT_OVERRIDDEN) {\n return row;\n }\n if (\n overridden !== undefined &&\n keyCols.every(c => overridden[c] === rowKey[c])\n ) {\n return overridden;\n }\n }\n // The base match is absent, removed, or no longer matches this key. Another\n // pending row may now own the key.\n return delta.getByColumns(keyCols, rowKey);\n }\n\n #requestToSQL(\n request: FetchRequest,\n filters: NoSubqueryCondition | undefined,\n order: Ordering | undefined,\n ): readonly SQLQuery[] {\n return buildSelectQueries(\n this.#table,\n this.#columns,\n request.constraint,\n filters,\n order,\n request.reverse,\n request.start,\n request.multiConstraints,\n request.filter,\n );\n }\n}\n\nfunction mergeOverlayPredicate(\n connPredicate: ((row: Row) => boolean) | undefined,\n reqFilter: StrictNoSubqueryCondition | undefined,\n): ((row: Row) => boolean) | undefined {\n if (!reqFilter) {\n return connPredicate;\n }\n const reqPredicate = createPredicate(reqFilter);\n if (!connPredicate) {\n return reqPredicate;\n }\n return row => connPredicate(row) && reqPredicate(row);\n}\n\n/**\n * Whether `a` occupies the same row identity as `b` -- the same primary key,\n * or the same value on any unique key, which is what a replicated write\n * conflicts on.\n */\nfunction collides(\n a: Row,\n b: Row,\n uniqueKeys: readonly (readonly string[])[],\n primaryKey: PrimaryKey,\n columns: Record<string, SchemaValue>,\n): boolean {\n if (\n primaryKey.every(col =>\n sqliteValuesEqual(a[col], b[col], columns[col].type),\n )\n ) {\n return true;\n }\n for (const key of uniqueKeys) {\n if (key.some(col => b[col] === null || b[col] === undefined)) {\n continue;\n }\n if (\n key.every(col => sqliteValuesEqual(a[col], b[col], columns[col].type))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction sqliteValuesEqual(\n a: Value | undefined,\n b: Value | undefined,\n type: ValueType,\n) {\n return toSQLiteType(a, type) === toSQLiteType(b, type);\n}\n\nfunction getUniqueIndexes(\n db: Database,\n tableName: string,\n): Map<string, Set<string>> {\n const sqlAndBindings = format(\n sql`\n SELECT idx.name, json_group_array(col.name) as columnsJSON\n FROM sqlite_master as idx\n JOIN pragma_index_list(idx.tbl_name) AS info ON info.name = idx.name\n JOIN pragma_index_info(idx.name) as col\n WHERE idx.tbl_name = ${tableName} AND\n idx.type = 'index' AND \n info.\"unique\" != 0 AND\n info.partial = 0\n GROUP BY idx.name\n ORDER BY idx.name`,\n );\n const stmt = db.prepare(sqlAndBindings.text);\n const indexes = stmt.all<{columnsJSON: string}>(...sqlAndBindings.values);\n return new Map(\n indexes.map(({columnsJSON}) => {\n const columns = JSON.parse(columnsJSON);\n const set = new Set<string>(columns);\n return [JSON.stringify(columns.sort()), set];\n }),\n );\n}\n\nexport function toSQLiteTypes(\n columns: readonly string[],\n row: Row,\n columnTypes: Record<string, SchemaValue>,\n): readonly unknown[] {\n return columns.map(col => toSQLiteType(row[col], columnTypes[col].type));\n}\n\nexport function toSQLiteTypeName(type: ValueType) {\n switch (type) {\n case 'boolean':\n return 'INTEGER';\n case 'number':\n return 'REAL';\n case 'string':\n return 'TEXT';\n case 'null':\n return 'NULL';\n case 'json':\n return 'TEXT';\n }\n}\n\nexport function fromSQLiteTypes(\n valueTypes: Record<string, SchemaValue>,\n row: Row,\n tableName: string,\n): Row {\n const newRow: Writable<Row> = {};\n for (const key of Object.keys(row)) {\n const valueType = valueTypes[key];\n if (valueType === undefined) {\n const columnList = Object.keys(valueTypes).sort().join(', ');\n throw new Error(\n `Invalid column \"${key}\" for table \"${tableName}\". Synced columns include ${columnList}`,\n );\n }\n newRow[key] = fromSQLiteType(valueType.type, row[key], key, tableName);\n }\n return newRow;\n}\n\nfunction fromSQLiteType(\n valueType: ValueType,\n v: Value,\n column: string,\n tableName: string,\n): Value {\n if (v === null) {\n return null;\n }\n switch (valueType) {\n case 'boolean':\n return !!v;\n case 'number':\n case 'string':\n case 'null':\n if (typeof v === 'bigint') {\n const bi = v as bigint;\n if (bi > Number.MAX_SAFE_INTEGER || bi < Number.MIN_SAFE_INTEGER) {\n throw new UnsupportedValueError(\n `value ${bi} (in ${tableName}.${column}) is outside of supported bounds`,\n );\n }\n return Number(bi);\n }\n return v;\n case 'json':\n try {\n return JSON.parse(v as string);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new UnsupportedValueError(\n `Failed to parse JSON for ${tableName}.${column}: ${errorMessage}`,\n {cause: error},\n );\n }\n }\n}\n\nexport class UnsupportedValueError extends Error {}\n\nfunction canUseUpdate(\n oldRow: Row,\n row: Row,\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n): boolean {\n for (const pk of primaryKey) {\n if (oldRow[pk] !== row[pk]) {\n return false;\n }\n }\n return Object.keys(columns).length > primaryKey.length;\n}\n\nfunction nonPrimaryValues(\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n row: Row,\n): Iterable<unknown> {\n return nonPrimaryKeys(columns, primaryKey).map(c =>\n toSQLiteType(row[c], columns[c].type),\n );\n}\n\nfunction nonPrimaryKeys(\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n) {\n return Object.keys(columns).filter(c => !primaryKey.includes(c));\n}\n\nfunction* generateWithYields(stream: Stream<Node>, shouldYield: () => boolean) {\n for (const n of stream) {\n if (shouldYield()) {\n yield 'yield';\n }\n yield n;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuEA,IAAI,aAAa;;;;;;;;;;;;;;;AAqCjB,IAAa,cAAb,MAA2C;CACzC,2BAAoB,IAAI,QAA8B;CACtD,eAAsC,CAAC;CAGvC,mBAA4B,IAAI,gBAA4B;CAC5D;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,aAAa;;;;;;CAMb;CACA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ionIndex","#table","#columns","#uniqueIndexes","#primaryKey","#logConfig","#lc","#shouldYield","#skipUnobservableChanges","#primaryKeySort","#stmts","#getStatementsFor","#delta","#rowsRead","#allColumns","#fetch","#getSchema","#queryRows","#requestToSQL","#withPendingDelta","#overlay","#mapFromSQLiteTypes","#writeChange","#pushEpoch","#writeChangeToDelta","#syncedDeleteKey","#getRowStmtCache","#getRowStmt"],"sources":["../../../../zqlite/src/table-source.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport type {LogContext} from '@rocicorp/logger';\nimport SQLite3Database from '@rocicorp/zero-sqlite3';\nimport type {LogConfig} from '../../otel/src/log-options.ts';\nimport {timeSampled} from '../../otel/src/maybe-time.ts';\nimport {assert, unreachable} from '../../shared/src/asserts.ts';\nimport {getOrInsertComputed} from '../../shared/src/map.ts';\nimport {must} from '../../shared/src/must.ts';\nimport type {Writable} from '../../shared/src/writable.ts';\nimport type {Condition, Ordering} from '../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../zero-protocol/src/primary-key.ts';\nimport type {\n SchemaValue,\n ValueType,\n} from '../../zero-schema/src/table-schema.ts';\nimport type {DebugDelegate} from '../../zql/src/builder/debug-delegate.ts';\nimport {\n createPredicate,\n transformFilters,\n type NoSubqueryCondition as StrictNoSubqueryCondition,\n} from '../../zql/src/builder/filter.ts';\nimport {ChangeType} from '../../zql/src/ivm/change-type.ts';\nimport {ConnectionIndex} from '../../zql/src/ivm/connection-index.ts';\nimport {\n makeComparator,\n type Comparator,\n type Node,\n} from '../../zql/src/ivm/data.ts';\nimport {\n generateWithOverlay,\n generateWithOverlayUnordered,\n generateWithStart,\n genPushAndWriteWithSplitEdit,\n type Connection,\n type Overlay,\n} from '../../zql/src/ivm/memory-source.ts';\nimport {type FetchRequest} from '../../zql/src/ivm/operator.ts';\nimport type {SourceSchema} from '../../zql/src/ivm/schema.ts';\nimport {SourceChangeIndex} from '../../zql/src/ivm/source-change-index.ts';\nimport {\n type Source,\n type SourceChange,\n type SourceInput,\n} from '../../zql/src/ivm/source.ts';\nimport type {Stream} from '../../zql/src/ivm/stream.ts';\nimport {assertOrderingIncludesPK} from '../../zql/src/query/complete-ordering.ts';\nimport type {Database, Statement} from './db.ts';\nimport {compile, format, sql} from './internal/sql.ts';\nimport {StatementCache} from './internal/statement-cache.ts';\nimport {\n generateWithPendingDelta,\n generateWithPendingDeltaUnordered,\n NOT_OVERRIDDEN,\n PendingDelta,\n} from './pending-delta.ts';\nimport {\n buildSelectQueries,\n toSQLiteType,\n type NoSubqueryCondition,\n} from './query-builder.ts';\n\ntype Statements = {\n readonly cache: StatementCache;\n readonly insert: Statement;\n readonly delete: Statement;\n readonly update: Statement | undefined;\n readonly checkExists: Statement;\n readonly getExisting: Statement;\n};\n\nlet eventCount = 0;\n\nexport type TableSourceOptions = {\n /**\n * When set, a pushed change that the filters of every connection reject\n * is neither pushed nor applied to the backing table, on the grounds that\n * no connection can observe it. This departs from the `Source.push`\n * contract (a push commits the change to the source), so it is only\n * appropriate when the caller does not read the table through any other\n * path and replaces the table's contents afterwards, as the view-syncer's\n * pipeline driver does when it advances to the next snapshot.\n */\n skipUnobservableChanges?: boolean | undefined;\n\n /**\n * When set, pushed changes are held in an in-memory {@link PendingDelta}\n * merged into every read instead of being written to the backing table.\n * The delta is dropped when the source moves to the next snapshot. This is\n * the initial mode; see {@link TableSource.setDeferWrites}.\n */\n deferWrites?: boolean | undefined;\n};\n\n/**\n * A source that is backed by a SQLite table.\n *\n * Values are written to the backing table _after_ being vended by the source.\n *\n * This ordering of events is to ensure self joins function properly. That is,\n * we can't reveal a value to an output before it has been pushed to that output.\n *\n * The code is fairly straightforward except for:\n * 1. Dealing with a `fetch` that has a basis of `before`.\n * 2. Dealing with compound orders that have differing directions (a ASC, b DESC, c ASC)\n *\n * See comments in relevant functions for more details.\n */\nexport class TableSource implements Source {\n readonly #dbCache = new WeakMap<Database, Statements>();\n readonly #connections: Connection[] = [];\n // Indexes #connections by the static equality constraints in their filters\n // so that a push can cheaply skip rows that no connection could accept.\n readonly #connectionIndex = new ConnectionIndex<Connection>();\n readonly #table: string;\n readonly #columns: Record<string, SchemaValue>;\n // Maps sorted columns JSON string (e.g. '[\"a\",\"b\"]) to Set of columns.\n readonly #uniqueIndexes: Map<string, Set<string>>;\n readonly #primaryKey: PrimaryKey;\n readonly #logConfig: LogConfig;\n readonly #lc: LogContext;\n readonly #shouldYield: () => boolean;\n readonly #skipUnobservableChanges: boolean;\n readonly #primaryKeySort: Ordering;\n #stmts: Statements;\n #overlay?: Overlay | undefined;\n #pushEpoch = 0;\n /**\n * When present, derivation is read-only: changes accumulate here instead of\n * being written to (and later rolled back out of) the backing snapshot. See\n * {@link PendingDelta}.\n */\n #delta: PendingDelta | undefined;\n #rowsRead = 0;\n\n /**\n * @param shouldYield a function called after each row is read from the database,\n * which should return true if the source should yield the special 'yield' value\n * to yield control back to the caller at the end of the pipeline. Can\n * also throw an error to abort the pipeline processing.\n */\n constructor(\n logContext: LogContext,\n logConfig: LogConfig,\n db: Database,\n tableName: string,\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n shouldYield = () => false,\n options: TableSourceOptions = {},\n ) {\n this.#lc = logContext;\n this.#logConfig = logConfig;\n this.#table = tableName;\n this.#columns = columns;\n this.#uniqueIndexes = getUniqueIndexes(db, tableName);\n this.#primaryKey = primaryKey;\n this.#primaryKeySort = primaryKey.map(k => [k, 'asc']);\n this.#stmts = this.#getStatementsFor(db);\n this.#shouldYield = shouldYield;\n this.#skipUnobservableChanges = options.skipUnobservableChanges ?? false;\n this.#delta = options.deferWrites\n ? new PendingDelta(primaryKey)\n : undefined;\n\n const primaryKeyStr = JSON.stringify(primaryKey.toSorted());\n assert(\n this.#uniqueIndexes.has(primaryKeyStr),\n `primary key ${primaryKeyStr} does not have a UNIQUE index`,\n );\n }\n\n /**\n * The number of rows read from SQLite by fetches, over the lifetime of this\n * source. Rows that SQLite scans and filters out itself are not counted.\n */\n get rowsRead(): number {\n return this.#rowsRead;\n }\n\n get tableSchema() {\n return {\n name: this.#table,\n columns: this.#columns,\n primaryKey: this.#primaryKey,\n };\n }\n\n /**\n * Sets the db (snapshot) to use, to facilitate the Snapshotter leapfrog\n * algorithm for concurrent traversal of historic timelines.\n */\n setDB(db: Database) {\n this.#stmts = this.#getStatementsFor(db);\n // The new snapshot already contains everything the batch was standing in\n // for, so the batch is done.\n this.#delta?.clear();\n }\n\n /**\n * Sets whether the changes pushed from now on are held in memory (see\n * {@link TableSourceOptions.deferWrites}) or written to the backing\n * snapshot. The two must not be mixed within one snapshot, so this may only\n * be called before the first push after construction or {@link setDB}. To\n * switch to writing through partway, see {@link writePendingChanges}.\n */\n setDeferWrites(deferWrites: boolean) {\n assert(\n this.#delta === undefined || this.#delta.isEmpty,\n 'Cannot change how writes are applied while changes are pending',\n );\n if (!deferWrites) {\n this.#delta = undefined;\n } else {\n this.#delta ??= new PendingDelta(this.#primaryKey);\n }\n }\n\n /**\n * Drops the changes held in memory (see {@link setDeferWrites}), for an\n * advancement that has been abandoned. The source then no longer reflects\n * the changes pushed to it, so it must not be read again until it has moved\n * to another snapshot ({@link setDB}), if it is used again at all.\n */\n discardPendingChanges(): void {\n this.#delta?.clear();\n }\n\n /**\n * Writes the changes held in memory (see {@link setDeferWrites}) to the\n * backing snapshot, which is left as if they had been written through (in\n * the source's columns), and writes the changes pushed from then on through\n * to it. Yields when the\n * source's `shouldYield` says to, and must not be interleaved with a push.\n */\n *writePendingChanges(): Stream<'yield'> {\n const delta = this.#delta;\n if (delta === undefined) {\n return;\n }\n // The rows the delta holds satisfy the table's unique keys, but one may\n // take a unique value from another row that the delta also changed. So\n // every row it touched is deleted before any is inserted.\n for (const key of delta.touchedKeys()) {\n this.#stmts.delete.run(\n ...toSQLiteTypes(this.#primaryKey, key, this.#columns),\n );\n if (this.#shouldYield()) {\n yield 'yield';\n }\n }\n const columns = Object.keys(this.#columns);\n for (const row of delta.liveRows()) {\n this.#stmts.insert.run(...toSQLiteTypes(columns, row, this.#columns));\n if (this.#shouldYield()) {\n yield 'yield';\n }\n }\n this.#delta = undefined;\n }\n\n #getStatementsFor(db: Database) {\n const cached = this.#dbCache.get(db);\n if (cached) {\n return cached;\n }\n\n const stmts = {\n cache: new StatementCache(db),\n insert: db.prepare(\n compile(\n sql`INSERT INTO ${sql.ident(this.#table)} (${sql.join(\n Object.keys(this.#columns).map(c => sql.ident(c)),\n ', ',\n )}) VALUES (${sql.__dangerous__rawValue(\n Array.from({length: Object.keys(this.#columns).length})\n .fill('?')\n .join(','),\n )})`,\n ),\n ),\n delete: db.prepare(\n compile(\n sql`DELETE FROM ${sql.ident(this.#table)} WHERE ${sql.join(\n this.#primaryKey.map(k => sql`${sql.ident(k)}=?`),\n ' AND ',\n )}`,\n ),\n ),\n // If all the columns are part of the primary key, we cannot use UPDATE.\n update:\n Object.keys(this.#columns).length > this.#primaryKey.length\n ? db.prepare(\n compile(\n sql`UPDATE ${sql.ident(this.#table)} SET ${sql.join(\n nonPrimaryKeys(this.#columns, this.#primaryKey).map(\n c => sql`${sql.ident(c)}=?`,\n ),\n ',',\n )} WHERE ${sql.join(\n this.#primaryKey.map(k => sql`${sql.ident(k)}=?`),\n ' AND ',\n )}`,\n ),\n )\n : undefined,\n checkExists: db.prepare(\n compile(\n sql`SELECT 1 AS \"exists\" FROM ${sql.ident(\n this.#table,\n )} WHERE ${sql.join(\n this.#primaryKey.map(k => sql`${sql.ident(k)}=?`),\n ' AND ',\n )} LIMIT 1`,\n ),\n ),\n getExisting: db.prepare(\n compile(\n sql`SELECT * FROM ${sql.ident(this.#table)} WHERE ${sql.join(\n this.#primaryKey.map(k => sql`${sql.ident(k)}=?`),\n ' AND ',\n )}`,\n ),\n ),\n };\n this.#dbCache.set(db, stmts);\n return stmts;\n }\n\n get #allColumns() {\n return sql.join(\n Object.keys(this.#columns).map(c => sql.ident(c)),\n sql`,`,\n );\n }\n\n #getSchema(connection: Connection, unordered: boolean): SourceSchema {\n return {\n tableName: this.#table,\n columns: this.#columns,\n primaryKey: this.#primaryKey,\n sort: unordered ? undefined : connection.sort,\n relationships: {},\n isHidden: false,\n system: 'client',\n compareRows: connection.compareRows,\n };\n }\n\n connect(\n sort: Ordering | undefined,\n filters?: Condition,\n splitEditKeys?: Set<string>,\n debug?: DebugDelegate,\n ) {\n const transformedFilters = transformFilters(filters);\n const unordered = sort === undefined;\n // PK comparator is used for source-level overlay matching (remove by PK\n // equality) even when no ordering is requested.\n const primaryKeySort: Ordering = this.#primaryKeySort;\n\n const input: SourceInput = {\n getSchema: () => schema,\n fetch: req => this.#fetch(req, connection),\n setOutput: output => {\n connection.output = output;\n },\n destroy: () => {\n const idx = this.#connections.indexOf(connection);\n assert(idx !== -1, 'Connection not found');\n this.#connections.splice(idx, 1);\n this.#connectionIndex.remove(connection);\n },\n fullyAppliedFilters: !transformedFilters.conditionsRemoved,\n };\n\n const connection: Connection = {\n input,\n debug,\n output: undefined,\n sort,\n splitEditKeys,\n filters: transformedFilters.filters\n ? {\n condition: transformedFilters.filters,\n predicate: createPredicate(transformedFilters.filters),\n }\n : undefined,\n compareRows: sort ? makeComparator(sort) : makeComparator(primaryKeySort),\n lastPushedEpoch: 0,\n };\n const schema = this.#getSchema(connection, unordered);\n if (!unordered) {\n assertOrderingIncludesPK(sort, this.#primaryKey);\n }\n\n this.#connections.push(connection);\n this.#connectionIndex.add(connection, transformedFilters.filters);\n return input;\n }\n\n toSQLiteRow(row: Row): Row {\n return Object.fromEntries(\n Object.entries(row).map(([key, value]) => [\n key,\n toSQLiteType(value, this.#columns[key].type),\n ]),\n ) as Row;\n }\n\n *#fetch(req: FetchRequest, connection: Connection): Stream<Node | 'yield'> {\n const {sort, debug} = connection;\n\n const rows = this.#queryRows(\n this.#requestToSQL(req, connection.filters?.condition, sort),\n debug,\n );\n const overlayPredicate = mergeOverlayPredicate(\n connection.filters?.predicate,\n req.filter,\n );\n try {\n if (sort) {\n const comparator = makeComparator(sort, req.reverse);\n yield* generateWithStart(\n generateWithYields(\n generateWithOverlay(\n req.start?.row,\n this.#withPendingDelta(\n rows,\n req,\n overlayPredicate,\n sort,\n comparator,\n ),\n req.constraint,\n this.#overlay,\n connection.lastPushedEpoch,\n comparator,\n // SQL does the ordering and constraining, so the row stream is\n // already in the connection's sort order: the splice comparator\n // and the `startAt` comparator coincide here.\n comparator,\n overlayPredicate,\n req.multiConstraints,\n ),\n this.#shouldYield,\n ),\n req.start,\n comparator,\n );\n } else {\n yield* generateWithYields(\n generateWithOverlayUnordered(\n this.#withPendingDelta(\n rows,\n req,\n overlayPredicate,\n undefined,\n undefined,\n ),\n req.constraint,\n this.#overlay,\n connection.lastPushedEpoch,\n this.#primaryKey,\n overlayPredicate,\n req.multiConstraints,\n ),\n this.#shouldYield,\n );\n }\n } finally {\n // The generators above do not close `rows` when they are abandoned\n // partway, which leaves its statement open.\n rows.return();\n }\n }\n\n /**\n * The rows of `queries`, run one after another as {@link buildSelectQueries}\n * requires. Each statement is run only once the previous one is exhausted,\n * so a fetch that stops early never runs the rest.\n */\n *#queryRows(\n queries: readonly SQLQuery[],\n debug: DebugDelegate | undefined,\n ): Generator<Row, void, undefined> {\n const {cache} = this.#stmts;\n for (const query of queries) {\n const sqlAndBindings = format(query);\n const cachedStatement = cache.get(sqlAndBindings.text);\n cachedStatement.statement.safeIntegers(true);\n const rowIterator = cachedStatement.statement.iterate<Row>(\n ...sqlAndBindings.values,\n );\n try {\n debug?.initQuery(this.#table, sqlAndBindings.text);\n yield* this.#mapFromSQLiteTypes(\n this.#columns,\n rowIterator,\n sqlAndBindings.text,\n debug,\n );\n } finally {\n // Ensure the SQLite iterate() is closed.\n rowIterator.return?.();\n if (debug) {\n let totalNvisit = 0;\n const planLines: string[] = [];\n for (let i = 0; ; i++) {\n const nvisit = cachedStatement.statement.scanStatus(\n i,\n SQLite3Database.SQLITE_SCANSTAT_NVISIT,\n 1,\n );\n if (nvisit === undefined) {\n break;\n }\n totalNvisit += Number(nvisit);\n const explain = cachedStatement.statement.scanStatus(\n i,\n SQLite3Database.SQLITE_SCANSTAT_EXPLAIN,\n 1,\n );\n if (typeof explain === 'string' && explain.length > 0) {\n planLines.push(explain);\n }\n }\n if (totalNvisit !== 0) {\n debug.recordNVisit(this.#table, sqlAndBindings.text, totalNvisit);\n }\n if (planLines.length > 0) {\n debug.recordExplain(this.#table, sqlAndBindings.text, planLines);\n }\n cachedStatement.statement.scanStatusReset();\n }\n cache.return(cachedStatement);\n }\n }\n }\n\n /**\n * Splices the batch overlay into a base row stream, if there is one. When\n * derivation is not deferred, or the batch is empty -- every fetch during\n * hydration, and every fetch before the first change of a pass -- this is\n * the identity and the source behaves exactly as it did before.\n *\n * `predicate` is the connection's filters ANDed with `req.filter`, which\n * SQL applies to the base rows. `sort` and `compare` are absent for\n * unordered fetches, where nothing downstream depends on position.\n */\n #withPendingDelta(\n baseRows: IterableIterator<Row>,\n req: FetchRequest,\n predicate: ((row: Row) => boolean) | undefined,\n sort: Ordering | undefined,\n compare: Comparator | undefined,\n ): IterableIterator<Row> {\n const delta = this.#delta;\n if (delta === undefined || delta.isEmpty) {\n return baseRows;\n }\n const deltaRows = delta.rowsFor(\n sort ?? this.#primaryKeySort,\n req.constraint,\n sort ? req.reverse : false,\n predicate,\n req.multiConstraints,\n sort ? req.start?.row : undefined,\n );\n return compare\n ? generateWithPendingDelta(baseRows, deltaRows, delta, compare)\n : generateWithPendingDeltaUnordered(baseRows, deltaRows, delta);\n }\n\n *#mapFromSQLiteTypes(\n valueTypes: Record<string, SchemaValue>,\n rowIterator: IterableIterator<Row>,\n query: string,\n debug: DebugDelegate | undefined,\n ): IterableIterator<Row> {\n let result;\n do {\n result = timeSampled(\n this.#lc,\n ++eventCount,\n this.#logConfig.ivmSampling,\n () => rowIterator.next(),\n this.#logConfig.slowRowThreshold,\n () =>\n `table-source.next took too long for ${query}. Are you missing an index?`,\n );\n if (result.done) {\n break;\n }\n this.#rowsRead++;\n const row = fromSQLiteTypes(valueTypes, result.value, this.#table);\n debug?.rowVended(this.#table, query, row);\n yield row;\n } while (!result.done);\n }\n\n *push(change: SourceChange): Stream<'yield'> {\n for (const result of this.genPush(change)) {\n if (result === 'yield') {\n yield result;\n }\n }\n }\n\n /**\n * The number of rows held in memory for changes that have been pushed but\n * not written, i.e. with `deferWrites`, since the last {@link setDB}.\n */\n get pendingRows(): number {\n return this.#delta?.size ?? 0;\n }\n\n /** Estimated bytes retained by deferred changes and their indexes. */\n get pendingBytes(): number {\n return this.#delta?.estimatedBytes ?? 0;\n }\n\n *genPush(change: SourceChange): Stream<'yield' | undefined> {\n if (\n this.#skipUnobservableChanges &&\n !this.#connectionIndex.mayAcceptChange(change)\n ) {\n // No connection can observe this row, so only a REMOVE needs to be\n // applied to the snapshot.\n if (change[SourceChangeIndex.TYPE] === ChangeType.REMOVE) {\n this.#writeChange(change);\n }\n return;\n }\n\n const exists = (row: Row) => {\n const delta = this.#delta;\n if (delta !== undefined && !delta.isEmpty) {\n const overridden = delta.get(row);\n if (overridden !== NOT_OVERRIDDEN) {\n return overridden !== undefined;\n }\n }\n return (\n this.#stmts.checkExists.get<{exists: number} | undefined>(\n ...toSQLiteTypes(this.#primaryKey, row, this.#columns),\n )?.exists === 1\n );\n };\n const setOverlay = (o: Overlay | undefined) => (this.#overlay = o);\n const writeChange = (c: SourceChange) => this.#writeChange(c);\n\n yield* genPushAndWriteWithSplitEdit(\n this.#connections,\n change,\n exists,\n setOverlay,\n writeChange,\n () => ++this.#pushEpoch,\n );\n }\n\n #writeChange(change: SourceChange) {\n const delta = this.#delta;\n if (delta !== undefined) {\n this.#writeChangeToDelta(delta, change);\n return;\n }\n switch (change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n this.#stmts.insert.run(\n ...toSQLiteTypes(\n // TODO(arv): Compute this once!\n Object.keys(this.#columns),\n change[SourceChangeIndex.ROW],\n this.#columns,\n ),\n );\n break;\n case ChangeType.REMOVE:\n this.#stmts.delete.run(\n ...toSQLiteTypes(\n this.#primaryKey,\n change[SourceChangeIndex.ROW],\n this.#columns,\n ),\n );\n break;\n case ChangeType.EDIT: {\n // If the PK is the same, use UPDATE.\n if (\n canUseUpdate(\n change[SourceChangeIndex.OLD_ROW],\n change[SourceChangeIndex.ROW],\n this.#columns,\n this.#primaryKey,\n )\n ) {\n const mergedRow = {\n ...change[SourceChangeIndex.OLD_ROW],\n ...change[SourceChangeIndex.ROW],\n };\n const params = [\n ...nonPrimaryValues(this.#columns, this.#primaryKey, mergedRow),\n ...toSQLiteTypes(this.#primaryKey, mergedRow, this.#columns),\n ];\n must(this.#stmts.update).run(params);\n } else {\n this.#stmts.delete.run(\n ...toSQLiteTypes(\n this.#primaryKey,\n change[SourceChangeIndex.OLD_ROW],\n this.#columns,\n ),\n );\n this.#stmts.insert.run(\n ...toSQLiteTypes(\n Object.keys(this.#columns),\n change[SourceChangeIndex.ROW],\n this.#columns,\n ),\n );\n }\n\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n /**\n * Reconciles a set of rows that the caller found in the *backing snapshot*\n * with the changes this source has applied but not written.\n *\n * A view-syncer computes the rows a replicated change collides with -- by\n * change-log key for a delete, by every unique key for a set -- against the\n * snapshot it is reading. When derivation writes through, that snapshot has\n * already absorbed the earlier changes of the same advancement, so the\n * probe sees them. When derivation is deferred they live here instead, and\n * the probe has to be brought up to date or the source is pushed a change\n * that contradicts its own state (a delete of a row the batch already\n * removed, an edit whose old row is stale).\n *\n * Two ways the batch can disagree with the probe, both handled here: a\n * probed row may have been removed, or may have been edited (so the\n * caller's copy is stale, or it no longer collides at all).\n *\n * The batch cannot have edited a row the probe missed *into* collision. The\n * change log keeps one entry per row key, so every row the batch holds is\n * that row's value at the advancement's target version, as is `next`, and\n * two distinct rows of one version cannot share a non-null unique key.\n *\n * Returns `base` untouched when derivation is not deferred, which is what\n * makes this a no-op for the write-through path.\n */\n reconcilePendingConflicts(\n base: readonly Row[],\n next: Row | null,\n rowKey: Row,\n uniqueKeys: readonly (readonly string[])[],\n ): readonly Row[] {\n const delta = this.#delta;\n if (delta === undefined || delta.isEmpty) {\n return base;\n }\n\n // The change-log key uses SQLite values, while pending rows use ZQL\n // values. It is the upstream replica identity, which may include columns\n // the source does not sync. The batch cannot have changed those (nor can a\n // write-through `UPDATE`), so only the synced columns are compared.\n const deleteKey = next === null ? this.#syncedDeleteKey(rowKey) : undefined;\n const out: Row[] = [];\n for (const row of base) {\n const pending = delta.get(row);\n const current = pending === NOT_OVERRIDDEN ? row : pending;\n if (current === undefined) {\n continue; // the batch removed it\n }\n if (\n deleteKey !== undefined\n ? !deleteKey.every(([col, value]) =>\n sqliteValuesEqual(current[col], value, this.#columns[col].type),\n )\n : !collides(\n current,\n must(next),\n uniqueKeys,\n this.#primaryKey,\n this.#columns,\n )\n ) {\n continue; // the batch edited it out of collision\n }\n out.push(current);\n }\n return out;\n }\n\n #syncedDeleteKey(rowKey: Row): [string, Value][] {\n const synced: Writable<Row> = {};\n for (const [col, value] of Object.entries(rowKey)) {\n if (Object.hasOwn(this.#columns, col)) {\n synced[col] = value;\n }\n }\n return Object.entries(fromSQLiteTypes(this.#columns, synced, this.#table));\n }\n\n /**\n * The batch-overlay counterpart of {@link #writeChange}. It must reproduce\n * that method's semantics exactly, including its treatment of an edit that\n * cannot be expressed as an `UPDATE` -- a changed primary key, or a table\n * whose columns are all part of the key -- as a delete followed by an\n * insert.\n */\n #writeChangeToDelta(delta: PendingDelta, change: SourceChange) {\n switch (change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n delta.set(change[SourceChangeIndex.ROW]);\n break;\n case ChangeType.REMOVE:\n delta.delete(change[SourceChangeIndex.ROW]);\n break;\n case ChangeType.EDIT: {\n const oldRow = change[SourceChangeIndex.OLD_ROW];\n const row = change[SourceChangeIndex.ROW];\n if (canUseUpdate(oldRow, row, this.#columns, this.#primaryKey)) {\n // `UPDATE` sets only the non-primary columns, so the row keeps any\n // column the change did not mention.\n delta.set({...oldRow, ...row});\n } else {\n delta.delete(oldRow);\n delta.set(row);\n }\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n #getRowStmtCache = new Map<string, string>();\n\n #getRowStmt(keyCols: string[]): string {\n const keyString = JSON.stringify(keyCols);\n return getOrInsertComputed(this.#getRowStmtCache, keyString, () =>\n compile(\n sql`SELECT ${this.#allColumns} FROM ${sql.ident(\n this.#table,\n )} WHERE ${sql.join(\n keyCols.map(k => sql`${sql.ident(k)}=?`),\n sql` AND`,\n )}`,\n ),\n );\n }\n\n /**\n * Retrieves a row from the backing DB by a unique key, or `undefined` if such a\n * row does not exist. This is not used in the IVM pipeline but is useful\n * for retrieving data that is consistent with the state (and type\n * semantics) of the pipeline. Note that this key may not necessarily correspond\n * to the `primaryKey` with which this TableSource.\n */\n getRow(rowKey: Row): Row | undefined {\n const keyCols = Object.keys(rowKey);\n\n const stmt = this.#getRowStmt(keyCols);\n const raw = this.#stmts.cache.use(stmt, cached =>\n cached.statement\n .safeIntegers(true)\n .get<Row>(...toSQLiteTypes(keyCols, rowKey, this.#columns)),\n );\n const row = raw ? fromSQLiteTypes(this.#columns, raw, this.#table) : raw;\n\n const delta = this.#delta;\n if (delta === undefined || delta.isEmpty) {\n return row;\n }\n if (row !== undefined) {\n // The batch may have edited or removed the base row out from under this\n // lookup. Its own primary key is what identifies it in the batch.\n const overridden = delta.get(row);\n if (overridden === NOT_OVERRIDDEN) {\n return row;\n }\n if (\n overridden !== undefined &&\n keyCols.every(c => overridden[c] === rowKey[c])\n ) {\n return overridden;\n }\n }\n // The base match is absent, removed, or no longer matches this key. Another\n // pending row may now own the key.\n return delta.getByColumns(keyCols, rowKey);\n }\n\n #requestToSQL(\n request: FetchRequest,\n filters: NoSubqueryCondition | undefined,\n order: Ordering | undefined,\n ): readonly SQLQuery[] {\n return buildSelectQueries(\n this.#table,\n this.#columns,\n request.constraint,\n filters,\n order,\n request.reverse,\n request.start,\n request.multiConstraints,\n request.filter,\n );\n }\n}\n\nfunction mergeOverlayPredicate(\n connPredicate: ((row: Row) => boolean) | undefined,\n reqFilter: StrictNoSubqueryCondition | undefined,\n): ((row: Row) => boolean) | undefined {\n if (!reqFilter) {\n return connPredicate;\n }\n const reqPredicate = createPredicate(reqFilter);\n if (!connPredicate) {\n return reqPredicate;\n }\n return row => connPredicate(row) && reqPredicate(row);\n}\n\n/**\n * Whether `a` occupies the same row identity as `b` -- the same primary key,\n * or the same value on any unique key, which is what a replicated write\n * conflicts on.\n */\nfunction collides(\n a: Row,\n b: Row,\n uniqueKeys: readonly (readonly string[])[],\n primaryKey: PrimaryKey,\n columns: Record<string, SchemaValue>,\n): boolean {\n if (\n primaryKey.every(col =>\n sqliteValuesEqual(a[col], b[col], columns[col].type),\n )\n ) {\n return true;\n }\n for (const key of uniqueKeys) {\n if (key.some(col => b[col] === null || b[col] === undefined)) {\n continue;\n }\n if (\n key.every(col => sqliteValuesEqual(a[col], b[col], columns[col].type))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction sqliteValuesEqual(\n a: Value | undefined,\n b: Value | undefined,\n type: ValueType,\n) {\n return toSQLiteType(a, type) === toSQLiteType(b, type);\n}\n\nfunction getUniqueIndexes(\n db: Database,\n tableName: string,\n): Map<string, Set<string>> {\n const sqlAndBindings = format(\n sql`\n SELECT idx.name, json_group_array(col.name) as columnsJSON\n FROM sqlite_master as idx\n JOIN pragma_index_list(idx.tbl_name) AS info ON info.name = idx.name\n JOIN pragma_index_info(idx.name) as col\n WHERE idx.tbl_name = ${tableName} AND\n idx.type = 'index' AND \n info.\"unique\" != 0 AND\n info.partial = 0\n GROUP BY idx.name\n ORDER BY idx.name`,\n );\n const stmt = db.prepare(sqlAndBindings.text);\n const indexes = stmt.all<{columnsJSON: string}>(...sqlAndBindings.values);\n return new Map(\n indexes.map(({columnsJSON}) => {\n const columns = JSON.parse(columnsJSON);\n const set = new Set<string>(columns);\n return [JSON.stringify(columns.sort()), set];\n }),\n );\n}\n\nexport function toSQLiteTypes(\n columns: readonly string[],\n row: Row,\n columnTypes: Record<string, SchemaValue>,\n): readonly unknown[] {\n return columns.map(col => toSQLiteType(row[col], columnTypes[col].type));\n}\n\nexport function toSQLiteTypeName(type: ValueType) {\n switch (type) {\n case 'boolean':\n return 'INTEGER';\n case 'number':\n return 'REAL';\n case 'string':\n return 'TEXT';\n case 'null':\n return 'NULL';\n case 'json':\n return 'TEXT';\n }\n}\n\nexport function fromSQLiteTypes(\n valueTypes: Record<string, SchemaValue>,\n row: Row,\n tableName: string,\n): Row {\n const newRow: Writable<Row> = {};\n for (const key of Object.keys(row)) {\n const valueType = valueTypes[key];\n if (valueType === undefined) {\n const columnList = Object.keys(valueTypes).sort().join(', ');\n throw new Error(\n `Invalid column \"${key}\" for table \"${tableName}\". Synced columns include ${columnList}`,\n );\n }\n newRow[key] = fromSQLiteType(valueType.type, row[key], key, tableName);\n }\n return newRow;\n}\n\nfunction fromSQLiteType(\n valueType: ValueType,\n v: Value,\n column: string,\n tableName: string,\n): Value {\n if (v === null) {\n return null;\n }\n switch (valueType) {\n case 'boolean':\n return !!v;\n case 'number':\n case 'string':\n case 'null':\n if (typeof v === 'bigint') {\n const bi = v as bigint;\n if (bi > Number.MAX_SAFE_INTEGER || bi < Number.MIN_SAFE_INTEGER) {\n throw new UnsupportedValueError(\n `value ${bi} (in ${tableName}.${column}) is outside of supported bounds`,\n );\n }\n return Number(bi);\n }\n return v;\n case 'json':\n try {\n return JSON.parse(v as string);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new UnsupportedValueError(\n `Failed to parse JSON for ${tableName}.${column}: ${errorMessage}`,\n {cause: error},\n );\n }\n }\n}\n\nexport class UnsupportedValueError extends Error {}\n\nfunction canUseUpdate(\n oldRow: Row,\n row: Row,\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n): boolean {\n for (const pk of primaryKey) {\n if (oldRow[pk] !== row[pk]) {\n return false;\n }\n }\n return Object.keys(columns).length > primaryKey.length;\n}\n\nfunction nonPrimaryValues(\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n row: Row,\n): Iterable<unknown> {\n return nonPrimaryKeys(columns, primaryKey).map(c =>\n toSQLiteType(row[c], columns[c].type),\n );\n}\n\nfunction nonPrimaryKeys(\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n) {\n return Object.keys(columns).filter(c => !primaryKey.includes(c));\n}\n\nfunction* generateWithYields(stream: Stream<Node>, shouldYield: () => boolean) {\n for (const n of stream) {\n if (shouldYield()) {\n yield 'yield';\n }\n yield n;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuEA,IAAI,aAAa;;;;;;;;;;;;;;;AAqCjB,IAAa,cAAb,MAA2C;CACzC,2BAAoB,IAAI,QAA8B;CACtD,eAAsC,CAAC;CAGvC,mBAA4B,IAAI,gBAA4B;CAC5D;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,aAAa;;;;;;CAMb;CACA,YAAY;;;;;;;CAQZ,YACE,YACA,WACA,IACA,WACA,SACA,YACA,oBAAoB,OACpB,UAA8B,CAAC,GAC/B;EACA,KAAKQ,MAAM;EACX,KAAKD,aAAa;EAClB,KAAKJ,SAAS;EACd,KAAKC,WAAW;EAChB,KAAKC,iBAAiB,iBAAiB,IAAI,SAAS;EACpD,KAAKC,cAAc;EACnB,KAAKK,kBAAkB,WAAW,KAAI,MAAK,CAAC,GAAG,KAAK,CAAC;EACrD,KAAKC,SAAS,KAAKC,kBAAkB,EAAE;EACvC,KAAKJ,eAAe;EACpB,KAAKC,2BAA2B,QAAQ,2BAA2B;EACnE,KAAKI,SAAS,QAAQ,cAClB,IAAI,aAAa,UAAU,IAC3B,KAAA;EAEJ,MAAM,gBAAgB,KAAK,UAAU,WAAW,SAAS,CAAC;EAC1D,OACE,KAAKT,eAAe,IAAI,aAAa,GACrC,eAAe,cAAc,8BAC/B;CACF;;;;;CAMA,IAAI,WAAmB;EACrB,OAAO,KAAKU;CACd;CAEA,IAAI,cAAc;EAChB,OAAO;GACL,MAAM,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