@rocicorp/zero 1.8.0 → 1.9.0-canary.0
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/shared/src/cache.d.ts +8 -1
- package/out/shared/src/cache.d.ts.map +1 -1
- package/out/shared/src/cache.js +25 -9
- package/out/shared/src/cache.js.map +1 -1
- package/out/shared/src/objects.d.ts +6 -1
- package/out/shared/src/objects.d.ts.map +1 -1
- package/out/shared/src/objects.js +19 -4
- package/out/shared/src/objects.js.map +1 -1
- package/out/zero/package.js +2 -19
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +4 -0
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +21 -6
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom-queries/transform-query.d.ts +6 -0
- package/out/zero-cache/src/custom-queries/transform-query.d.ts.map +1 -1
- package/out/zero-cache/src/custom-queries/transform-query.js +8 -0
- package/out/zero-cache/src/custom-queries/transform-query.js.map +1 -1
- package/out/zero-cache/src/db/migration-lite.d.ts.map +1 -1
- package/out/zero-cache/src/db/migration-lite.js +5 -2
- package/out/zero-cache/src/db/migration-lite.js.map +1 -1
- package/out/zero-cache/src/db/migration.d.ts.map +1 -1
- package/out/zero-cache/src/db/migration.js +3 -1
- package/out/zero-cache/src/db/migration.js.map +1 -1
- package/out/zero-cache/src/db/sqlite-corruption.d.ts +11 -0
- package/out/zero-cache/src/db/sqlite-corruption.d.ts.map +1 -0
- package/out/zero-cache/src/db/sqlite-corruption.js +191 -0
- package/out/zero-cache/src/db/sqlite-corruption.js.map +1 -0
- package/out/zero-cache/src/server/anonymous-otel-start.d.ts +1 -1
- package/out/zero-cache/src/server/anonymous-otel-start.js.map +1 -1
- package/out/zero-cache/src/server/backup-watermark-reader.js +1 -1
- package/out/zero-cache/src/server/backup-watermark-reader.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +7 -2
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/logging.d.ts +8 -0
- package/out/zero-cache/src/server/logging.d.ts.map +1 -1
- package/out/zero-cache/src/server/logging.js +27 -5
- package/out/zero-cache/src/server/logging.js.map +1 -1
- package/out/zero-cache/src/server/main.d.ts.map +1 -1
- package/out/zero-cache/src/server/main.js +6 -1
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/mutator.js +1 -1
- package/out/zero-cache/src/server/mutator.js.map +1 -1
- package/out/zero-cache/src/server/otel-log-sink.d.ts +7 -1
- package/out/zero-cache/src/server/otel-log-sink.d.ts.map +1 -1
- package/out/zero-cache/src/server/otel-log-sink.js +7 -2
- package/out/zero-cache/src/server/otel-log-sink.js.map +1 -1
- package/out/zero-cache/src/server/reaper.js +1 -1
- package/out/zero-cache/src/server/reaper.js.map +1 -1
- package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/server/replicator.js +11 -1
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/server/shadow-syncer.js +1 -1
- package/out/zero-cache/src/server/shadow-syncer.js.map +1 -1
- package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/server/syncer.js +6 -1
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-schema.js +8 -5
- package/out/zero-cache/src/services/change-source/common/replica-schema.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +36 -2
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +76 -33
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +15 -0
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +41 -10
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts +21 -0
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +34 -5
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +2 -2
- package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +61 -87
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +17 -12
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
- package/out/zero-cache/src/services/life-cycle.d.ts +1 -1
- package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
- package/out/zero-cache/src/services/life-cycle.js +15 -3
- package/out/zero-cache/src/services/life-cycle.js.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.js +20 -3
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.js +2 -2
- package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +4 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +28 -15
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/recorder.d.ts +1 -1
- package/out/zero-cache/src/services/replicator/reporter/recorder.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/recorder.js +5 -12
- package/out/zero-cache/src/services/replicator/reporter/recorder.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker.js +38 -7
- package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.js +8 -1
- package/out/zero-cache/src/services/view-syncer/cvr.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 +66 -26
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/query-covering.d.ts +28 -0
- package/out/zero-cache/src/services/view-syncer/query-covering.d.ts.map +1 -0
- package/out/zero-cache/src/services/view-syncer/query-covering.js +159 -0
- package/out/zero-cache/src/services/view-syncer/query-covering.js.map +1 -0
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +2 -0
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +71 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/lite.d.ts.map +1 -1
- package/out/zero-cache/src/types/lite.js +4 -1
- package/out/zero-cache/src/types/lite.js.map +1 -1
- package/out/zero-cache/src/types/pg.d.ts +18 -0
- package/out/zero-cache/src/types/pg.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg.js +50 -0
- package/out/zero-cache/src/types/pg.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +1 -0
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/crud.d.ts.map +1 -1
- package/out/zero-client/src/client/crud.js +3 -4
- package/out/zero-client/src/client/crud.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-schema/src/builder/relationship-builder.d.ts.map +1 -1
- package/out/zero-schema/src/builder/relationship-builder.js +3 -2
- package/out/zero-schema/src/builder/relationship-builder.js.map +1 -1
- package/out/zero-schema/src/builder/schema-builder.d.ts.map +1 -1
- package/out/zero-schema/src/builder/schema-builder.js +7 -7
- package/out/zero-schema/src/builder/schema-builder.js.map +1 -1
- package/out/zero-schema/src/builder/table-builder.d.ts.map +1 -1
- package/out/zero-schema/src/builder/table-builder.js +2 -1
- package/out/zero-schema/src/builder/table-builder.js.map +1 -1
- package/out/zero-server/src/custom.js +2 -1
- package/out/zero-server/src/custom.js.map +1 -1
- package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
- package/out/zql/src/ivm/view-apply-change.js +2 -1
- package/out/zql/src/ivm/view-apply-change.js.map +1 -1
- package/out/zql/src/mutate/crud.d.ts +10 -8
- package/out/zql/src/mutate/crud.d.ts.map +1 -1
- package/out/zql/src/mutate/crud.js +3 -4
- package/out/zql/src/mutate/crud.js.map +1 -1
- package/out/zqlite/src/db.js +2 -2
- package/out/zqlite/src/internal/statement-cache.d.ts +25 -1
- package/out/zqlite/src/internal/statement-cache.d.ts.map +1 -1
- package/out/zqlite/src/internal/statement-cache.js +48 -18
- package/out/zqlite/src/internal/statement-cache.js.map +1 -1
- package/out/zqlite/src/query-builder.js +3 -3
- package/out/zqlite/src/query-builder.js.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.js +5 -5
- package/out/zqlite/src/table-source.js +3 -3
- package/package.json +2 -33
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relationship-builder.d.ts","sourceRoot":"","sources":["../../../../../zero-schema/src/builder/relationship-builder.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"relationship-builder.d.ts","sourceRoot":"","sources":["../../../../../zero-schema/src/builder/relationship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AM,CAAC,EAAE,EACpD,aAAa,CACd;QACD,aAAa,CACX,SAAS,CAAC,MAAM,aAAa,CAAC,SAAS,CAAC,GAAG,MAAM,CAAC,EAAE,EACpD,SAAS,CAAC,MAAM,KAAK,CAAC,SAAS,CAAC,GAAG,MAAM,CAAC,EAAE,EAC5C,KAAK,CACN;KACF,CAAC;CACH,CAAC;AAEF,wBAAgB,aAAa,CAC3B,OAAO,SAAS,WAAW,EAC3B,cAAc,SAAS,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,EAEnD,KAAK,EAAE,uBAAuB,CAAC,OAAO,CAAC,EACvC,EAAE,EAAE,CAAC,QAAQ,EAAE;IACb,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7B,GAAG,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;CAC5B,KAAK,cAAc,GACnB;IAAC,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAAC,aAAa,EAAE,cAAc,CAAA;CAAC,CAUxD"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { mapValues } from "../../../shared/src/objects.js";
|
|
1
2
|
//#region ../zero-schema/src/builder/relationship-builder.ts
|
|
2
3
|
function relationships(table, cb) {
|
|
3
|
-
const relationships = cb({
|
|
4
|
+
const relationships = mapValues(cb({
|
|
4
5
|
many,
|
|
5
6
|
one
|
|
6
|
-
});
|
|
7
|
+
}), (relationship) => relationship);
|
|
7
8
|
return {
|
|
8
9
|
name: table.schema.name,
|
|
9
10
|
relationships
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relationship-builder.js","names":[],"sources":["../../../../../zero-schema/src/builder/relationship-builder.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport type {Relationship, TableSchema} from '../table-schema.ts';\nimport type {TableBuilderWithColumns} from './table-builder.ts';\n\ntype ConnectArg<TSourceField, TDestField, TDest extends TableSchema> = {\n readonly sourceField: TSourceField;\n readonly destField: TDestField;\n readonly destSchema: TableBuilderWithColumns<TDest>;\n};\n\ntype ManyConnection<TSourceField, TDestField, TDest extends TableSchema> = {\n readonly sourceField: TSourceField;\n readonly destField: TDestField;\n readonly destSchema: TDest['name'];\n readonly cardinality: 'many';\n};\n\ntype OneConnection<TSourceField, TDestField, TDest extends TableSchema> = {\n readonly sourceField: TSourceField;\n readonly destField: TDestField;\n readonly destSchema: TDest['name'];\n readonly cardinality: 'one';\n};\n\ntype Prev = [-1, 0, 1, 2, 3, 4, 5, 6];\n\nexport type PreviousSchema<\n TSource extends TableSchema,\n K extends number,\n TDests extends TableSchema[],\n> = K extends 0 ? TSource : TDests[Prev[K]];\n\nexport type Relationships = {\n name: string; // table name\n relationships: Record<string, Relationship>; // relationships for that table\n};\n\n// Overloaded types for better inference\ntype ManyConnector<TSource extends TableSchema> = {\n // Single direct relationship\n <TDest extends TableSchema>(\n arg: ConnectArg<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ): [\n ManyConnection<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ];\n\n // Junction relationship (two hops)\n <TJunction extends TableSchema, TDest extends TableSchema>(\n firstHop: ConnectArg<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TJunction['columns'] & string)[],\n TJunction\n >,\n secondHop: ConnectArg<\n readonly (keyof TJunction['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ): [\n ManyConnection<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TJunction['columns'] & string)[],\n TJunction\n >,\n ManyConnection<\n readonly (keyof TJunction['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ];\n};\n\ntype OneConnector<TSource extends TableSchema> = {\n // Single direct relationship\n <TDest extends TableSchema>(\n arg: ConnectArg<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ): [\n OneConnection<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ];\n\n // Two-hop relationship (e.g., invoice_line -> invoice -> customer)\n <TIntermediate extends TableSchema, TDest extends TableSchema>(\n firstHop: ConnectArg<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TIntermediate['columns'] & string)[],\n TIntermediate\n >,\n secondHop: ConnectArg<\n readonly (keyof TIntermediate['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ): [\n OneConnection<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TIntermediate['columns'] & string)[],\n TIntermediate\n >,\n OneConnection<\n readonly (keyof TIntermediate['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ];\n};\n\nexport function relationships<\n TSource extends TableSchema,\n TRelationships extends Record<string, Relationship>,\n>(\n table: TableBuilderWithColumns<TSource>,\n cb: (connects: {\n many: ManyConnector<TSource>;\n one: OneConnector<TSource>;\n }) => TRelationships,\n): {name: TSource['name']; relationships: TRelationships} {\n const relationships = cb({many, one} as any);\n\n return {\n name: table.schema.name,\n relationships,\n };\n}\n\nfunction many(\n ...args: readonly ConnectArg<any, any, TableSchema>[]\n): ManyConnection<any, any, any>[] {\n return args.map(arg => ({\n sourceField: arg.sourceField,\n destField: arg.destField,\n destSchema: arg.destSchema.schema.name,\n cardinality: 'many',\n }));\n}\n\nfunction one(\n ...args: readonly ConnectArg<any, any, TableSchema>[]\n): OneConnection<any, any, any>[] {\n return args.map(arg => ({\n sourceField: arg.sourceField,\n destField: arg.destField,\n destSchema: arg.destSchema.schema.name,\n cardinality: 'one',\n }));\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"relationship-builder.js","names":[],"sources":["../../../../../zero-schema/src/builder/relationship-builder.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport {mapValues} from '../../../shared/src/objects.ts';\nimport type {Relationship, TableSchema} from '../table-schema.ts';\nimport type {TableBuilderWithColumns} from './table-builder.ts';\n\ntype ConnectArg<TSourceField, TDestField, TDest extends TableSchema> = {\n readonly sourceField: TSourceField;\n readonly destField: TDestField;\n readonly destSchema: TableBuilderWithColumns<TDest>;\n};\n\ntype ManyConnection<TSourceField, TDestField, TDest extends TableSchema> = {\n readonly sourceField: TSourceField;\n readonly destField: TDestField;\n readonly destSchema: TDest['name'];\n readonly cardinality: 'many';\n};\n\ntype OneConnection<TSourceField, TDestField, TDest extends TableSchema> = {\n readonly sourceField: TSourceField;\n readonly destField: TDestField;\n readonly destSchema: TDest['name'];\n readonly cardinality: 'one';\n};\n\ntype Prev = [-1, 0, 1, 2, 3, 4, 5, 6];\n\nexport type PreviousSchema<\n TSource extends TableSchema,\n K extends number,\n TDests extends TableSchema[],\n> = K extends 0 ? TSource : TDests[Prev[K]];\n\nexport type Relationships = {\n name: string; // table name\n relationships: Record<string, Relationship>; // relationships for that table\n};\n\n// Overloaded types for better inference\ntype ManyConnector<TSource extends TableSchema> = {\n // Single direct relationship\n <TDest extends TableSchema>(\n arg: ConnectArg<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ): [\n ManyConnection<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ];\n\n // Junction relationship (two hops)\n <TJunction extends TableSchema, TDest extends TableSchema>(\n firstHop: ConnectArg<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TJunction['columns'] & string)[],\n TJunction\n >,\n secondHop: ConnectArg<\n readonly (keyof TJunction['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ): [\n ManyConnection<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TJunction['columns'] & string)[],\n TJunction\n >,\n ManyConnection<\n readonly (keyof TJunction['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ];\n};\n\ntype OneConnector<TSource extends TableSchema> = {\n // Single direct relationship\n <TDest extends TableSchema>(\n arg: ConnectArg<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ): [\n OneConnection<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ];\n\n // Two-hop relationship (e.g., invoice_line -> invoice -> customer)\n <TIntermediate extends TableSchema, TDest extends TableSchema>(\n firstHop: ConnectArg<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TIntermediate['columns'] & string)[],\n TIntermediate\n >,\n secondHop: ConnectArg<\n readonly (keyof TIntermediate['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ): [\n OneConnection<\n readonly (keyof TSource['columns'] & string)[],\n readonly (keyof TIntermediate['columns'] & string)[],\n TIntermediate\n >,\n OneConnection<\n readonly (keyof TIntermediate['columns'] & string)[],\n readonly (keyof TDest['columns'] & string)[],\n TDest\n >,\n ];\n};\n\nexport function relationships<\n TSource extends TableSchema,\n TRelationships extends Record<string, Relationship>,\n>(\n table: TableBuilderWithColumns<TSource>,\n cb: (connects: {\n many: ManyConnector<TSource>;\n one: OneConnector<TSource>;\n }) => TRelationships,\n): {name: TSource['name']; relationships: TRelationships} {\n const relationships = mapValues(\n cb({many, one} as any),\n relationship => relationship,\n );\n\n return {\n name: table.schema.name,\n relationships: relationships as TRelationships,\n };\n}\n\nfunction many(\n ...args: readonly ConnectArg<any, any, TableSchema>[]\n): ManyConnection<any, any, any>[] {\n return args.map(arg => ({\n sourceField: arg.sourceField,\n destField: arg.destField,\n destSchema: arg.destSchema.schema.name,\n cardinality: 'many',\n }));\n}\n\nfunction one(\n ...args: readonly ConnectArg<any, any, TableSchema>[]\n): OneConnection<any, any, any>[] {\n return args.map(arg => ({\n sourceField: arg.sourceField,\n destField: arg.destField,\n destSchema: arg.destSchema.schema.name,\n cardinality: 'one',\n }));\n}\n"],"mappings":";;AA2HA,SAAgB,cAId,OACA,IAIwD;CACxD,MAAM,gBAAgB,UACpB,GAAG;EAAC;EAAM;CAAG,CAAQ,IACrB,iBAAgB,YAClB;CAEA,OAAO;EACL,MAAM,MAAM,OAAO;EACJ;CACjB;AACF;AAEA,SAAS,KACP,GAAG,MAC8B;CACjC,OAAO,KAAK,KAAI,SAAQ;EACtB,aAAa,IAAI;EACjB,WAAW,IAAI;EACf,YAAY,IAAI,WAAW,OAAO;EAClC,aAAa;CACf,EAAE;AACJ;AAEA,SAAS,IACP,GAAG,MAC6B;CAChC,OAAO,KAAK,KAAI,SAAQ;EACtB,aAAa,IAAI;EACjB,WAAW,IAAI;EACf,YAAY,IAAI,WAAW,OAAO;EAClC,aAAa;CACf,EAAE;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-builder.d.ts","sourceRoot":"","sources":["../../../../../zero-schema/src/builder/schema-builder.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,YAAY,EAClB,MAAM,6CAA6C,CAAC;AACrD,OAAO,KAAK,EAEV,MAAM,EACN,WAAW,EACZ,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAC,KAAK,uBAAuB,EAAC,MAAM,oBAAoB,CAAC;AAEhE;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,KAAK,CAAC,OAAO,SAAS,SAAS,uBAAuB,CAAC,WAAW,CAAC,EAAE,EACrE,KAAK,CAAC,cAAc,SAAS,SAAS,aAAa,EAAE,EACrD,KAAK,CAAC,oBAAoB,SAAS,OAAO,GAAG,SAAS,EACtD,KAAK,CAAC,qBAAqB,SAAS,OAAO,GAAG,SAAS,EACvD,OAAO,EAAE;IACT,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,aAAa,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IACpD,sCAAsC;IACtC,QAAQ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qB,SAAS,OAAO,GAAG,SAAS,EACvD,OAAO,EAAE;IACT,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,aAAa,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IACpD,sCAAsC;IACtC,QAAQ,CAAC,mBAAmB,CAAC,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAChE,uCAAuC;IACvC,QAAQ,CAAC,oBAAoB,CAAC,EAAE,qBAAqB,GAAG,SAAS,CAAC;CACnE,GAAG;IACF,MAAM,EAAE;QACN,QAAQ,EAAE,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,OAAO,CACxD,OAAO,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,EACzB;YAAC,IAAI,EAAE,CAAC,CAAA;SAAC,CACV;KACF,CAAC;IACF,aAAa,EAAE;QACb,QAAQ,EAAE,CAAC,IAAI,cAAc,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,GAAG,OAAO,CACrD,cAAc,CAAC,MAAM,CAAC,EACtB;YAAC,IAAI,EAAE,CAAC,CAAA;SAAC,CACV,CAAC,eAAe,CAAC;KACnB,CAAC;IACF,mBAAmB,EAAE,oBAAoB,CAAC;IAC1C,oBAAoB,EAAE,qBAAqB,CAAC;CAC7C,CA0CA;AA+BD,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG;IAChD,YAAY,EAAE,YAAY,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;CACd,CAmBA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { h64 } from "../../../shared/src/hash.js";
|
|
2
|
-
import { mapEntries } from "../../../shared/src/objects.js";
|
|
2
|
+
import { assignProperty, mapEntries } from "../../../shared/src/objects.js";
|
|
3
3
|
import { normalizeClientSchema } from "../../../zero-protocol/src/client-schema.js";
|
|
4
4
|
//#region ../zero-schema/src/builder/schema-builder.ts
|
|
5
5
|
/**
|
|
@@ -19,11 +19,11 @@ function createSchema(options) {
|
|
|
19
19
|
if (serverNames.has(serverName)) throw new Error(`Multiple tables reference the name "${serverName}"`);
|
|
20
20
|
serverNames.add(serverName);
|
|
21
21
|
if (Object.hasOwn(retTables, table.schema.name)) throw new Error(`Table "${table.schema.name}" is defined more than once in the schema`);
|
|
22
|
-
retTables
|
|
22
|
+
assignProperty(retTables, table.schema.name, table.build());
|
|
23
23
|
});
|
|
24
24
|
options.relationships?.forEach((relationships) => {
|
|
25
|
-
if (retRelationships
|
|
26
|
-
retRelationships
|
|
25
|
+
if (Object.hasOwn(retRelationships, relationships.name)) throw new Error(`Relationships for table "${relationships.name}" are defined more than once in the schema`);
|
|
26
|
+
assignProperty(retRelationships, relationships.name, relationships.relationships);
|
|
27
27
|
checkRelationship(relationships.relationships, relationships.name, retTables);
|
|
28
28
|
});
|
|
29
29
|
return {
|
|
@@ -36,10 +36,10 @@ function createSchema(options) {
|
|
|
36
36
|
function checkRelationship(relationships, tableName, tables) {
|
|
37
37
|
Object.entries(relationships).forEach(([name, rel]) => {
|
|
38
38
|
let source = tables[tableName];
|
|
39
|
-
if (source.columns
|
|
39
|
+
if (Object.hasOwn(source.columns, name)) throw new Error(`Relationship "${tableName}"."${name}" cannot have the same name as the column "${name}" on the the table "${source.name}"`);
|
|
40
40
|
rel.forEach((connection) => {
|
|
41
|
-
if (!tables
|
|
42
|
-
if (!source.columns
|
|
41
|
+
if (!Object.hasOwn(tables, connection.destSchema)) throw new Error(`For relationship "${tableName}"."${name}", destination table "${connection.destSchema}" is missing in the schema`);
|
|
42
|
+
if (!Object.hasOwn(source.columns, connection.sourceField[0])) throw new Error(`For relationship "${tableName}"."${name}", the source field "${connection.sourceField[0]}" is missing in the table schema "${source.name}"`);
|
|
43
43
|
source = tables[connection.destSchema];
|
|
44
44
|
});
|
|
45
45
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-builder.js","names":[],"sources":["../../../../../zero-schema/src/builder/schema-builder.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport {h64} from '../../../shared/src/hash.ts';\nimport {mapEntries} from '../../../shared/src/objects.ts';\nimport {\n normalizeClientSchema,\n type ClientSchema,\n} from '../../../zero-protocol/src/client-schema.ts';\nimport type {\n Relationship,\n Schema,\n TableSchema,\n} from '../../../zero-types/src/schema.ts';\nimport type {Relationships} from './relationship-builder.ts';\nimport {type TableBuilderWithColumns} from './table-builder.ts';\n\n/**\n * Note: the keys of the `tables` and `relationships` parameters do not matter.\n * You can assign them to any value you like. E.g.,\n *\n * ```ts\n * createSchema({rsdfgafg: table('users')...}, {sdfd: relationships(users, ...)})\n * ```\n */\nexport function createSchema<\n const TTables extends readonly TableBuilderWithColumns<TableSchema>[],\n const TRelationships extends readonly Relationships[],\n const TEnableLegacyQueries extends boolean | undefined,\n const TEnableLegacyMutators extends boolean | undefined,\n>(options: {\n readonly tables: TTables;\n readonly relationships?: TRelationships | undefined;\n /** @see Schema.enableLegacyQueries */\n readonly enableLegacyQueries?: TEnableLegacyQueries | undefined;\n /** @see Schema.enableLegacyMutators */\n readonly enableLegacyMutators?: TEnableLegacyMutators | undefined;\n}): {\n tables: {\n readonly [K in TTables[number]['schema']['name']]: Extract<\n TTables[number]['schema'],\n {name: K}\n >;\n };\n relationships: {\n readonly [K in TRelationships[number]['name']]: Extract<\n TRelationships[number],\n {name: K}\n >['relationships'];\n };\n enableLegacyQueries: TEnableLegacyQueries;\n enableLegacyMutators: TEnableLegacyMutators;\n} {\n const retTables: Record<string, TableSchema> = {};\n const retRelationships: Record<string, Record<string, Relationship>> = {};\n const serverNames = new Set<string>();\n\n options.tables.forEach(table => {\n const {serverName = table.schema.name} = table.schema;\n if (serverNames.has(serverName)) {\n throw new Error(`Multiple tables reference the name \"${serverName}\"`);\n }\n serverNames.add(serverName);\n if (Object.hasOwn(retTables, table.schema.name)) {\n throw new Error(\n `Table \"${table.schema.name}\" is defined more than once in the schema`,\n );\n }\n retTables
|
|
1
|
+
{"version":3,"file":"schema-builder.js","names":[],"sources":["../../../../../zero-schema/src/builder/schema-builder.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport {h64} from '../../../shared/src/hash.ts';\nimport {assignProperty, mapEntries} from '../../../shared/src/objects.ts';\nimport {\n normalizeClientSchema,\n type ClientSchema,\n} from '../../../zero-protocol/src/client-schema.ts';\nimport type {\n Relationship,\n Schema,\n TableSchema,\n} from '../../../zero-types/src/schema.ts';\nimport type {Relationships} from './relationship-builder.ts';\nimport {type TableBuilderWithColumns} from './table-builder.ts';\n\n/**\n * Note: the keys of the `tables` and `relationships` parameters do not matter.\n * You can assign them to any value you like. E.g.,\n *\n * ```ts\n * createSchema({rsdfgafg: table('users')...}, {sdfd: relationships(users, ...)})\n * ```\n */\nexport function createSchema<\n const TTables extends readonly TableBuilderWithColumns<TableSchema>[],\n const TRelationships extends readonly Relationships[],\n const TEnableLegacyQueries extends boolean | undefined,\n const TEnableLegacyMutators extends boolean | undefined,\n>(options: {\n readonly tables: TTables;\n readonly relationships?: TRelationships | undefined;\n /** @see Schema.enableLegacyQueries */\n readonly enableLegacyQueries?: TEnableLegacyQueries | undefined;\n /** @see Schema.enableLegacyMutators */\n readonly enableLegacyMutators?: TEnableLegacyMutators | undefined;\n}): {\n tables: {\n readonly [K in TTables[number]['schema']['name']]: Extract<\n TTables[number]['schema'],\n {name: K}\n >;\n };\n relationships: {\n readonly [K in TRelationships[number]['name']]: Extract<\n TRelationships[number],\n {name: K}\n >['relationships'];\n };\n enableLegacyQueries: TEnableLegacyQueries;\n enableLegacyMutators: TEnableLegacyMutators;\n} {\n const retTables: Record<string, TableSchema> = {};\n const retRelationships: Record<string, Record<string, Relationship>> = {};\n const serverNames = new Set<string>();\n\n options.tables.forEach(table => {\n const {serverName = table.schema.name} = table.schema;\n if (serverNames.has(serverName)) {\n throw new Error(`Multiple tables reference the name \"${serverName}\"`);\n }\n serverNames.add(serverName);\n if (Object.hasOwn(retTables, table.schema.name)) {\n throw new Error(\n `Table \"${table.schema.name}\" is defined more than once in the schema`,\n );\n }\n assignProperty(retTables, table.schema.name, table.build());\n });\n options.relationships?.forEach(relationships => {\n if (Object.hasOwn(retRelationships, relationships.name)) {\n throw new Error(\n `Relationships for table \"${relationships.name}\" are defined more than once in the schema`,\n );\n }\n assignProperty(\n retRelationships,\n relationships.name,\n relationships.relationships,\n );\n checkRelationship(\n relationships.relationships,\n relationships.name,\n retTables,\n );\n });\n\n return {\n tables: retTables,\n relationships: retRelationships,\n enableLegacyQueries: options.enableLegacyQueries,\n enableLegacyMutators: options.enableLegacyMutators,\n } as any;\n}\n\nfunction checkRelationship(\n relationships: Record<string, Relationship>,\n tableName: string,\n tables: Record<string, TableSchema>,\n) {\n // TS should be able to check this for us but something is preventing it from happening.\n Object.entries(relationships).forEach(([name, rel]) => {\n let source = tables[tableName];\n if (Object.hasOwn(source.columns, name)) {\n throw new Error(\n `Relationship \"${tableName}\".\"${name}\" cannot have the same name as the column \"${name}\" on the the table \"${source.name}\"`,\n );\n }\n rel.forEach(connection => {\n if (!Object.hasOwn(tables, connection.destSchema)) {\n throw new Error(\n `For relationship \"${tableName}\".\"${name}\", destination table \"${connection.destSchema}\" is missing in the schema`,\n );\n }\n if (!Object.hasOwn(source.columns, connection.sourceField[0])) {\n throw new Error(\n `For relationship \"${tableName}\".\"${name}\", the source field \"${connection.sourceField[0]}\" is missing in the table schema \"${source.name}\"`,\n );\n }\n source = tables[connection.destSchema];\n });\n });\n}\n\nexport function clientSchemaFrom(schema: Schema): {\n clientSchema: ClientSchema;\n hash: string;\n} {\n const client = {\n tables: mapEntries(\n schema.tables,\n (name, {serverName, columns, primaryKey}) => [\n serverName ?? name,\n {\n columns: mapEntries(columns, (name, {serverName, type}) => [\n serverName ?? name,\n {type},\n ]),\n primaryKey: primaryKey.map(k => columns[k].serverName ?? k),\n },\n ],\n ),\n } satisfies ClientSchema;\n const clientSchema = normalizeClientSchema(client);\n const hash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,WAAW,2BACzF;GAEF,IAAI,CAAC,OAAO,OAAO,OAAO,SAAS,WAAW,YAAY,EAAE,GAC1D,MAAM,IAAI,MACR,qBAAqB,UAAU,KAAK,KAAK,uBAAuB,WAAW,YAAY,GAAG,oCAAoC,OAAO,KAAK,EAC5I;GAEF,SAAS,OAAO,WAAW;EAC7B,CAAC;CACH,CAAC;AACH;AAEA,SAAgB,iBAAiB,QAG/B;CAgBA,MAAM,eAAe,sBAAsB,EAdzC,QAAQ,WACN,OAAO,SACN,MAAM,EAAC,YAAY,SAAS,iBAAgB,CAC3C,cAAc,MACd;EACE,SAAS,WAAW,UAAU,MAAM,EAAC,YAAY,WAAU,CACzD,cAAc,MACd,EAAC,KAAI,CACP,CAAC;EACD,YAAY,WAAW,KAAI,MAAK,QAAQ,GAAG,cAAc,CAAC;CAC5D,CACF,CACF,EAEyC,CAAM;CAEjD,OAAO;EAAC;EAAc,MADT,IAAI,KAAK,UAAU,YAAY,CAAC,EAAE,SAAS,EAClC;CAAI;AAC5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-builder.d.ts","sourceRoot":"","sources":["../../../../../zero-schema/src/builder/table-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"table-builder.d.ts","sourceRoot":"","sources":["../../../../../zero-schema/src/builder/table-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAEnE,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,2CAA2C,CAAC;AAC1E,OAAO,KAAK,EAAC,WAAW,EAAE,WAAW,EAAC,MAAM,oBAAoB,CAAC;AAGjE,wBAAgB,KAAK,CAAC,KAAK,SAAS,MAAM,EAAE,IAAI,EAAE,KAAK;;;gBAI1B,UAAU;GAEtC;AAED,wBAAgB,MAAM,CAAC,CAAC,SAAS,MAAM,GA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AM,EAAE,UAAU,EAAE,UAAU;oBACL,MAAM;;IAMvD,QAAQ,IAAI,aAAa,CAAC,IAAI,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG;QAAC,QAAQ,EAAE,IAAI,CAAA;KAAC,CAAC;IAOtE,IAAI,MAAM,WAET;CACF;AAED,YAAY,EAAC,aAAa,EAAC,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { mapValues } from "../../../shared/src/objects.js";
|
|
1
2
|
//#region ../zero-schema/src/builder/table-builder.ts
|
|
2
3
|
function table(name) {
|
|
3
4
|
return new TableBuilder({
|
|
@@ -53,7 +54,7 @@ var TableBuilder = class TableBuilder {
|
|
|
53
54
|
});
|
|
54
55
|
}
|
|
55
56
|
columns(columns) {
|
|
56
|
-
const columnSchemas =
|
|
57
|
+
const columnSchemas = mapValues(columns, (column) => column.schema);
|
|
57
58
|
return new TableBuilderWithColumns({
|
|
58
59
|
...this.#schema,
|
|
59
60
|
columns: columnSchemas
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-builder.js","names":["#schema"],"sources":["../../../../../zero-schema/src/builder/table-builder.ts"],"sourcesContent":["import type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {SchemaValue, TableSchema} from '../table-schema.ts';\n\n/* oxlint-disable @typescript-eslint/no-explicit-any */\nexport function table<TName extends string>(name: TName) {\n return new TableBuilder({\n name,\n columns: {},\n primaryKey: [] as any as PrimaryKey,\n });\n}\n\nexport function string<T extends string = string>() {\n return new ColumnBuilder({\n type: 'string',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function number<T extends number = number>() {\n return new ColumnBuilder({\n type: 'number',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function boolean<T extends boolean = boolean>() {\n return new ColumnBuilder({\n type: 'boolean',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function json<T extends ReadonlyJSONValue = ReadonlyJSONValue>() {\n return new ColumnBuilder({\n type: 'json',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function enumeration<T extends string>() {\n return new ColumnBuilder({\n type: 'string',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport const column = {\n string,\n number,\n boolean,\n json,\n enumeration,\n};\n\nexport class TableBuilder<TShape extends TableSchema> {\n readonly #schema: TShape;\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n from<ServerName extends string>(serverName: ServerName) {\n return new TableBuilder<TShape>({\n ...this.#schema,\n // Strip the \"public.\" schema if specified, as tables in the upstream\n // \"public\" schema are created without the schema prefix on the replica.\n // See liteTableName() in zero-cache/src/types/names.ts\n serverName: serverName.startsWith('public.')\n ? serverName.substring('public.'.length)\n : serverName,\n });\n }\n\n columns<const TColumns extends Record<string, ColumnBuilder<SchemaValue>>>(\n columns: TColumns,\n ): TableBuilderWithColumns<{\n name: TShape['name'];\n columns: {[K in keyof TColumns]: TColumns[K]['schema']};\n primaryKey: TShape['primaryKey'];\n }> {\n const columnSchemas =
|
|
1
|
+
{"version":3,"file":"table-builder.js","names":["#schema"],"sources":["../../../../../zero-schema/src/builder/table-builder.ts"],"sourcesContent":["import type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {mapValues} from '../../../shared/src/objects.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {SchemaValue, TableSchema} from '../table-schema.ts';\n\n/* oxlint-disable @typescript-eslint/no-explicit-any */\nexport function table<TName extends string>(name: TName) {\n return new TableBuilder({\n name,\n columns: {},\n primaryKey: [] as any as PrimaryKey,\n });\n}\n\nexport function string<T extends string = string>() {\n return new ColumnBuilder({\n type: 'string',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function number<T extends number = number>() {\n return new ColumnBuilder({\n type: 'number',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function boolean<T extends boolean = boolean>() {\n return new ColumnBuilder({\n type: 'boolean',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function json<T extends ReadonlyJSONValue = ReadonlyJSONValue>() {\n return new ColumnBuilder({\n type: 'json',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport function enumeration<T extends string>() {\n return new ColumnBuilder({\n type: 'string',\n optional: false,\n customType: null as unknown as T,\n });\n}\n\nexport const column = {\n string,\n number,\n boolean,\n json,\n enumeration,\n};\n\nexport class TableBuilder<TShape extends TableSchema> {\n readonly #schema: TShape;\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n from<ServerName extends string>(serverName: ServerName) {\n return new TableBuilder<TShape>({\n ...this.#schema,\n // Strip the \"public.\" schema if specified, as tables in the upstream\n // \"public\" schema are created without the schema prefix on the replica.\n // See liteTableName() in zero-cache/src/types/names.ts\n serverName: serverName.startsWith('public.')\n ? serverName.substring('public.'.length)\n : serverName,\n });\n }\n\n columns<const TColumns extends Record<string, ColumnBuilder<SchemaValue>>>(\n columns: TColumns,\n ): TableBuilderWithColumns<{\n name: TShape['name'];\n columns: {[K in keyof TColumns]: TColumns[K]['schema']};\n primaryKey: TShape['primaryKey'];\n }> {\n const columnSchemas = mapValues(columns, column => column.schema);\n return new TableBuilderWithColumns({\n ...this.#schema,\n columns: columnSchemas,\n }) as any;\n }\n}\n\nexport class TableBuilderWithColumns<TShape extends TableSchema> {\n readonly #schema: TShape;\n\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n primaryKey<TPKColNames extends (keyof TShape['columns'])[]>(\n ...pkColumnNames: TPKColNames\n ) {\n return new TableBuilderWithColumns({\n ...this.#schema,\n primaryKey: pkColumnNames,\n });\n }\n\n get schema() {\n return this.#schema;\n }\n\n build() {\n // We can probably get the type system to throw an error if primaryKey is not called\n // before passing the schema to createSchema\n // Till then --\n if (this.#schema.primaryKey.length === 0) {\n throw new Error(`Table \"${this.#schema.name}\" is missing a primary key`);\n }\n const names = new Set<string>();\n for (const [col, {serverName}] of Object.entries(this.#schema.columns)) {\n const name = serverName ?? col;\n if (names.has(name)) {\n throw new Error(\n `Table \"${\n this.#schema.name\n }\" has multiple columns referencing \"${name}\"`,\n );\n }\n names.add(name);\n }\n return this.#schema;\n }\n}\n\nclass ColumnBuilder<TShape extends SchemaValue<any>> {\n readonly #schema: TShape;\n constructor(schema: TShape) {\n this.#schema = schema;\n }\n\n from<ServerName extends string>(serverName: ServerName) {\n return new ColumnBuilder<TShape & {serverName: string}>({\n ...this.#schema,\n serverName,\n });\n }\n\n optional(): ColumnBuilder<Omit<TShape, 'optional'> & {optional: true}> {\n return new ColumnBuilder({\n ...this.#schema,\n optional: true,\n });\n }\n\n get schema() {\n return this.#schema;\n }\n}\n\nexport type {ColumnBuilder};\n"],"mappings":";;AAMA,SAAgB,MAA4B,MAAa;CACvD,OAAO,IAAI,aAAa;EACtB;EACA,SAAS,CAAC;EACV,YAAY,CAAC;CACf,CAAC;AACH;AAEA,SAAgB,SAAoC;CAClD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,SAAoC;CAClD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,UAAuC;CACrD,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,OAAwD;CACtE,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAEA,SAAgB,cAAgC;CAC9C,OAAO,IAAI,cAAc;EACvB,MAAM;EACN,UAAU;EACV,YAAY;CACd,CAAC;AACH;AAUA,IAAa,eAAb,MAAa,aAAyC;CACpD;CACA,YAAY,QAAgB;EAC1B,KAAKA,UAAU;CACjB;CAEA,KAAgC,YAAwB;EACtD,OAAO,IAAI,aAAqB;GAC9B,GAAG,KAAKA;GAIR,YAAY,WAAW,WAAW,SAAS,IACvC,WAAW,UAAU,CAAgB,IACrC;EACN,CAAC;CACH;CAEA,QACE,SAKC;EACD,MAAM,gBAAgB,UAAU,UAAS,WAAU,OAAO,MAAM;EAChE,OAAO,IAAI,wBAAwB;GACjC,GAAG,KAAKA;GACR,SAAS;EACX,CAAC;CACH;AACF;AAEA,IAAa,0BAAb,MAAa,wBAAoD;CAC/D;CAEA,YAAY,QAAgB;EAC1B,KAAKA,UAAU;CACjB;CAEA,WACE,GAAG,eACH;EACA,OAAO,IAAI,wBAAwB;GACjC,GAAG,KAAKA;GACR,YAAY;EACd,CAAC;CACH;CAEA,IAAI,SAAS;EACX,OAAO,KAAKA;CACd;CAEA,QAAQ;EAIN,IAAI,KAAKA,QAAQ,WAAW,WAAW,GACrC,MAAM,IAAI,MAAM,UAAU,KAAKA,QAAQ,KAAK,2BAA2B;EAEzE,MAAM,wBAAQ,IAAI,IAAY;EAC9B,KAAK,MAAM,CAAC,KAAK,EAAC,iBAAgB,OAAO,QAAQ,KAAKA,QAAQ,OAAO,GAAG;GACtE,MAAM,OAAO,cAAc;GAC3B,IAAI,MAAM,IAAI,IAAI,GAChB,MAAM,IAAI,MACR,UACE,KAAKA,QAAQ,KACd,sCAAsC,KAAK,EAC9C;GAEF,MAAM,IAAI,IAAI;EAChB;EACA,OAAO,KAAKA;CACd;AACF;AAEA,IAAM,gBAAN,MAAM,cAA+C;CACnD;CACA,YAAY,QAAgB;EAC1B,KAAKA,UAAU;CACjB;CAEA,KAAgC,YAAwB;EACtD,OAAO,IAAI,cAA6C;GACtD,GAAG,KAAKA;GACR;EACF,CAAC;CACH;CAEA,WAAuE;EACrE,OAAO,IAAI,cAAc;GACvB,GAAG,KAAKA;GACR,UAAU;EACZ,CAAC;CACH;CAEA,IAAI,SAAS;EACX,OAAO,KAAKA;CACd;AACF"}
|
|
@@ -162,7 +162,8 @@ function makeServerTableCRUD(schema) {
|
|
|
162
162
|
value = removeUndefined(value);
|
|
163
163
|
const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];
|
|
164
164
|
const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);
|
|
165
|
-
const
|
|
165
|
+
const primaryKeyColumns = origAndServerNamesFor(schema.primaryKey, schema);
|
|
166
|
+
const stmt = formatPgInternalConvert(sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(targetedColumns.map(([, serverName]) => sql.ident(serverName)), ",")}) VALUES (${sql.join(Object.entries(value).map(([col, v]) => sqlInsertValue(v, serverTableSchema[serverNameFor(col, schema)])), ", ")}) ON CONFLICT (${sql.join(primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)), ", ")}) DO NOTHING`);
|
|
166
167
|
await this[dbTxSymbol].query(stmt.text, stmt.values);
|
|
167
168
|
},
|
|
168
169
|
async upsert(value) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.js","names":["#dbTransaction","#schema","#serverSchema","#tableCRUDs","#getOrFetchServerSchema"],"sources":["../../../../zero-server/src/custom.ts"],"sourcesContent":["import {assert} from '../../shared/src/asserts.ts';\nimport {mapValues} from '../../shared/src/objects.ts';\nimport {recordProxy} from '../../shared/src/record-proxy.ts';\nimport {\n formatPgInternalConvert,\n sql,\n sqlConvertColumnArg,\n} from '../../z2s/src/sql.ts';\nimport type {TableSchema} from '../../zero-schema/src/table-schema.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {\n ServerColumnSchema,\n ServerSchema,\n ServerTableSchema,\n} from '../../zero-types/src/server-schema.ts';\nimport {\n type CRUDExecutor,\n type CRUDKind,\n makeCRUDMutate,\n makeTransactionMutate,\n type SchemaCRUD,\n type TableCRUD,\n type TransactionMutate,\n} from '../../zql/src/mutate/crud.ts';\nimport type {\n DBTransaction,\n MutateCRUD,\n ServerTransaction,\n} from '../../zql/src/mutate/custom.ts';\nimport {createRunnableBuilder} from '../../zql/src/query/create-builder.ts';\nimport {QueryDelegateBase} from '../../zql/src/query/query-delegate-base.ts';\nimport {asQueryInternals} from '../../zql/src/query/query-internals.ts';\nimport type {\n HumanReadable,\n Query,\n RunOptions,\n} from '../../zql/src/query/query.ts';\nimport type {ConditionalSchemaQuery} from '../../zql/src/query/schema-query.ts';\nimport {getServerSchema} from './schema.ts';\n\nexport type CustomMutatorDefs<TDBTransaction> = {\n [namespaceOrKey: string]:\n | CustomMutatorImpl<TDBTransaction>\n | CustomMutatorDefs<TDBTransaction>;\n};\n\nexport type CustomMutatorImpl<\n TDBTransaction,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TArgs = any,\n Context = unknown,\n> = (tx: TDBTransaction, args: TArgs, ctx: Context) => Promise<void>;\n\n/**\n * QueryDelegate implementation for server-side transactions.\n * Extends QueryDelegateBase to satisfy the QueryDelegate interface,\n * but overrides run() to execute against Postgres and throws on\n * preload()/materialize() which don't make sense server-side.\n */\nclass ServerTransactionQueryDelegate extends QueryDelegateBase {\n readonly #dbTransaction: DBTransaction<unknown>;\n readonly #schema: Schema;\n readonly #serverSchema: ServerSchema;\n\n readonly defaultQueryComplete = true;\n\n constructor(\n dbTransaction: DBTransaction<unknown>,\n schema: Schema,\n serverSchema: ServerSchema,\n ) {\n super();\n this.#dbTransaction = dbTransaction;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n }\n\n getSource(): never {\n throw new Error('not implemented');\n }\n\n override run<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n return this.#dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n\n override preload(): never {\n throw new Error('preload() is not supported in server transactions');\n }\n\n override materialize(): never {\n throw new Error('materialize() is not supported in server transactions');\n }\n}\n\nexport class TransactionImpl<\n TSchema extends Schema,\n TWrappedTransaction,\n> implements ServerTransaction<TSchema, TWrappedTransaction> {\n readonly location = 'server';\n readonly reason = 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n readonly clientID: string;\n readonly mutationID: number;\n readonly mutate: TransactionMutate<TSchema>;\n /**\n * @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: ConditionalSchemaQuery<TSchema>;\n\n readonly #schema: TSchema;\n readonly #serverSchema: ServerSchema;\n\n constructor(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n mutate: TransactionMutate<TSchema>,\n schema: TSchema,\n serverSchema: ServerSchema,\n ) {\n this.dbTransaction = dbTransaction;\n this.clientID = clientID;\n this.mutationID = mutationID;\n this.mutate = mutate;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n\n const delegate = new ServerTransactionQueryDelegate(\n dbTransaction,\n schema,\n serverSchema,\n );\n this.query = createRunnableBuilder(delegate, schema);\n }\n\n run<TTable extends keyof TSchema['tables'] & string, TReturn>(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n\n // Execute the query using the database-specific executor\n return this.dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n}\n\nconst dbTxSymbol = Symbol();\n\nconst serverSchemaSymbol = Symbol();\n\ntype WithHiddenTxAndSchema = {\n [dbTxSymbol]: DBTransaction<unknown>;\n [serverSchemaSymbol]: ServerSchema;\n};\n\n/**\n * Factory for creating MutateCRUD instances efficiently.\n *\n * Pre-creates the SQL-generating TableCRUD methods once from the schema,\n * caches the serverSchema after first fetch, and only binds the transaction\n * at transaction time.\n *\n * Use this when you need to create many transactions and want to avoid\n * the overhead of re-creating CRUD methods for each one.\n */\nexport class CRUDMutatorFactory<S extends Schema> {\n readonly #schema: S;\n readonly #tableCRUDs: Record<string, TableCRUD<TableSchema>>;\n #serverSchema: ServerSchema | undefined;\n\n constructor(schema: S) {\n this.#schema = schema;\n // Pre-create TableCRUD methods for each table once\n this.#tableCRUDs = {};\n for (const tableSchema of Object.values(schema.tables)) {\n this.#tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n }\n\n /**\n * Gets the cached serverSchema, or fetches and caches it on first call.\n */\n async #getOrFetchServerSchema(\n dbTransaction: DBTransaction<unknown>,\n ): Promise<ServerSchema> {\n if (!this.#serverSchema) {\n this.#serverSchema = await getServerSchema(dbTransaction, this.#schema);\n }\n return this.#serverSchema;\n }\n\n /**\n * Creates a CRUDExecutor bound to the given transaction and serverSchema.\n * Uses the pre-created TableCRUD methods from construction time.\n */\n createExecutor(\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n ): CRUDExecutor {\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(this.#tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n }\n\n /**\n * Creates a full ServerTransaction.\n * Fetches/caches serverSchema automatically.\n */\n async createTransaction<TWrappedTransaction>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n ): Promise<TransactionImpl<S, TWrappedTransaction>> {\n const serverSchema = await this.#getOrFetchServerSchema(dbTransaction);\n const executor = this.createExecutor(dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(this.#schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n this.#schema,\n serverSchema,\n );\n }\n}\n\nexport async function makeServerTransaction<\n TSchema extends Schema,\n TWrappedTransaction,\n>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n schema: TSchema,\n) {\n const serverSchema = await getServerSchema(dbTransaction, schema);\n // Use the internal executor and shared function directly,\n // bypassing the validation in makeMutateCRUD/makeSchemaCRUD\n const executor = makeServerCRUDExecutor(schema, dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n schema,\n serverSchema,\n );\n}\n\n/**\n * @deprecated Use transactions instead.\n *\n * Returns a curried function for backwards compatibility.\n */\nexport function makeSchemaCRUD<S extends Schema>(\n schema: S,\n): (\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n) => MutateCRUD<S, true> {\n return (dbTransaction: DBTransaction<unknown>, serverSchema: ServerSchema) =>\n makeCRUDMutate(\n schema,\n true,\n makeServerCRUDExecutor(schema, dbTransaction, serverSchema),\n );\n}\n\nfunction removeUndefined<T extends Record<string, unknown>>(value: T): T {\n const valueWithoutUndefined: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n valueWithoutUndefined[key] = val;\n }\n }\n return valueWithoutUndefined as T;\n}\n\n/**\n * Creates a CRUDExecutor for server-side SQL execution.\n *\n * For users with very large schemas it is expensive to re-create\n * all the CRUD mutators for each transaction. Instead, we create\n * the SQL-generating methods once up-front and then bind them to\n * the transaction as requested.\n */\nfunction makeServerCRUDExecutor<S extends Schema>(\n schema: S,\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n): CRUDExecutor {\n // Pre-create TableCRUD methods for each table (optimization for large schemas)\n const tableCRUDs: Record<string, TableCRUD<TableSchema>> = {};\n for (const tableSchema of Object.values(schema.tables)) {\n tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n\n // Bind transaction context to the methods\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n // Return executor that dispatches to bound methods\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n}\n\n/**\n * Creates SQL-generating TableCRUD methods for a table.\n * Methods use `this` context to access transaction and server schema.\n */\nfunction makeServerTableCRUD(schema: TableSchema): TableCRUD<TableSchema> {\n return {\n async insert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, v]) =>\n sqlInsertValue(v, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )})`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async upsert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, val]) =>\n sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) DO UPDATE SET ${sql.join(\n Object.entries(value).map(\n ([col, val]) =>\n sql`${sql.ident(\n schema.columns[col].serverName ?? col,\n )} = ${sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)])}`,\n ),\n ', ',\n )}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async update(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const stmt = formatPgInternalConvert(\n sql`UPDATE ${sql.ident(serverName(schema))} SET ${sql.join(\n targetedColumns.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlInsertValue(value[origName], serverTableSchema[serverName])}`,\n ),\n ', ',\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async delete(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const stmt = formatPgInternalConvert(\n sql`DELETE FROM ${sql.ident(\n serverName(schema),\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n };\n}\n\nfunction serverName(x: {name: string; serverName?: string | undefined}) {\n return x.serverName ?? x.name;\n}\n\nfunction primaryKeyClause(\n schema: TableSchema,\n serverTableSchema: ServerTableSchema,\n row: Record<string, unknown>,\n) {\n const primaryKey = origAndServerNamesFor(schema.primaryKey, schema);\n return sql`${sql.join(\n primaryKey.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlValue(row[origName], serverTableSchema[serverName])}`,\n ),\n ' AND ',\n )}`;\n}\n\nfunction origAndServerNamesFor(\n originalNames: readonly string[],\n schema: TableSchema,\n): [origName: string, serverName: string][] {\n return originalNames.map(\n name => [name, serverNameFor(name, schema)] as const,\n );\n}\n\nfunction serverNameFor(originalName: string, schema: TableSchema): string {\n const col = schema.columns[originalName];\n assert(\n col,\n `Column ${originalName} was not found in the Zero schema for the table ${schema.name}`,\n );\n return col.serverName ?? originalName;\n}\n\nfunction sqlValue(value: unknown, serverColumnSchema: ServerColumnSchema) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, true);\n}\n\nfunction sqlInsertValue(\n value: unknown,\n serverColumnSchema: ServerColumnSchema,\n) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2DA,IAAM,iCAAN,cAA6C,kBAAkB;CAC7D;CACA;CACA;CAEA,uBAAgC;CAEhC,YACE,eACA,QACA,cACA;EACA,MAAM;EACN,KAAKA,iBAAiB;EACtB,KAAKC,UAAU;EACf,KAAKC,gBAAgB;CACvB;CAEA,YAAmB;EACjB,MAAM,IAAI,MAAM,iBAAiB;CACnC;CAEA,IAKE,OACA,UACiC;EACjC,MAAM,iBAAiB,iBAAiB,KAAK;EAC7C,OAAO,KAAKF,eAAe,SACzB,eAAe,KACf,eAAe,QACf,KAAKC,SACL,KAAKC,aACP;CACF;CAEA,UAA0B;EACxB,MAAM,IAAI,MAAM,mDAAmD;CACrE;CAEA,cAA8B;EAC5B,MAAM,IAAI,MAAM,uDAAuD;CACzE;AACF;AAEA,IAAa,kBAAb,MAG6D;CAC3D,WAAoB;CACpB,SAAkB;CAClB;CACA;CACA;CACA;;;;CAIA;CAEA;CACA;CAEA,YACE,eACA,UACA,YACA,QACA,QACA,cACA;EACA,KAAK,gBAAgB;EACrB,KAAK,WAAW;EAChB,KAAK,aAAa;EAClB,KAAK,SAAS;EACd,KAAKD,UAAU;EACf,KAAKC,gBAAgB;EAErB,MAAM,WAAW,IAAI,+BACnB,eACA,QACA,YACF;EACA,KAAK,QAAQ,sBAAsB,UAAU,MAAM;CACrD;CAEA,IACE,OACA,UACiC;EACjC,MAAM,iBAAiB,iBAAiB,KAAK;EAG7C,OAAO,KAAK,cAAc,SACxB,eAAe,KACf,eAAe,QACf,KAAKD,SACL,KAAKC,aACP;CACF;AACF;AAEA,IAAM,aAAa,OAAO;AAE1B,IA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A,SAAS,WAAW,GAAoD;CACtE,OAAO,EAAE,cAAc,EAAE;AAC3B;AAEA,SAAS,iBACP,QACA,mBACA,KACA;CACA,MAAM,aAAa,sBAAsB,OAAO,YAAY,MAAM;CAClE,OAAO,GAAG,GAAG,IAAI,KACf,WAAW,KACR,CAAC,UAAU,gBACV,GAAG,GAAG,IAAI,MAAM,UAAU,EAAE,KAAK,SAAS,IAAI,WAAW,kBAAkB,WAAW,GAC1F,GACA,OACF;AACF;AAEA,SAAS,sBACP,eACA,QAC0C;CAC1C,OAAO,cAAc,KACnB,SAAQ,CAAC,MAAM,cAAc,MAAM,MAAM,CAAC,CAC5C;AACF;AAEA,SAAS,cAAc,cAAsB,QAA6B;CACxE,MAAM,MAAM,OAAO,QAAQ;CAC3B,OACE,KACA,UAAU,aAAa,kDAAkD,OAAO,MAClF;CACA,OAAO,IAAI,cAAc;AAC3B;AAEA,SAAS,SAAS,OAAgB,oBAAwC;CACxE,OAAO,oBAAoB,oBAAoB,OAAO,OAAO,IAAI;AACnE;AAEA,SAAS,eACP,OACA,oBACA;CACA,OAAO,oBAAoB,oBAAoB,OAAO,OAAO,KAAK;AACpE"}
|
|
1
|
+
{"version":3,"file":"custom.js","names":["#dbTransaction","#schema","#serverSchema","#tableCRUDs","#getOrFetchServerSchema"],"sources":["../../../../zero-server/src/custom.ts"],"sourcesContent":["import {assert} from '../../shared/src/asserts.ts';\nimport {mapValues} from '../../shared/src/objects.ts';\nimport {recordProxy} from '../../shared/src/record-proxy.ts';\nimport {\n formatPgInternalConvert,\n sql,\n sqlConvertColumnArg,\n} from '../../z2s/src/sql.ts';\nimport type {TableSchema} from '../../zero-schema/src/table-schema.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {\n ServerColumnSchema,\n ServerSchema,\n ServerTableSchema,\n} from '../../zero-types/src/server-schema.ts';\nimport {\n type CRUDExecutor,\n type CRUDKind,\n makeCRUDMutate,\n makeTransactionMutate,\n type SchemaCRUD,\n type TableCRUD,\n type TransactionMutate,\n} from '../../zql/src/mutate/crud.ts';\nimport type {\n DBTransaction,\n MutateCRUD,\n ServerTransaction,\n} from '../../zql/src/mutate/custom.ts';\nimport {createRunnableBuilder} from '../../zql/src/query/create-builder.ts';\nimport {QueryDelegateBase} from '../../zql/src/query/query-delegate-base.ts';\nimport {asQueryInternals} from '../../zql/src/query/query-internals.ts';\nimport type {\n HumanReadable,\n Query,\n RunOptions,\n} from '../../zql/src/query/query.ts';\nimport type {ConditionalSchemaQuery} from '../../zql/src/query/schema-query.ts';\nimport {getServerSchema} from './schema.ts';\n\nexport type CustomMutatorDefs<TDBTransaction> = {\n [namespaceOrKey: string]:\n | CustomMutatorImpl<TDBTransaction>\n | CustomMutatorDefs<TDBTransaction>;\n};\n\nexport type CustomMutatorImpl<\n TDBTransaction,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TArgs = any,\n Context = unknown,\n> = (tx: TDBTransaction, args: TArgs, ctx: Context) => Promise<void>;\n\n/**\n * QueryDelegate implementation for server-side transactions.\n * Extends QueryDelegateBase to satisfy the QueryDelegate interface,\n * but overrides run() to execute against Postgres and throws on\n * preload()/materialize() which don't make sense server-side.\n */\nclass ServerTransactionQueryDelegate extends QueryDelegateBase {\n readonly #dbTransaction: DBTransaction<unknown>;\n readonly #schema: Schema;\n readonly #serverSchema: ServerSchema;\n\n readonly defaultQueryComplete = true;\n\n constructor(\n dbTransaction: DBTransaction<unknown>,\n schema: Schema,\n serverSchema: ServerSchema,\n ) {\n super();\n this.#dbTransaction = dbTransaction;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n }\n\n getSource(): never {\n throw new Error('not implemented');\n }\n\n override run<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n return this.#dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n\n override preload(): never {\n throw new Error('preload() is not supported in server transactions');\n }\n\n override materialize(): never {\n throw new Error('materialize() is not supported in server transactions');\n }\n}\n\nexport class TransactionImpl<\n TSchema extends Schema,\n TWrappedTransaction,\n> implements ServerTransaction<TSchema, TWrappedTransaction> {\n readonly location = 'server';\n readonly reason = 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n readonly clientID: string;\n readonly mutationID: number;\n readonly mutate: TransactionMutate<TSchema>;\n /**\n * @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: ConditionalSchemaQuery<TSchema>;\n\n readonly #schema: TSchema;\n readonly #serverSchema: ServerSchema;\n\n constructor(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n mutate: TransactionMutate<TSchema>,\n schema: TSchema,\n serverSchema: ServerSchema,\n ) {\n this.dbTransaction = dbTransaction;\n this.clientID = clientID;\n this.mutationID = mutationID;\n this.mutate = mutate;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n\n const delegate = new ServerTransactionQueryDelegate(\n dbTransaction,\n schema,\n serverSchema,\n );\n this.query = createRunnableBuilder(delegate, schema);\n }\n\n run<TTable extends keyof TSchema['tables'] & string, TReturn>(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n\n // Execute the query using the database-specific executor\n return this.dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n}\n\nconst dbTxSymbol = Symbol();\n\nconst serverSchemaSymbol = Symbol();\n\ntype WithHiddenTxAndSchema = {\n [dbTxSymbol]: DBTransaction<unknown>;\n [serverSchemaSymbol]: ServerSchema;\n};\n\n/**\n * Factory for creating MutateCRUD instances efficiently.\n *\n * Pre-creates the SQL-generating TableCRUD methods once from the schema,\n * caches the serverSchema after first fetch, and only binds the transaction\n * at transaction time.\n *\n * Use this when you need to create many transactions and want to avoid\n * the overhead of re-creating CRUD methods for each one.\n */\nexport class CRUDMutatorFactory<S extends Schema> {\n readonly #schema: S;\n readonly #tableCRUDs: Record<string, TableCRUD<TableSchema>>;\n #serverSchema: ServerSchema | undefined;\n\n constructor(schema: S) {\n this.#schema = schema;\n // Pre-create TableCRUD methods for each table once\n this.#tableCRUDs = {};\n for (const tableSchema of Object.values(schema.tables)) {\n this.#tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n }\n\n /**\n * Gets the cached serverSchema, or fetches and caches it on first call.\n */\n async #getOrFetchServerSchema(\n dbTransaction: DBTransaction<unknown>,\n ): Promise<ServerSchema> {\n if (!this.#serverSchema) {\n this.#serverSchema = await getServerSchema(dbTransaction, this.#schema);\n }\n return this.#serverSchema;\n }\n\n /**\n * Creates a CRUDExecutor bound to the given transaction and serverSchema.\n * Uses the pre-created TableCRUD methods from construction time.\n */\n createExecutor(\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n ): CRUDExecutor {\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(this.#tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n }\n\n /**\n * Creates a full ServerTransaction.\n * Fetches/caches serverSchema automatically.\n */\n async createTransaction<TWrappedTransaction>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n ): Promise<TransactionImpl<S, TWrappedTransaction>> {\n const serverSchema = await this.#getOrFetchServerSchema(dbTransaction);\n const executor = this.createExecutor(dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(this.#schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n this.#schema,\n serverSchema,\n );\n }\n}\n\nexport async function makeServerTransaction<\n TSchema extends Schema,\n TWrappedTransaction,\n>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n schema: TSchema,\n) {\n const serverSchema = await getServerSchema(dbTransaction, schema);\n // Use the internal executor and shared function directly,\n // bypassing the validation in makeMutateCRUD/makeSchemaCRUD\n const executor = makeServerCRUDExecutor(schema, dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n schema,\n serverSchema,\n );\n}\n\n/**\n * @deprecated Use transactions instead.\n *\n * Returns a curried function for backwards compatibility.\n */\nexport function makeSchemaCRUD<S extends Schema>(\n schema: S,\n): (\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n) => MutateCRUD<S, true> {\n return (dbTransaction: DBTransaction<unknown>, serverSchema: ServerSchema) =>\n makeCRUDMutate(\n schema,\n true,\n makeServerCRUDExecutor(schema, dbTransaction, serverSchema),\n );\n}\n\nfunction removeUndefined<T extends Record<string, unknown>>(value: T): T {\n const valueWithoutUndefined: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n valueWithoutUndefined[key] = val;\n }\n }\n return valueWithoutUndefined as T;\n}\n\n/**\n * Creates a CRUDExecutor for server-side SQL execution.\n *\n * For users with very large schemas it is expensive to re-create\n * all the CRUD mutators for each transaction. Instead, we create\n * the SQL-generating methods once up-front and then bind them to\n * the transaction as requested.\n */\nfunction makeServerCRUDExecutor<S extends Schema>(\n schema: S,\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n): CRUDExecutor {\n // Pre-create TableCRUD methods for each table (optimization for large schemas)\n const tableCRUDs: Record<string, TableCRUD<TableSchema>> = {};\n for (const tableSchema of Object.values(schema.tables)) {\n tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n\n // Bind transaction context to the methods\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n // Return executor that dispatches to bound methods\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n}\n\n/**\n * Creates SQL-generating TableCRUD methods for a table.\n * Methods use `this` context to access transaction and server schema.\n */\nfunction makeServerTableCRUD(schema: TableSchema): TableCRUD<TableSchema> {\n return {\n async insert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, v]) =>\n sqlInsertValue(v, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) DO NOTHING`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async upsert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, val]) =>\n sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) DO UPDATE SET ${sql.join(\n Object.entries(value).map(\n ([col, val]) =>\n sql`${sql.ident(\n schema.columns[col].serverName ?? col,\n )} = ${sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)])}`,\n ),\n ', ',\n )}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async update(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const stmt = formatPgInternalConvert(\n sql`UPDATE ${sql.ident(serverName(schema))} SET ${sql.join(\n targetedColumns.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlInsertValue(value[origName], serverTableSchema[serverName])}`,\n ),\n ', ',\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async delete(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const stmt = formatPgInternalConvert(\n sql`DELETE FROM ${sql.ident(\n serverName(schema),\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n };\n}\n\nfunction serverName(x: {name: string; serverName?: string | undefined}) {\n return x.serverName ?? x.name;\n}\n\nfunction primaryKeyClause(\n schema: TableSchema,\n serverTableSchema: ServerTableSchema,\n row: Record<string, unknown>,\n) {\n const primaryKey = origAndServerNamesFor(schema.primaryKey, schema);\n return sql`${sql.join(\n primaryKey.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlValue(row[origName], serverTableSchema[serverName])}`,\n ),\n ' AND ',\n )}`;\n}\n\nfunction origAndServerNamesFor(\n originalNames: readonly string[],\n schema: TableSchema,\n): [origName: string, serverName: string][] {\n return originalNames.map(\n name => [name, serverNameFor(name, schema)] as const,\n );\n}\n\nfunction serverNameFor(originalName: string, schema: TableSchema): string {\n const col = schema.columns[originalName];\n assert(\n col,\n `Column ${originalName} was not found in the Zero schema for the table ${schema.name}`,\n );\n return col.serverName ?? originalName;\n}\n\nfunction sqlValue(value: unknown, serverColumnSchema: ServerColumnSchema) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, true);\n}\n\nfunction sqlInsertValue(\n value: unknown,\n serverColumnSchema: ServerColumnSchema,\n) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2DA,IAAM,iCAAN,cAA6C,kBAAkB;CAC7D;CACA;CACA;CAEA,uBAAgC;CAEhC,YACE,eACA,QACA,cACA;EACA,MAAM;EACN,KAAKA,iBAAiB;EACtB,KAAKC,UAAU;EACf,KAAKC,gBAAgB;CACvB;CAEA,YAAmB;EACjB,MAAM,IAAI,MAAM,iBAAiB;CACnC;CAEA,IAKE,OACA,UACiC;EACjC,MAAM,iBAAiB,iBAAiB,KAAK;EAC7C,OAAO,KAAKF,eAAe,SACzB,eAAe,KACf,eAAe,QACf,KAAKC,SACL,KAAKC,aACP;CACF;CAEA,UAA0B;EACxB,MAAM,IAAI,MAAM,mDAAmD;CACrE;CAEA,cAA8B;EAC5B,MAAM,IAAI,MAAM,uDAAuD;CACzE;AACF;AAEA,IAAa,kBAAb,MAG6D;CAC3D,WAAoB;CACpB,SAAkB;CAClB;CACA;CACA;CACA;;;;CAIA;CAEA;CACA;CAEA,YACE,eACA,UACA,YACA,QACA,QACA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pE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-apply-change.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/view-apply-change.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"view-apply-change.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/view-apply-change.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,iCAAiC,CAAC;AAC9D,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAkB,KAAK,IAAI,EAAC,MAAM,WAAW,CAAC;AAErD,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAC,KAAK,EAAE,MAAM,EAAC,MAAM,WAAW,CAAC;AAE7C,eAAO,MAAM,cAAc,eAAe,CAAC;AAC3C,eAAO,MAAM,QAAQ,eAAe,CAAC;AAErC,KAAK,iBAAiB,GAAG,KAAK,GAAG;IAC/B,QAAQ,CAAC,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1C,CAAC;AAEF,KAAK,gBAAgB,GAAG,QAAQ,CAAC,iBAAiB,CAAC,CAAC;AAEpD;;;;GAIG;AACH,KAAK,SAAS,CAAC,CAAC,SAAS,MAAM,IAAI,CAAC,SAAS,IAAI,GAC7C,gBAAgB,GAChB,iBAAiB,CAAC;AAQtB;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,GAAG,EAAE,GAAG,CAAC;IACT,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,EAAE,CAAC,CAAC;CAC/C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,QAAQ,GAAG,IAAI,GAAG,YAAY,CAAC;AAE3C;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAClB,aAAa,GACb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,mBAAmB,CAAC,CAAC,SAAS,MAAM,EAClD,WAAW,EAAE,SAAS,CAAC,CAAC,CAAC,EACzB,MAAM,EAAE,UAAU,EAClB,MAAM,EAAE,YAAY,EACpB,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,CAAC,GACR,SAAS,CAAC,CAAC,CAAC,CAuUd;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAC1B,WAAW,EAAE,KAAK,EAClB,OAAO,EAAE,UAAU,EAAE,EACrB,MAAM,EAAE,YAAY,EACpB,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,OAAe,EACxB,MAAM,GAAE,MAAc,GACrB,KAAK,CAcP"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assert, assertArray, assertNumber, unreachable } from "../../../shared/src/asserts.js";
|
|
2
2
|
import { must } from "../../../shared/src/must.js";
|
|
3
|
+
import { assignProperty } from "../../../shared/src/objects.js";
|
|
3
4
|
import { skipYields } from "./skip-yields.js";
|
|
4
5
|
import "./data.js";
|
|
5
6
|
//#region ../zql/src/ivm/view-apply-change.ts
|
|
@@ -354,7 +355,7 @@ function arrayWith(mutate, array, index, value) {
|
|
|
354
355
|
}
|
|
355
356
|
function setProperty(mutate, parentEntry, key, value) {
|
|
356
357
|
if (mutate || owns(parentEntry)) {
|
|
357
|
-
parentEntry
|
|
358
|
+
assignProperty(parentEntry, key, value);
|
|
358
359
|
return parentEntry;
|
|
359
360
|
}
|
|
360
361
|
return track({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-apply-change.js","names":[],"sources":["../../../../../zql/src/ivm/view-apply-change.ts"],"sourcesContent":["import {\n assert,\n assertArray,\n assertNumber,\n unreachable,\n} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Writable} from '../../../shared/src/writable.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport {type Comparator, type Node} from './data.ts';\nimport {skipYields} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Entry, Format} from './view.ts';\n\nexport const refCountSymbol = Symbol('rc');\nexport const idSymbol = Symbol('id');\n\ntype ReadonlyMetaEntry = Entry & {\n readonly [refCountSymbol]: number;\n readonly [idSymbol]?: string | undefined;\n};\n\ntype MutableMetaEntry = Writable<ReadonlyMetaEntry>;\n\n/**\n * MetaEntry is an Entry with internal tracking fields for reference counting\n * and stable identity. All entries in the view tree are MetaEntry instances,\n * created through makeNewMetaEntry().\n */\ntype MetaEntry<M extends Mutate> = M extends true\n ? MutableMetaEntry\n : ReadonlyMetaEntry;\n\ntype MutableArray<M extends Mutate, T> = M extends true ? T[] : readonly T[];\n\ntype MetaEntryList<M extends Mutate> = MutableArray<M, MetaEntry<M>>;\n\ntype MutableMetaEntryList = MutableMetaEntry[];\n\n/**\n * Node with eagerly-expanded relationships (arrays instead of generators).\n * Used when batching changes to capture source state at push time.\n */\nexport type ExpandedNode = {\n row: Row;\n relationships: Record<string, ExpandedNode[]>;\n};\n\n/**\n * A node for view changes. Can be either:\n * - A lazy Node with generator relationships (original behavior)\n * - An ExpandedNode with pre-computed relationship arrays (for batching)\n */\nexport type ViewNode = Node | ExpandedNode;\n\n/**\n * `applyChange` does not consume the `relationships` of `ChildChange#node`,\n * `EditChange#node` and `EditChange#oldNode`. The `ViewChange` type\n * documents and enforces this via the type system.\n */\nexport type ViewChange =\n | AddViewChange\n | RemoveViewChange\n | ChildViewChange\n | EditViewChange;\n\nexport type RowOnlyNode = {row: Row};\n\nexport type AddViewChange = {\n type: 'add';\n node: ViewNode;\n};\n\nexport type RemoveViewChange = {\n type: 'remove';\n node: ViewNode;\n};\n\ntype ChildViewChange = {\n type: 'child';\n node: RowOnlyNode;\n child: {\n relationshipName: string;\n change: ViewChange;\n };\n};\n\ntype EditViewChange = {\n type: 'edit';\n node: RowOnlyNode;\n oldNode: RowOnlyNode;\n};\n\n/**\n * This is a subset of WeakMap but restricted to what we need.\n * @deprecated Not used anymore. This will be removed in the future.\n */\nexport interface RefCountMap {\n get(entry: Entry): number | undefined;\n set(entry: Entry, refCount: number): void;\n delete(entry: Entry): boolean;\n}\n\n/**\n * Get child nodes from a relationship, handling both lazy (Node) and expanded (ExpandedNode).\n */\nfunction* getChildNodes(\n node: ViewNode,\n relationship: string,\n): Generator<ViewNode> {\n const children = node.relationships[relationship];\n if (Array.isArray(children)) {\n // ExpandedNode: already an array\n yield* children;\n } else {\n // Node: lazy generator function\n yield* skipYields(children());\n }\n}\n\ntype Mutate = boolean;\ntype WithIDs = boolean;\n\n/**\n * Transaction-scoped copy-on-write.\n *\n * `applyChange` is immutable: it path-copies a new spine on every call so the\n * previously-emitted snapshot is never mutated. But within a single transaction\n * (a run of `push()` calls before `flush()`) only the final state is ever\n * observed by a listener, so the intermediate spines are pure allocation/GC\n * churn — making a K-change transaction O(K * spineSize).\n *\n * When the caller passes a WeakSet as the `mutate` argument, objects and arrays\n * that were created or cloned during the current transaction are recorded in it.\n * A helper that needs to modify such an object mutates it in place (it is not\n * yet observed) instead of cloning again. The first touch of a node still\n * copies-on-write (preserving the committed snapshot's references); subsequent\n * touches in the same transaction are in-place. This brings a K-change\n * transaction to O(spineSize + K) while keeping cross-transaction reference\n * stability.\n *\n * The set is module-scoped for the duration of a single (synchronous,\n * non-re-entrant) `applyChange` call and saved/restored around it.\n *\n * It is a WeakSet on purpose: it must not keep transiently-cloned arrays/entries\n * alive. A strong Set would extend their lifetime to the end of the transaction,\n * pushing large clones out of the young generation and adding GC pressure that\n * shows up as a regression on single-change transactions over wide lists. A\n * WeakSet gives the same identity test (\"created this transaction?\") while\n * letting dead clones be collected as cheaply as in the plain immutable path.\n */\nlet activeDirty: WeakSet<object> | undefined;\n\n/** True if `o` was created/cloned during the current transaction. */\nfunction owns(o: object): boolean {\n return activeDirty !== undefined && activeDirty.has(o);\n}\n\n/** Record `o` as owned by the current transaction (no-op outside a txn). */\nfunction track<T extends object>(o: T): T {\n activeDirty?.add(o);\n return o;\n}\n\n/**\n * Immutable view update. Returns new Entry on change, same Entry if unchanged.\n * Unchanged entries keep identity, enabling shallow comparison optimizations\n * in UI frameworks (React.memo, Solid's fine-grained reactivity, etc).\n *\n * Propagation: recurse DOWN to find target, copy objects on the way UP.\n * Siblings keep original refs. Only the ancestor path is copied.\n *\n * root {users:[A,B], items:[C,D,E]} --edit C--> root' {users:[A,B], items':[C',D,E]}\n * │ same ref │ │ │\n * └─────────────────┴── unchanged ──────────────┘ new array C' new, D/E same\n *\n * `mutate` selects the update strategy:\n * - `false` (default): fully immutable; every changed node is path-copied.\n * - `true`: mutate the tree in place (only safe when it is not yet observed,\n * e.g. during initial hydration).\n * - a `WeakSet`: transaction-scoped copy-on-write — copy on first touch, then\n * mutate in place for the rest of the transaction. See `activeDirty` above.\n */\nexport function applyChange(\n parentEntry: Entry,\n change: ViewChange,\n schema: SourceSchema,\n relationship: string,\n format: Format,\n withIDs = false,\n mutate: boolean | WeakSet<object> = false,\n): Entry {\n // A WeakSet selects copy-on-write; a boolean selects full mutate / immutable.\n const inPlace = mutate === true;\n const prevDirty = activeDirty;\n activeDirty = typeof mutate === 'object' ? mutate : undefined;\n try {\n return applyChangeInternal(\n parentEntry as MetaEntry<typeof inPlace>,\n change,\n schema,\n relationship,\n format,\n withIDs,\n inPlace,\n );\n } finally {\n activeDirty = prevDirty;\n }\n}\n\nexport function applyChangeInternal<M extends Mutate>(\n parentEntry: MetaEntry<M>,\n change: ViewChange,\n schema: SourceSchema,\n relationship: string,\n format: Format,\n withIDs: WithIDs,\n mutate: M,\n): MetaEntry<M> {\n if (schema.isHidden) {\n switch (change.type) {\n case 'add':\n case 'remove': {\n let currentParent = parentEntry;\n for (const relationship of Object.keys(change.node.relationships)) {\n const childSchema = must(schema.relationships[relationship]);\n for (const node of getChildNodes(change.node, relationship)) {\n currentParent = applyChangeInternal(\n currentParent,\n {type: change.type, node},\n childSchema,\n relationship,\n format,\n withIDs,\n mutate,\n );\n }\n }\n return currentParent;\n }\n case 'edit':\n // If hidden at this level it means that the hidden row was changed. If\n // the row was changed in such a way that it would change the\n // relationships then the edit would have been split into remove and\n // add.\n return parentEntry;\n case 'child': {\n const childSchema = must(\n schema.relationships[change.child.relationshipName],\n );\n return applyChangeInternal(\n parentEntry,\n change.child.change,\n childSchema,\n relationship,\n format,\n withIDs,\n mutate,\n );\n }\n default:\n unreachable(change);\n }\n }\n\n const {singular, relationships: childFormats} = format;\n switch (change.type) {\n // ADD: Insert row (rc=1) or increment refCount if duplicate.\n // RefCount tracks when the same row is reachable via multiple edges\n // within a relationship:\n //\n // issue.labels: [L1, L2] both point to same creator\n // │ │ │\n // ▼ ▼ ▼\n // label.creator ──────────► [User:rc=2] (one row, two refs)\n //\n // add(A) add(A) remove(A) remove(A)\n // ↓ ↓ ↓ ↓\n // [A:rc=1] → [A:rc=2] → [A:rc=1] → (deleted)\n case 'add': {\n if (singular) {\n const oldEntry = getOptionalSingularEntry(parentEntry, relationship);\n if (oldEntry !== undefined) {\n // Duplicate add: increment refCount\n assert(\n schema.compareRows(oldEntry, change.node.row) === 0,\n `Singular relationship '${relationship}' should not have multiple rows. You may need to declare this relationship with the \\`many\\` helper instead of the \\`one\\` helper in your schema.`,\n );\n\n const newEntry = incRefCount(mutate, oldEntry);\n return setRelation(mutate, parentEntry, relationship, newEntry);\n } else {\n // New row: create with rc=1, initialize nested relationships\n const newEntry = makeNewMetaEntry(\n change.node.row,\n schema,\n withIDs,\n 1,\n );\n initializeRelationshipsForNewEntryIfAny(\n newEntry,\n change.node,\n schema,\n childFormats,\n withIDs,\n );\n return setRelation(mutate, parentEntry, relationship, newEntry);\n }\n } else {\n // Plural: binary search for position, insert or increment refCount\n const view = getChildEntryList(parentEntry, relationship);\n const {newEntry, newView} = add(\n change.node.row,\n view,\n schema,\n withIDs,\n mutate,\n );\n\n if (newEntry) {\n initializeRelationshipsForNewEntryIfAny(\n newEntry,\n change.node,\n schema,\n childFormats,\n withIDs,\n );\n }\n return setRelation(mutate, parentEntry, relationship, newView);\n }\n }\n // REMOVE: Decrement refCount, physically remove when rc=0.\n case 'remove': {\n if (singular) {\n const oldEntry = getSingularEntry(parentEntry, relationship);\n const rc = oldEntry[refCountSymbol];\n if (rc === 1) {\n return setRelation(mutate, parentEntry, relationship, undefined);\n }\n const newEntry = decRefCount(mutate, oldEntry);\n return setRelation(mutate, parentEntry, relationship, newEntry);\n } else {\n const view = getChildEntryList(parentEntry, relationship);\n const newView = removeAndUpdateRefCount(\n view,\n change.node.row,\n schema.compareRows,\n mutate,\n );\n return setRelation(mutate, parentEntry, relationship, newView);\n }\n }\n // CHILD: Propagate nested change up to this level (leaf-to-root pattern).\n case 'child': {\n const childSchema = must(\n schema.relationships[change.child.relationshipName],\n );\n const childFormat = format.relationships[change.child.relationshipName];\n if (childFormat === undefined) {\n return parentEntry; // Relationship not in view format\n }\n\n if (singular) {\n const existing = getSingularEntry(parentEntry, relationship);\n const newExisting = applyChangeInternal(\n existing,\n change.child.change,\n childSchema,\n change.child.relationshipName,\n childFormat,\n withIDs,\n mutate,\n );\n // Preserve identity if child didn't change (enables shallow-compare optimizations).\n if (newExisting === existing) {\n return parentEntry;\n }\n return setRelation(mutate, parentEntry, relationship, newExisting);\n } else {\n // Find the target row in the sorted array via binary search.\n const view = getChildEntryList(parentEntry, relationship);\n const pos = binarySearch(view, change.node.row, schema.compareRows);\n assert(pos >= 0, 'node does not exist');\n const existing = view[pos];\n const newExisting = applyChangeInternal(\n existing,\n change.child.change,\n childSchema,\n change.child.relationshipName,\n childFormat,\n withIDs,\n mutate,\n );\n // Preserve identity if descendant didn't change.\n if (newExisting === existing) {\n return parentEntry;\n }\n // applyChangeInternal preserves MetaEntry structure when input is MetaEntry\n assertMetaEntry(newExisting);\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n arrayWith(mutate, view, pos, newExisting),\n );\n }\n }\n // EDIT: Update row fields. If sort key changes, row may move position.\n //\n // Position change with rc>1 (two query paths reach same row):\n //\n // Before: [A, B(rc=2), C, D] After: [A, B(rc=1), C, B'(rc=1), D]\n // │ │ │\n // path1 + path2 path1 ghost path2 moved\n //\n // Why ghost stays: path1 still expects B at old position.\n // B' appears where path2's sort order places it.\n case 'edit': {\n if (singular) {\n const existing = getSingularEntry(parentEntry, relationship);\n const newEntry = applyEdit(existing, change, schema, withIDs, mutate);\n return setRelation(mutate, parentEntry, relationship, newEntry);\n } else {\n const view = getChildEntryList(parentEntry, relationship);\n // Sort key changed: row may need to move\n if (schema.compareRows(change.oldNode.row, change.node.row) !== 0) {\n const oldPos = binarySearch(\n view,\n change.oldNode.row,\n schema.compareRows,\n );\n assert(oldPos >= 0, 'old node does not exist');\n const oldEntry = view[oldPos];\n const rawPos = binarySearch(\n view,\n change.node.row,\n schema.compareRows,\n );\n const found = rawPos >= 0;\n const pos = found ? rawPos : ~rawPos;\n // A special case:\n // when refCount is 1 (so the row is being moved without leaving a\n // placeholder behind), and the new pos is the same as the old, or\n // directly after the old (so after the remove of the old it would be\n // in the same pos): the row does not need to be moved, just edited.\n if (\n oldEntry[refCountSymbol] === 1 &&\n (pos === oldPos || pos - 1 === oldPos)\n ) {\n const newEntry = applyEdit(\n oldEntry,\n change,\n schema,\n withIDs,\n mutate,\n );\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n arrayWith(mutate, view, oldPos, newEntry),\n );\n } else {\n // Move the row. If rc > 1, an edit will be received for each ref.\n // On first edit: move row, apply edit, set rc=1. Leave a copy at\n // old pos with decremented rc. As each edit arrives, old copy's rc\n // decrements and new pos rc increments. When copy rc hits 0, remove.\n const newRefCount = oldEntry[refCountSymbol] - 1;\n let newView: MutableMetaEntryList;\n let adjustedPos = pos;\n\n if (newRefCount === 0) {\n newView = removeAt(mutate, view, oldPos);\n adjustedPos = oldPos < pos ? pos - 1 : pos;\n } else {\n const oldEntryCopy = setRefCount(mutate, oldEntry, newRefCount);\n newView = arrayWith(mutate, view, oldPos, oldEntryCopy);\n }\n\n if (found) {\n // Merge with existing at new pos\n const existingEntry = newView[adjustedPos];\n const editedEntry = applyEdit(\n existingEntry,\n change,\n schema,\n withIDs,\n mutate,\n );\n const updatedEntry = setRefCount(\n mutate,\n editedEntry,\n existingEntry[refCountSymbol] + 1,\n );\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n arrayWith(mutate, newView, adjustedPos, updatedEntry),\n );\n } else {\n // Insert at new pos with rc=1\n const editedEntry = applyEdit(\n oldEntry,\n change,\n schema,\n withIDs,\n mutate,\n );\n const movedEntry = setRefCount(mutate, editedEntry, 1);\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n insertAt(mutate, newView, adjustedPos, movedEntry),\n );\n }\n }\n } else {\n // Sort key unchanged: edit in place\n const pos = binarySearch(\n view,\n change.oldNode.row,\n schema.compareRows,\n );\n assert(pos >= 0, 'node does not exist');\n const newEntry = applyEdit(\n view[pos],\n change,\n schema,\n withIDs,\n mutate,\n );\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n arrayWith(mutate, view, pos, newEntry),\n );\n }\n }\n }\n default:\n unreachable(change);\n }\n}\n\n/**\n * Batch apply multiple changes to an Entry tree.\n * For small batches or complex cases, falls back to sequential applyChange.\n * Future optimization: O(N + K) batch processing for large K.\n */\nexport function applyChanges(\n parentEntry: Entry,\n changes: ViewChange[],\n schema: SourceSchema,\n relationship: string,\n format: Format,\n withIDs: WithIDs = false,\n mutate: Mutate = false,\n): Entry {\n let result = parentEntry;\n for (const change of changes) {\n result = applyChange(\n result,\n change,\n schema,\n relationship,\n format,\n withIDs,\n mutate,\n );\n }\n return result;\n}\n\nfunction applyEdit<M extends Mutate>(\n existing: MetaEntry<M>,\n change: EditViewChange,\n schema: SourceSchema,\n withIDs: WithIDs,\n mutate: Mutate,\n): MetaEntry<M> {\n // In-place edit is safe when fully mutating or when `existing` was already\n // created/cloned in this transaction (copy-on-write). A primary-key change\n // always needs a fresh entry so identity tracks the new key.\n const canMutate = mutate || owns(existing);\n const newEntry: MutableMetaEntry =\n canMutate && schema.compareRows(change.oldNode.row, change.node.row) === 0\n ? Object.assign(existing, change.node.row)\n : track({...existing, ...change.node.row});\n\n if (withIDs) {\n return setProperty(\n mutate,\n newEntry,\n idSymbol,\n makeID(change.node.row, schema),\n );\n }\n return newEntry;\n}\n\n/**\n * Initialize child relationships on a newly-added entry by mutating it in place.\n *\n * New nodes don't exist in the view yet, so we can build in-place (no refs to preserve):\n *\n * New nodes don't exist in the view yet, so we can build in-place (no refs to preserve):\n *\n * Existing node edit (must path-copy): New node (can build in-place):\n *\n * view: [A, B, C] view: [A, B, _]\n * │ │\n * edit C.child add C with children\n * │ │\n * ▼ ▼\n * view': [A, B, C'] ◄─ path-copy view': [A, B, C{children:[...]}]\n * up the tree └─ built in-place\n *\n * Hidden schemas still use applyChange to collapse junction levels.\n */\nfunction initializeRelationshipsForNewEntryIfAny(\n entry: MutableMetaEntry,\n node: ViewNode,\n schema: SourceSchema,\n childFormats: Record<string, Format>,\n withIDs: WithIDs,\n): void {\n let result = entry;\n for (const relationship of Object.keys(node.relationships)) {\n const childSchema = must(schema.relationships[relationship]);\n const childFormat = childFormats[relationship];\n if (childFormat === undefined) {\n continue;\n }\n\n // Hidden/singular: use applyChange to handle properly\n if (childSchema.isHidden || childFormat.singular) {\n const newView = childFormat.singular\n ? undefined\n : track([] as MutableMetaEntryList);\n result[relationship] = newView;\n\n for (const childNode of getChildNodes(node, relationship)) {\n applyChangeInternal(\n result,\n {type: 'add', node: childNode},\n childSchema,\n relationship,\n childFormat,\n withIDs,\n true, // this is a new entry, so we can mutate\n );\n }\n } else {\n // Plural non-hidden: build array in-place for efficiency\n const childArray: MutableMetaEntryList = track([]);\n\n for (const childNode of getChildNodes(node, relationship)) {\n const newEntry = makeNewMetaEntry(\n childNode.row,\n childSchema,\n withIDs,\n 1,\n );\n const rawPos = binarySearch(\n childArray,\n childNode.row,\n childSchema.compareRows,\n );\n\n if (rawPos >= 0) {\n childArray[rawPos][refCountSymbol]++;\n } else {\n childArray.splice(~rawPos, 0, newEntry);\n initializeRelationshipsForNewEntryIfAny(\n newEntry,\n childNode,\n childSchema,\n childFormat.relationships,\n withIDs,\n );\n }\n }\n\n result[relationship] = childArray;\n }\n }\n}\n\nfunction add<M extends Mutate>(\n row: Row,\n view: MetaEntryList<M>,\n schema: SourceSchema,\n withIDs: WithIDs,\n mutate: M,\n): {\n newEntry: MutableMetaEntry | undefined;\n newView: MutableMetaEntryList;\n} {\n const rawPos = binarySearch(view, row, schema.compareRows);\n\n if (rawPos >= 0) {\n const existing = view[rawPos];\n\n const updated = incRefCount(mutate, existing);\n return {\n newEntry: undefined,\n newView: arrayWith(mutate, view, rawPos, updated),\n };\n }\n const newEntry = makeNewMetaEntry(row, schema, withIDs, 1);\n return {newEntry, newView: insertAt(mutate, view, ~rawPos, newEntry)};\n}\n\nfunction insertAt<M extends Mutate, T>(\n mutate: M,\n array: MutableArray<M, T>,\n index: number,\n item: T,\n): T[] {\n if (mutate || owns(array)) {\n (array as T[]).splice(index, 0, item);\n return array as T[];\n }\n return track(array.toSpliced(index, 0, item));\n}\n\nfunction removeAt<M extends Mutate, T>(\n mutate: M,\n array: MutableArray<M, T>,\n index: number,\n): T[] {\n if (mutate || owns(array)) {\n (array as T[]).splice(index, 1);\n return array as T[];\n }\n return track(array.toSpliced(index, 1));\n}\n\nfunction removeAndUpdateRefCount<M extends Mutate>(\n view: MetaEntryList<M>,\n row: Row,\n compareRows: Comparator,\n mutate: M,\n): MutableMetaEntryList {\n const pos = binarySearch(view, row, compareRows);\n assert(pos >= 0, 'node does not exist');\n const oldEntry = view[pos];\n const rc = oldEntry[refCountSymbol];\n if (rc === 1) {\n return removeAt(mutate, view, pos);\n }\n const newEntry = decRefCount(mutate, oldEntry);\n return arrayWith(mutate, view, pos, newEntry);\n}\n\n/**\n * Binary search returning a number.\n * - If found at index `i`: returns `i` (>= 0).\n * - If not found, insertion point is `low`: returns `~low` (< 0).\n * Recover insertion point with `~result`.\n */\nfunction binarySearch(\n view: MetaEntryList<Mutate>,\n target: Row,\n comparator: Comparator,\n): number {\n let low = 0;\n let high = view.length - 1;\n while (low <= high) {\n const mid = (low + high) >>> 1;\n // MetaEntry has all Row props; comparator only reads string keys\n const comparison = comparator(view[mid] as Row, target);\n if (comparison < 0) {\n low = mid + 1;\n } else if (comparison > 0) {\n high = mid - 1;\n } else {\n return mid;\n }\n }\n return ~low;\n}\n\n/** Assert value is MetaEntry (has refCountSymbol). */\nfunction assertMetaEntry<M extends Mutate>(\n v: unknown,\n): asserts v is MetaEntry<M> {\n assertNumber((v as Partial<MetaEntry<M>>)[refCountSymbol]);\n}\n\n/** Get singular MetaEntry, throws if missing. */\nfunction getSingularEntry<M extends Mutate>(\n parentEntry: MetaEntry<M>,\n relationship: string,\n): MetaEntry<M> {\n const entry = parentEntry[relationship];\n assert(entry !== undefined, 'node does not exist');\n assertMetaEntry(entry);\n return entry;\n}\n\n/** Get singular MetaEntry or undefined if not set. */\nfunction getOptionalSingularEntry<M extends Mutate>(\n parentEntry: MetaEntry<M>,\n relationship: string,\n): MetaEntry<M> | undefined {\n const entry = parentEntry[relationship];\n if (entry === undefined) {\n return undefined;\n }\n assertMetaEntry(entry);\n return entry;\n}\n\n/** Get child array as MetaEntryList. */\nfunction getChildEntryList<M extends Mutate>(\n parentEntry: MetaEntry<M>,\n relationship: string,\n): MetaEntryList<M> {\n const view = parentEntry[relationship];\n assertArray(view);\n return view as MetaEntryList<M>;\n}\n\n/** Create MetaEntry from row with given refCount. */\nfunction makeNewMetaEntry(\n row: Row,\n schema: SourceSchema,\n withIDs: WithIDs,\n rc: number,\n): MutableMetaEntry {\n // This creates a new MetaEntry from a Row. We never mutate Rows.\n if (withIDs) {\n return track({\n ...row,\n [refCountSymbol]: rc,\n [idSymbol]: makeID(row, schema),\n });\n }\n return track({...row, [refCountSymbol]: rc});\n}\n\nfunction makeID(row: Row, schema: SourceSchema) {\n // optimization for case of non-compound primary key\n if (schema.primaryKey.length === 1) {\n return JSON.stringify(row[schema.primaryKey[0]]);\n }\n return JSON.stringify(schema.primaryKey.map(k => row[k]));\n}\n\nfunction incRefCount<M extends Mutate>(\n mutate: M,\n entry: MetaEntry<M>,\n): MutableMetaEntry {\n return setRefCount(mutate, entry, entry[refCountSymbol] + 1);\n}\n\nfunction decRefCount<M extends Mutate>(\n mutate: M,\n entry: MetaEntry<M>,\n): MutableMetaEntry {\n return setRefCount(mutate, entry, entry[refCountSymbol] - 1);\n}\n\nfunction setRefCount<M extends Mutate>(\n mutate: M,\n entry: MetaEntry<M>,\n count: number,\n): MutableMetaEntry {\n if (mutate || owns(entry)) {\n (entry as MutableMetaEntry)[refCountSymbol] = count;\n return entry;\n }\n return track({...entry, [refCountSymbol]: count});\n}\n\nfunction arrayWith<M extends Mutate, T>(\n mutate: M,\n array: MutableArray<M, T>,\n index: number,\n value: T,\n): T[] {\n if (mutate || owns(array)) {\n (array as T[])[index] = value;\n return array as T[];\n }\n return track(array.with(index, value));\n}\n\nfunction setProperty<\n M extends Mutate,\n K extends string | keyof MetaEntry<M>,\n V,\n>(\n mutate: M,\n parentEntry: MetaEntry<M>,\n key: K,\n value: V,\n): MutableMetaEntry & {[P in K]: V} {\n if (mutate || owns(parentEntry)) {\n (parentEntry as {[P in K]: V})[key] = value;\n return parentEntry as MutableMetaEntry & {[P in K]: V};\n }\n return track({...parentEntry, [key]: value});\n}\n\nconst setRelation: <M extends Mutate>(\n mutate: M,\n parentEntry: MetaEntry<M>,\n relationship: string,\n value: Entry | Entry[] | undefined,\n) => MutableMetaEntry = setProperty;\n"],"mappings":";;;;;AAcA,IAAa,iBAAiB,OAAO,IAAI;AACzC,IAAa,WAAW,OAAO,IAAI;;;;AA2FnC,UAAU,cACR,MACA,cACqB;CACrB,MAAM,WAAW,KAAK,cAAc;CACpC,IAAI,MAAM,QAAQ,QAAQ,GAExB,OAAO;MAGP,OAAO,WAAW,SAAS,CAAC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAI;;AAGJ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,GAC/B,OAAO,KAAK,UAAU,IAAI,OAAO,WAAW,GAAG;CAEjD,OAAO,KAAK,UAAU,OAAO,WAAW,KAAI,MAAK,IAAI,EAAE,CAAC;AAC1D;AAEA,SAAS,YACP,QACA,OACkB;CAClB,OAAO,YAAY,QAAQ,OAAO,MAAM,kBAAkB,CAAC;AAC7D;AAEA,SAAS,YACP,QACA,OACkB;CAClB,OAAO,YAAY,QAAQ,OAAO,MAAM,kBAAkB,CAAC;AAC7D;AAEA,SAAS,YACP,QACA,OACA,OACkB;CAClB,IAAI,UAAU,KAAK,KAAK,GAAG;EACzB,MAA4B,kBAAkB;EAC9C,OAAO;CACT;CACA,OAAO,MAAM;EAAC,GAAG;GAAQ,iBAAiB;CAAK,CAAC;AAClD;AAEA,SAAS,UACP,QACA,OACA,OACA,OACK;CACL,IAAI,UAAU,KAAK,KAAK,GAAG;EACzB,MAAe,SAAS;EACxB,OAAO;CACT;CACA,OAAO,MAAM,MAAM,KAAK,OAAO,KAAK,CAAC;AACvC;AAEA,SAAS,YAKP,QACA,aACA,KACA,OACkC;CAClC,IAAI,UAAU,KAAK,WAAW,GAAG;EAC/B,YAA+B,OAAO;EACtC,OAAO;CACT;CACA,OAAO,MAAM;EAAC,GAAG;GAAc,MAAM;CAAK,CAAC;AAC7C;AAEA,IAAM,cAKkB"}
|
|
1
|
+
{"version":3,"file":"view-apply-change.js","names":[],"sources":["../../../../../zql/src/ivm/view-apply-change.ts"],"sourcesContent":["import {\n assert,\n assertArray,\n assertNumber,\n unreachable,\n} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {assignProperty} from '../../../shared/src/objects.ts';\nimport type {Writable} from '../../../shared/src/writable.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport {type Comparator, type Node} from './data.ts';\nimport {skipYields} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Entry, Format} from './view.ts';\n\nexport const refCountSymbol = Symbol('rc');\nexport const idSymbol = Symbol('id');\n\ntype ReadonlyMetaEntry = Entry & {\n readonly [refCountSymbol]: number;\n readonly [idSymbol]?: string | undefined;\n};\n\ntype MutableMetaEntry = Writable<ReadonlyMetaEntry>;\n\n/**\n * MetaEntry is an Entry with internal tracking fields for reference counting\n * and stable identity. All entries in the view tree are MetaEntry instances,\n * created through makeNewMetaEntry().\n */\ntype MetaEntry<M extends Mutate> = M extends true\n ? MutableMetaEntry\n : ReadonlyMetaEntry;\n\ntype MutableArray<M extends Mutate, T> = M extends true ? T[] : readonly T[];\n\ntype MetaEntryList<M extends Mutate> = MutableArray<M, MetaEntry<M>>;\n\ntype MutableMetaEntryList = MutableMetaEntry[];\n\n/**\n * Node with eagerly-expanded relationships (arrays instead of generators).\n * Used when batching changes to capture source state at push time.\n */\nexport type ExpandedNode = {\n row: Row;\n relationships: Record<string, ExpandedNode[]>;\n};\n\n/**\n * A node for view changes. Can be either:\n * - A lazy Node with generator relationships (original behavior)\n * - An ExpandedNode with pre-computed relationship arrays (for batching)\n */\nexport type ViewNode = Node | ExpandedNode;\n\n/**\n * `applyChange` does not consume the `relationships` of `ChildChange#node`,\n * `EditChange#node` and `EditChange#oldNode`. The `ViewChange` type\n * documents and enforces this via the type system.\n */\nexport type ViewChange =\n | AddViewChange\n | RemoveViewChange\n | ChildViewChange\n | EditViewChange;\n\nexport type RowOnlyNode = {row: Row};\n\nexport type AddViewChange = {\n type: 'add';\n node: ViewNode;\n};\n\nexport type RemoveViewChange = {\n type: 'remove';\n node: ViewNode;\n};\n\ntype ChildViewChange = {\n type: 'child';\n node: RowOnlyNode;\n child: {\n relationshipName: string;\n change: ViewChange;\n };\n};\n\ntype EditViewChange = {\n type: 'edit';\n node: RowOnlyNode;\n oldNode: RowOnlyNode;\n};\n\n/**\n * This is a subset of WeakMap but restricted to what we need.\n * @deprecated Not used anymore. This will be removed in the future.\n */\nexport interface RefCountMap {\n get(entry: Entry): number | undefined;\n set(entry: Entry, refCount: number): void;\n delete(entry: Entry): boolean;\n}\n\n/**\n * Get child nodes from a relationship, handling both lazy (Node) and expanded (ExpandedNode).\n */\nfunction* getChildNodes(\n node: ViewNode,\n relationship: string,\n): Generator<ViewNode> {\n const children = node.relationships[relationship];\n if (Array.isArray(children)) {\n // ExpandedNode: already an array\n yield* children;\n } else {\n // Node: lazy generator function\n yield* skipYields(children());\n }\n}\n\ntype Mutate = boolean;\ntype WithIDs = boolean;\n\n/**\n * Transaction-scoped copy-on-write.\n *\n * `applyChange` is immutable: it path-copies a new spine on every call so the\n * previously-emitted snapshot is never mutated. But within a single transaction\n * (a run of `push()` calls before `flush()`) only the final state is ever\n * observed by a listener, so the intermediate spines are pure allocation/GC\n * churn — making a K-change transaction O(K * spineSize).\n *\n * When the caller passes a WeakSet as the `mutate` argument, objects and arrays\n * that were created or cloned during the current transaction are recorded in it.\n * A helper that needs to modify such an object mutates it in place (it is not\n * yet observed) instead of cloning again. The first touch of a node still\n * copies-on-write (preserving the committed snapshot's references); subsequent\n * touches in the same transaction are in-place. This brings a K-change\n * transaction to O(spineSize + K) while keeping cross-transaction reference\n * stability.\n *\n * The set is module-scoped for the duration of a single (synchronous,\n * non-re-entrant) `applyChange` call and saved/restored around it.\n *\n * It is a WeakSet on purpose: it must not keep transiently-cloned arrays/entries\n * alive. A strong Set would extend their lifetime to the end of the transaction,\n * pushing large clones out of the young generation and adding GC pressure that\n * shows up as a regression on single-change transactions over wide lists. A\n * WeakSet gives the same identity test (\"created this transaction?\") while\n * letting dead clones be collected as cheaply as in the plain immutable path.\n */\nlet activeDirty: WeakSet<object> | undefined;\n\n/** True if `o` was created/cloned during the current transaction. */\nfunction owns(o: object): boolean {\n return activeDirty !== undefined && activeDirty.has(o);\n}\n\n/** Record `o` as owned by the current transaction (no-op outside a txn). */\nfunction track<T extends object>(o: T): T {\n activeDirty?.add(o);\n return o;\n}\n\n/**\n * Immutable view update. Returns new Entry on change, same Entry if unchanged.\n * Unchanged entries keep identity, enabling shallow comparison optimizations\n * in UI frameworks (React.memo, Solid's fine-grained reactivity, etc).\n *\n * Propagation: recurse DOWN to find target, copy objects on the way UP.\n * Siblings keep original refs. Only the ancestor path is copied.\n *\n * root {users:[A,B], items:[C,D,E]} --edit C--> root' {users:[A,B], items':[C',D,E]}\n * │ same ref │ │ │\n * └─────────────────┴── unchanged ──────────────┘ new array C' new, D/E same\n *\n * `mutate` selects the update strategy:\n * - `false` (default): fully immutable; every changed node is path-copied.\n * - `true`: mutate the tree in place (only safe when it is not yet observed,\n * e.g. during initial hydration).\n * - a `WeakSet`: transaction-scoped copy-on-write — copy on first touch, then\n * mutate in place for the rest of the transaction. See `activeDirty` above.\n */\nexport function applyChange(\n parentEntry: Entry,\n change: ViewChange,\n schema: SourceSchema,\n relationship: string,\n format: Format,\n withIDs = false,\n mutate: boolean | WeakSet<object> = false,\n): Entry {\n // A WeakSet selects copy-on-write; a boolean selects full mutate / immutable.\n const inPlace = mutate === true;\n const prevDirty = activeDirty;\n activeDirty = typeof mutate === 'object' ? mutate : undefined;\n try {\n return applyChangeInternal(\n parentEntry as MetaEntry<typeof inPlace>,\n change,\n schema,\n relationship,\n format,\n withIDs,\n inPlace,\n );\n } finally {\n activeDirty = prevDirty;\n }\n}\n\nexport function applyChangeInternal<M extends Mutate>(\n parentEntry: MetaEntry<M>,\n change: ViewChange,\n schema: SourceSchema,\n relationship: string,\n format: Format,\n withIDs: WithIDs,\n mutate: M,\n): MetaEntry<M> {\n if (schema.isHidden) {\n switch (change.type) {\n case 'add':\n case 'remove': {\n let currentParent = parentEntry;\n for (const relationship of Object.keys(change.node.relationships)) {\n const childSchema = must(schema.relationships[relationship]);\n for (const node of getChildNodes(change.node, relationship)) {\n currentParent = applyChangeInternal(\n currentParent,\n {type: change.type, node},\n childSchema,\n relationship,\n format,\n withIDs,\n mutate,\n );\n }\n }\n return currentParent;\n }\n case 'edit':\n // If hidden at this level it means that the hidden row was changed. If\n // the row was changed in such a way that it would change the\n // relationships then the edit would have been split into remove and\n // add.\n return parentEntry;\n case 'child': {\n const childSchema = must(\n schema.relationships[change.child.relationshipName],\n );\n return applyChangeInternal(\n parentEntry,\n change.child.change,\n childSchema,\n relationship,\n format,\n withIDs,\n mutate,\n );\n }\n default:\n unreachable(change);\n }\n }\n\n const {singular, relationships: childFormats} = format;\n switch (change.type) {\n // ADD: Insert row (rc=1) or increment refCount if duplicate.\n // RefCount tracks when the same row is reachable via multiple edges\n // within a relationship:\n //\n // issue.labels: [L1, L2] both point to same creator\n // │ │ │\n // ▼ ▼ ▼\n // label.creator ──────────► [User:rc=2] (one row, two refs)\n //\n // add(A) add(A) remove(A) remove(A)\n // ↓ ↓ ↓ ↓\n // [A:rc=1] → [A:rc=2] → [A:rc=1] → (deleted)\n case 'add': {\n if (singular) {\n const oldEntry = getOptionalSingularEntry(parentEntry, relationship);\n if (oldEntry !== undefined) {\n // Duplicate add: increment refCount\n assert(\n schema.compareRows(oldEntry, change.node.row) === 0,\n `Singular relationship '${relationship}' should not have multiple rows. You may need to declare this relationship with the \\`many\\` helper instead of the \\`one\\` helper in your schema.`,\n );\n\n const newEntry = incRefCount(mutate, oldEntry);\n return setRelation(mutate, parentEntry, relationship, newEntry);\n } else {\n // New row: create with rc=1, initialize nested relationships\n const newEntry = makeNewMetaEntry(\n change.node.row,\n schema,\n withIDs,\n 1,\n );\n initializeRelationshipsForNewEntryIfAny(\n newEntry,\n change.node,\n schema,\n childFormats,\n withIDs,\n );\n return setRelation(mutate, parentEntry, relationship, newEntry);\n }\n } else {\n // Plural: binary search for position, insert or increment refCount\n const view = getChildEntryList(parentEntry, relationship);\n const {newEntry, newView} = add(\n change.node.row,\n view,\n schema,\n withIDs,\n mutate,\n );\n\n if (newEntry) {\n initializeRelationshipsForNewEntryIfAny(\n newEntry,\n change.node,\n schema,\n childFormats,\n withIDs,\n );\n }\n return setRelation(mutate, parentEntry, relationship, newView);\n }\n }\n // REMOVE: Decrement refCount, physically remove when rc=0.\n case 'remove': {\n if (singular) {\n const oldEntry = getSingularEntry(parentEntry, relationship);\n const rc = oldEntry[refCountSymbol];\n if (rc === 1) {\n return setRelation(mutate, parentEntry, relationship, undefined);\n }\n const newEntry = decRefCount(mutate, oldEntry);\n return setRelation(mutate, parentEntry, relationship, newEntry);\n } else {\n const view = getChildEntryList(parentEntry, relationship);\n const newView = removeAndUpdateRefCount(\n view,\n change.node.row,\n schema.compareRows,\n mutate,\n );\n return setRelation(mutate, parentEntry, relationship, newView);\n }\n }\n // CHILD: Propagate nested change up to this level (leaf-to-root pattern).\n case 'child': {\n const childSchema = must(\n schema.relationships[change.child.relationshipName],\n );\n const childFormat = format.relationships[change.child.relationshipName];\n if (childFormat === undefined) {\n return parentEntry; // Relationship not in view format\n }\n\n if (singular) {\n const existing = getSingularEntry(parentEntry, relationship);\n const newExisting = applyChangeInternal(\n existing,\n change.child.change,\n childSchema,\n change.child.relationshipName,\n childFormat,\n withIDs,\n mutate,\n );\n // Preserve identity if child didn't change (enables shallow-compare optimizations).\n if (newExisting === existing) {\n return parentEntry;\n }\n return setRelation(mutate, parentEntry, relationship, newExisting);\n } else {\n // Find the target row in the sorted array via binary search.\n const view = getChildEntryList(parentEntry, relationship);\n const pos = binarySearch(view, change.node.row, schema.compareRows);\n assert(pos >= 0, 'node does not exist');\n const existing = view[pos];\n const newExisting = applyChangeInternal(\n existing,\n change.child.change,\n childSchema,\n change.child.relationshipName,\n childFormat,\n withIDs,\n mutate,\n );\n // Preserve identity if descendant didn't change.\n if (newExisting === existing) {\n return parentEntry;\n }\n // applyChangeInternal preserves MetaEntry structure when input is MetaEntry\n assertMetaEntry(newExisting);\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n arrayWith(mutate, view, pos, newExisting),\n );\n }\n }\n // EDIT: Update row fields. If sort key changes, row may move position.\n //\n // Position change with rc>1 (two query paths reach same row):\n //\n // Before: [A, B(rc=2), C, D] After: [A, B(rc=1), C, B'(rc=1), D]\n // │ │ │\n // path1 + path2 path1 ghost path2 moved\n //\n // Why ghost stays: path1 still expects B at old position.\n // B' appears where path2's sort order places it.\n case 'edit': {\n if (singular) {\n const existing = getSingularEntry(parentEntry, relationship);\n const newEntry = applyEdit(existing, change, schema, withIDs, mutate);\n return setRelation(mutate, parentEntry, relationship, newEntry);\n } else {\n const view = getChildEntryList(parentEntry, relationship);\n // Sort key changed: row may need to move\n if (schema.compareRows(change.oldNode.row, change.node.row) !== 0) {\n const oldPos = binarySearch(\n view,\n change.oldNode.row,\n schema.compareRows,\n );\n assert(oldPos >= 0, 'old node does not exist');\n const oldEntry = view[oldPos];\n const rawPos = binarySearch(\n view,\n change.node.row,\n schema.compareRows,\n );\n const found = rawPos >= 0;\n const pos = found ? rawPos : ~rawPos;\n // A special case:\n // when refCount is 1 (so the row is being moved without leaving a\n // placeholder behind), and the new pos is the same as the old, or\n // directly after the old (so after the remove of the old it would be\n // in the same pos): the row does not need to be moved, just edited.\n if (\n oldEntry[refCountSymbol] === 1 &&\n (pos === oldPos || pos - 1 === oldPos)\n ) {\n const newEntry = applyEdit(\n oldEntry,\n change,\n schema,\n withIDs,\n mutate,\n );\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n arrayWith(mutate, view, oldPos, newEntry),\n );\n } else {\n // Move the row. If rc > 1, an edit will be received for each ref.\n // On first edit: move row, apply edit, set rc=1. Leave a copy at\n // old pos with decremented rc. As each edit arrives, old copy's rc\n // decrements and new pos rc increments. When copy rc hits 0, remove.\n const newRefCount = oldEntry[refCountSymbol] - 1;\n let newView: MutableMetaEntryList;\n let adjustedPos = pos;\n\n if (newRefCount === 0) {\n newView = removeAt(mutate, view, oldPos);\n adjustedPos = oldPos < pos ? pos - 1 : pos;\n } else {\n const oldEntryCopy = setRefCount(mutate, oldEntry, newRefCount);\n newView = arrayWith(mutate, view, oldPos, oldEntryCopy);\n }\n\n if (found) {\n // Merge with existing at new pos\n const existingEntry = newView[adjustedPos];\n const editedEntry = applyEdit(\n existingEntry,\n change,\n schema,\n withIDs,\n mutate,\n );\n const updatedEntry = setRefCount(\n mutate,\n editedEntry,\n existingEntry[refCountSymbol] + 1,\n );\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n arrayWith(mutate, newView, adjustedPos, updatedEntry),\n );\n } else {\n // Insert at new pos with rc=1\n const editedEntry = applyEdit(\n oldEntry,\n change,\n schema,\n withIDs,\n mutate,\n );\n const movedEntry = setRefCount(mutate, editedEntry, 1);\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n insertAt(mutate, newView, adjustedPos, movedEntry),\n );\n }\n }\n } else {\n // Sort key unchanged: edit in place\n const pos = binarySearch(\n view,\n change.oldNode.row,\n schema.compareRows,\n );\n assert(pos >= 0, 'node does not exist');\n const newEntry = applyEdit(\n view[pos],\n change,\n schema,\n withIDs,\n mutate,\n );\n return setRelation(\n mutate,\n parentEntry,\n relationship,\n arrayWith(mutate, view, pos, newEntry),\n );\n }\n }\n }\n default:\n unreachable(change);\n }\n}\n\n/**\n * Batch apply multiple changes to an Entry tree.\n * For small batches or complex cases, falls back to sequential applyChange.\n * Future optimization: O(N + K) batch processing for large K.\n */\nexport function applyChanges(\n parentEntry: Entry,\n changes: ViewChange[],\n schema: SourceSchema,\n relationship: string,\n format: Format,\n withIDs: WithIDs = false,\n mutate: Mutate = false,\n): Entry {\n let result = parentEntry;\n for (const change of changes) {\n result = applyChange(\n result,\n change,\n schema,\n relationship,\n format,\n withIDs,\n mutate,\n );\n }\n return result;\n}\n\nfunction applyEdit<M extends Mutate>(\n existing: MetaEntry<M>,\n change: EditViewChange,\n schema: SourceSchema,\n withIDs: WithIDs,\n mutate: Mutate,\n): MetaEntry<M> {\n // In-place edit is safe when fully mutating or when `existing` was already\n // created/cloned in this transaction (copy-on-write). A primary-key change\n // always needs a fresh entry so identity tracks the new key.\n const canMutate = mutate || owns(existing);\n const newEntry: MutableMetaEntry =\n canMutate && schema.compareRows(change.oldNode.row, change.node.row) === 0\n ? Object.assign(existing, change.node.row)\n : track({...existing, ...change.node.row});\n\n if (withIDs) {\n return setProperty(\n mutate,\n newEntry,\n idSymbol,\n makeID(change.node.row, schema),\n );\n }\n return newEntry;\n}\n\n/**\n * Initialize child relationships on a newly-added entry by mutating it in place.\n *\n * New nodes don't exist in the view yet, so we can build in-place (no refs to preserve):\n *\n * New nodes don't exist in the view yet, so we can build in-place (no refs to preserve):\n *\n * Existing node edit (must path-copy): New node (can build in-place):\n *\n * view: [A, B, C] view: [A, B, _]\n * │ │\n * edit C.child add C with children\n * │ │\n * ▼ ▼\n * view': [A, B, C'] ◄─ path-copy view': [A, B, C{children:[...]}]\n * up the tree └─ built in-place\n *\n * Hidden schemas still use applyChange to collapse junction levels.\n */\nfunction initializeRelationshipsForNewEntryIfAny(\n entry: MutableMetaEntry,\n node: ViewNode,\n schema: SourceSchema,\n childFormats: Record<string, Format>,\n withIDs: WithIDs,\n): void {\n let result = entry;\n for (const relationship of Object.keys(node.relationships)) {\n const childSchema = must(schema.relationships[relationship]);\n const childFormat = childFormats[relationship];\n if (childFormat === undefined) {\n continue;\n }\n\n // Hidden/singular: use applyChange to handle properly\n if (childSchema.isHidden || childFormat.singular) {\n const newView = childFormat.singular\n ? undefined\n : track([] as MutableMetaEntryList);\n result[relationship] = newView;\n\n for (const childNode of getChildNodes(node, relationship)) {\n applyChangeInternal(\n result,\n {type: 'add', node: childNode},\n childSchema,\n relationship,\n childFormat,\n withIDs,\n true, // this is a new entry, so we can mutate\n );\n }\n } else {\n // Plural non-hidden: build array in-place for efficiency\n const childArray: MutableMetaEntryList = track([]);\n\n for (const childNode of getChildNodes(node, relationship)) {\n const newEntry = makeNewMetaEntry(\n childNode.row,\n childSchema,\n withIDs,\n 1,\n );\n const rawPos = binarySearch(\n childArray,\n childNode.row,\n childSchema.compareRows,\n );\n\n if (rawPos >= 0) {\n childArray[rawPos][refCountSymbol]++;\n } else {\n childArray.splice(~rawPos, 0, newEntry);\n initializeRelationshipsForNewEntryIfAny(\n newEntry,\n childNode,\n childSchema,\n childFormat.relationships,\n withIDs,\n );\n }\n }\n\n result[relationship] = childArray;\n }\n }\n}\n\nfunction add<M extends Mutate>(\n row: Row,\n view: MetaEntryList<M>,\n schema: SourceSchema,\n withIDs: WithIDs,\n mutate: M,\n): {\n newEntry: MutableMetaEntry | undefined;\n newView: MutableMetaEntryList;\n} {\n const rawPos = binarySearch(view, row, schema.compareRows);\n\n if (rawPos >= 0) {\n const existing = view[rawPos];\n\n const updated = incRefCount(mutate, existing);\n return {\n newEntry: undefined,\n newView: arrayWith(mutate, view, rawPos, updated),\n };\n }\n const newEntry = makeNewMetaEntry(row, schema, withIDs, 1);\n return {newEntry, newView: insertAt(mutate, view, ~rawPos, newEntry)};\n}\n\nfunction insertAt<M extends Mutate, T>(\n mutate: M,\n array: MutableArray<M, T>,\n index: number,\n item: T,\n): T[] {\n if (mutate || owns(array)) {\n (array as T[]).splice(index, 0, item);\n return array as T[];\n }\n return track(array.toSpliced(index, 0, item));\n}\n\nfunction removeAt<M extends Mutate, T>(\n mutate: M,\n array: MutableArray<M, T>,\n index: number,\n): T[] {\n if (mutate || owns(array)) {\n (array as T[]).splice(index, 1);\n return array as T[];\n }\n return track(array.toSpliced(index, 1));\n}\n\nfunction removeAndUpdateRefCount<M extends Mutate>(\n view: MetaEntryList<M>,\n row: Row,\n compareRows: Comparator,\n mutate: M,\n): MutableMetaEntryList {\n const pos = binarySearch(view, row, compareRows);\n assert(pos >= 0, 'node does not exist');\n const oldEntry = view[pos];\n const rc = oldEntry[refCountSymbol];\n if (rc === 1) {\n return removeAt(mutate, view, pos);\n }\n const newEntry = decRefCount(mutate, oldEntry);\n return arrayWith(mutate, view, pos, newEntry);\n}\n\n/**\n * Binary search returning a number.\n * - If found at index `i`: returns `i` (>= 0).\n * - If not found, insertion point is `low`: returns `~low` (< 0).\n * Recover insertion point with `~result`.\n */\nfunction binarySearch(\n view: MetaEntryList<Mutate>,\n target: Row,\n comparator: Comparator,\n): number {\n let low = 0;\n let high = view.length - 1;\n while (low <= high) {\n const mid = (low + high) >>> 1;\n // MetaEntry has all Row props; comparator only reads string keys\n const comparison = comparator(view[mid] as Row, target);\n if (comparison < 0) {\n low = mid + 1;\n } else if (comparison > 0) {\n high = mid - 1;\n } else {\n return mid;\n }\n }\n return ~low;\n}\n\n/** Assert value is MetaEntry (has refCountSymbol). */\nfunction assertMetaEntry<M extends Mutate>(\n v: unknown,\n): asserts v is MetaEntry<M> {\n assertNumber((v as Partial<MetaEntry<M>>)[refCountSymbol]);\n}\n\n/** Get singular MetaEntry, throws if missing. */\nfunction getSingularEntry<M extends Mutate>(\n parentEntry: MetaEntry<M>,\n relationship: string,\n): MetaEntry<M> {\n const entry = parentEntry[relationship];\n assert(entry !== undefined, 'node does not exist');\n assertMetaEntry(entry);\n return entry;\n}\n\n/** Get singular MetaEntry or undefined if not set. */\nfunction getOptionalSingularEntry<M extends Mutate>(\n parentEntry: MetaEntry<M>,\n relationship: string,\n): MetaEntry<M> | undefined {\n const entry = parentEntry[relationship];\n if (entry === undefined) {\n return undefined;\n }\n assertMetaEntry(entry);\n return entry;\n}\n\n/** Get child array as MetaEntryList. */\nfunction getChildEntryList<M extends Mutate>(\n parentEntry: MetaEntry<M>,\n relationship: string,\n): MetaEntryList<M> {\n const view = parentEntry[relationship];\n assertArray(view);\n return view as MetaEntryList<M>;\n}\n\n/** Create MetaEntry from row with given refCount. */\nfunction makeNewMetaEntry(\n row: Row,\n schema: SourceSchema,\n withIDs: WithIDs,\n rc: number,\n): MutableMetaEntry {\n // This creates a new MetaEntry from a Row. We never mutate Rows.\n if (withIDs) {\n return track({\n ...row,\n [refCountSymbol]: rc,\n [idSymbol]: makeID(row, schema),\n });\n }\n return track({\n ...row,\n [refCountSymbol]: rc,\n });\n}\n\nfunction makeID(row: Row, schema: SourceSchema) {\n // optimization for case of non-compound primary key\n if (schema.primaryKey.length === 1) {\n return JSON.stringify(row[schema.primaryKey[0]]);\n }\n return JSON.stringify(schema.primaryKey.map(k => row[k]));\n}\n\nfunction incRefCount<M extends Mutate>(\n mutate: M,\n entry: MetaEntry<M>,\n): MutableMetaEntry {\n return setRefCount(mutate, entry, entry[refCountSymbol] + 1);\n}\n\nfunction decRefCount<M extends Mutate>(\n mutate: M,\n entry: MetaEntry<M>,\n): MutableMetaEntry {\n return setRefCount(mutate, entry, entry[refCountSymbol] - 1);\n}\n\nfunction setRefCount<M extends Mutate>(\n mutate: M,\n entry: MetaEntry<M>,\n count: number,\n): MutableMetaEntry {\n if (mutate || owns(entry)) {\n (entry as MutableMetaEntry)[refCountSymbol] = count;\n return entry;\n }\n return track({\n ...entry,\n [refCountSymbol]: count,\n });\n}\n\nfunction arrayWith<M extends Mutate, T>(\n mutate: M,\n array: MutableArray<M, T>,\n index: number,\n value: T,\n): T[] {\n if (mutate || owns(array)) {\n (array as T[])[index] = value;\n return array as T[];\n }\n return track(array.with(index, value));\n}\n\nfunction setProperty<\n M extends Mutate,\n K extends string | keyof MetaEntry<M>,\n V,\n>(\n mutate: M,\n parentEntry: MetaEntry<M>,\n key: K,\n value: V,\n): MutableMetaEntry & {[P in K]: V} {\n if (mutate || owns(parentEntry)) {\n assignProperty(parentEntry as {[P in K]: V}, key, value);\n return parentEntry as MutableMetaEntry & {[P in K]: V};\n }\n return track({\n ...parentEntry,\n [key]: value,\n }) as MutableMetaEntry & {[P in K]: V};\n}\n\nconst setRelation: <M extends Mutate>(\n mutate: M,\n parentEntry: MetaEntry<M>,\n relationship: string,\n value: Entry | Entry[] | undefined,\n) => MutableMetaEntry = setProperty;\n"],"mappings":";;;;;;AAeA,IAAa,iBAAiB,OAAO,IAAI;AACzC,IAAa,WAAW,OAAO,IAAI;;;;AA2FnC,UAAU,cACR,MACA,cACqB;CACrB,MAAM,WAAW,KAAK,cAAc;CACpC,IAAI,MAAM,QAAQ,QAAQ,GAExB,OAAO;MAGP,OAAO,WAAW,SAAS,CAAC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAI;;AAGJ,SAAS,KAAK,GAAoB;CAChC,OAAO,gBAAgB,KAAA,KAAa,YAAY,IAAI,CAAC;AACvD;;AAGA,SAAS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MAAK,IAAI,EAAE,CAAC;AAC1D;AAEA,SAAS,YACP,QACA,OACkB;CAClB,OAAO,YAAY,QAAQ,OAAO,MAAM,kBAAkB,CAAC;AAC7D;AAEA,SAAS,YACP,QACA,OACkB;CAClB,OAAO,YAAY,QAAQ,OAAO,MAAM,kBAAkB,CAAC;AAC7D;AAEA,SAAS,YACP,QACA,OACA,OACkB;CAClB,IAAI,UAAU,KAAK,KAAK,GAAG;EACzB,MAA4B,kBAAkB;EAC9C,OAAO;CACT;CACA,OAAO,MAAM;EACX,GAAG;GACF,iBAAiB;CACpB,CAAC;AACH;AAEA,SAAS,UACP,QACA,OACA,OACA,OACK;CACL,IAAI,UAAU,KAAK,KAAK,GAAG;EACzB,MAAe,SAAS;EACxB,OAAO;CACT;CACA,OAAO,MAAM,MAAM,KAAK,OAAO,KAAK,CAAC;AACvC;AAEA,SAAS,YAKP,QACA,aACA,KACA,OACkC;CAClC,IAAI,UAAU,KAAK,WAAW,GAAG;EAC/B,eAAe,aAA8B,KAAK,KAAK;EACvD,OAAO;CACT;CACA,OAAO,MAAM;EACX,GAAG;GACF,MAAM;CACT,CAAC;AACH;AAEA,IAAM,cAKkB"}
|
|
@@ -8,10 +8,11 @@ export type SchemaCRUD<S extends Schema> = {
|
|
|
8
8
|
export type TransactionMutate<S extends Schema> = SchemaCRUD<S>;
|
|
9
9
|
export type TableCRUD<S extends TableSchema> = {
|
|
10
10
|
/**
|
|
11
|
-
* Writes a row
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* Writes a row. If a row with the same primary key already exists this is a
|
|
12
|
+
* no-op; the existing row is left unchanged. A collision on any other unique
|
|
13
|
+
* constraint still throws. Non-primary-key fields that are 'optional' can be
|
|
14
|
+
* omitted or set to `undefined`. Such fields will be assigned the value
|
|
15
|
+
* `null` optimistically and then the default value as defined by the server.
|
|
15
16
|
*/
|
|
16
17
|
insert: (value: InsertValue<S>) => Promise<void>;
|
|
17
18
|
/**
|
|
@@ -57,10 +58,11 @@ export type UpdateValue<S extends TableSchema> = Expand<PrimaryKeyFields<S> & {
|
|
|
57
58
|
*/
|
|
58
59
|
export type TableMutator<TS extends TableSchema> = {
|
|
59
60
|
/**
|
|
60
|
-
* Writes a row
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
61
|
+
* Writes a row. If a row with the same primary key already exists this is a
|
|
62
|
+
* no-op; the existing row is left unchanged. A collision on any other unique
|
|
63
|
+
* constraint still throws. Non-primary-key fields that are 'optional' can be
|
|
64
|
+
* omitted or set to `undefined`. Such fields will be assigned the value
|
|
65
|
+
* `null` optimistically and then the default value as defined by the server.
|
|
64
66
|
*/
|
|
65
67
|
insert: (value: InsertValue<TS>) => Promise<void>;
|
|
66
68
|
/**
|