@rocicorp/zero 1.12.0 → 1.13.0-canary.1
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/bigint-json.d.ts +6 -0
- package/out/shared/src/bigint-json.d.ts.map +1 -1
- package/out/shared/src/bigint-json.js +14 -1
- package/out/shared/src/bigint-json.js.map +1 -1
- package/out/shared/src/objects.d.ts +7 -0
- package/out/shared/src/objects.d.ts.map +1 -1
- package/out/shared/src/objects.js +10 -1
- package/out/shared/src/objects.js.map +1 -1
- package/out/shared/src/resolver.d.ts.map +1 -1
- package/out/shared/src/resolver.js +12 -1
- package/out/shared/src/resolver.js.map +1 -1
- package/out/shared/src/valita.d.ts.map +1 -1
- package/out/shared/src/valita.js +2 -1
- package/out/shared/src/valita.js.map +1 -1
- package/out/z2s/src/compiler.d.ts.map +1 -1
- package/out/z2s/src/compiler.js +4 -2
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/zero/package.js +2 -2
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +4 -3
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
- package/out/zero-cache/src/config/normalize.js +3 -23
- package/out/zero-cache/src/config/normalize.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +1 -27
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +19 -47
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom/fetch.js +17 -2
- package/out/zero-cache/src/custom/fetch.js.map +1 -1
- package/out/zero-cache/src/db/create.js +45 -1
- package/out/zero-cache/src/db/create.js.map +1 -1
- package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
- package/out/zero-cache/src/db/lite-tables.js +4 -3
- package/out/zero-cache/src/db/lite-tables.js.map +1 -1
- package/out/zero-cache/src/db/pg-copy-binary.js +61 -25
- package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
- package/out/zero-cache/src/db/pg-to-lite.d.ts +17 -0
- package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
- package/out/zero-cache/src/db/pg-to-lite.js +84 -1
- package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +21 -30
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/inspector-delegate.js +1 -1
- package/out/zero-cache/src/server/main.js +0 -1
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/replicator.js +1 -1
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +6 -5
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +50 -12
- 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.js +64 -21
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js +11 -6
- 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 +13 -1
- 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 +16 -3
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +6 -4
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.js +56 -12
- package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +35 -12
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +6 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.js +25 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +6 -5
- package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backfill-state.js +7 -6
- package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js +2 -2
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +16 -199
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +76 -127
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +15 -49
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -2
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +20 -36
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js +32 -20
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +4 -2
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +0 -16
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.js +3 -95
- package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-db.js +2 -2
- package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +1 -30
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +83 -38
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +7 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -0
- package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.js +4 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.js +2 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +6 -102
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
- package/out/zero-cache/src/services/statz.d.ts.map +1 -1
- package/out/zero-cache/src/services/statz.js +1 -1
- package/out/zero-cache/src/services/statz.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/active-users-gauge.js +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
- package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +47 -3
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +51 -6
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/lite.d.ts +7 -0
- package/out/zero-cache/src/types/lite.d.ts.map +1 -1
- package/out/zero-cache/src/types/lite.js +12 -2
- package/out/zero-cache/src/types/lite.js.map +1 -1
- package/out/zero-cache/src/types/pg-types.d.ts +2 -1
- package/out/zero-cache/src/types/pg-types.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg-types.js +2 -1
- package/out/zero-cache/src/types/pg-types.js.map +1 -1
- package/out/zero-cache/src/types/pg.d.ts +20 -0
- package/out/zero-cache/src/types/pg.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg.js +64 -27
- package/out/zero-cache/src/types/pg.js.map +1 -1
- package/out/zero-cache/src/types/streams.d.ts +2 -0
- package/out/zero-cache/src/types/streams.d.ts.map +1 -1
- package/out/zero-cache/src/types/streams.js +2 -1
- package/out/zero-cache/src/types/streams.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.js +7 -6
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +18 -1
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/crud-impl.js +1 -1
- package/out/zero-client/src/client/ivm-branch.js +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-protocol/src/client-schema.js +1 -1
- package/out/zero-protocol/src/down.d.ts +2 -2
- package/out/zero-schema/src/builder/schema-builder.js +1 -1
- package/out/zql/src/builder/builder.js +1 -1
- package/out/zql/src/ivm/aggregate.js +1 -1
- package/out/zql/src/ivm/flipped-join.js +1 -1
- package/out/zql/src/ivm/group-by.js +1 -1
- package/out/zql/src/ivm/join-index.js +1 -1
- package/out/zql/src/ivm/memory-source.js +1 -1
- package/out/zql/src/ivm/view-apply-change.js +1 -1
- package/out/zqlite/src/db.js +4 -1
- package/out/zqlite/src/db.js.map +1 -1
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +4 -2
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +2 -2
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +0 -67
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +0 -39
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/shard-sampling.js +0 -19
- package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +0 -417
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","names":["v","v.parse"],"sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/init.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../../../shared/src/asserts.ts';\nimport * as v from '../../../../../../shared/src/valita.ts';\nimport {\n runSchemaMigrations,\n type IncrementalMigrationMap,\n type Migration,\n} from '../../../../db/migration.ts';\nimport type {PostgresDB} from '../../../../types/pg.ts';\nimport {upstreamSchema, type ShardConfig} from '../../../../types/shards.ts';\nimport {id} from '../../../../types/sql.ts';\nimport {AutoResetSignal} from '../../../change-streamer/schema/tables.ts';\nimport {publishedSchema} from './published.ts';\nimport * as ReplicaStage from './replica-stage-enum.ts';\nimport {\n getMutationsTableDefinition,\n legacyReplicationSlot,\n metadataPublicationName,\n setupTablesAndReplication,\n setupTriggers,\n} from './shard.ts';\n\n/**\n * Ensures that a shard is set up for initial sync.\n */\nexport async function ensureShardSchema(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardConfig,\n installPartialIndexTriggers = true,\n): Promise<void> {\n const initialSetup: Migration = {\n migrateSchema: (lc, tx) =>\n setupTablesAndReplication(lc, tx, shard, installPartialIndexTriggers),\n minSafeVersion: 1,\n };\n await runSchemaMigrations(\n lc,\n `upstream-shard-${shard.appID}`,\n upstreamSchema(shard),\n db,\n initialSetup,\n // The incremental migration of any existing replicas will be replaced by\n // the incoming replica being synced, so the replicaVersion here is\n // unnecessary.\n getIncrementalMigrations(shard, installPartialIndexTriggers),\n );\n}\n\nfunction getIncrementalMigrations(\n shard: ShardConfig,\n installPartialIndexTriggers: boolean,\n): IncrementalMigrationMap {\n const shardConfigTable = `${upstreamSchema(shard)}.shardConfig`;\n\n return {\n 6: {\n migrateSchema: () => {\n throw new AutoResetSignal('resetting to upgrade shard schema');\n },\n },\n\n // v7: Updates the DDL event trigger protocol to v2, and adds support for\n // ALTER SCHEMA x RENAME TO y\n // (migration logic subsumbed by v23)\n\n // v8: Adds support for non-disruptive resyncs, which tracks multiple\n // replicas with different slot names.\n 8: {\n migrateSchema: async (lc, sql) => {\n const legacyShardConfigSchema = v.object({\n replicaVersion: v.string().nullable(),\n initialSchema: publishedSchema.nullable(),\n });\n const result = await sql`\n SELECT \"replicaVersion\", \"initialSchema\" FROM ${sql(shardConfigTable)}`;\n assert(\n result.length === 1,\n () => `Expected exactly one shardConfig row, got ${result.length}`,\n );\n const {replicaVersion, initialSchema} = v.parse(\n result[0],\n legacyShardConfigSchema,\n 'passthrough',\n );\n\n await Promise.all([\n sql`\n CREATE TABLE ${sql(upstreamSchema(shard))}.replicas (\n \"slot\" TEXT PRIMARY KEY,\n \"version\" TEXT NOT NULL,\n \"initialSchema\" JSON NOT NULL\n );\n `,\n sql`\n INSERT INTO ${sql(upstreamSchema(shard))}.replicas ${sql({\n slot: legacyReplicationSlot(shard),\n version: replicaVersion,\n initialSchema,\n })}\n `,\n sql`\n ALTER TABLE ${sql(shardConfigTable)} DROP \"replicaVersion\", DROP \"initialSchema\"\n `,\n ]);\n lc.info?.(`Upgraded schema to support non-disruptive resyncs`);\n },\n },\n\n // v9: Fixes field ordering of compound indexes. This incremental migration\n // only fixes indexes resulting from new schema changes. A full resync is\n // required to fix existing indexes.\n //\n // The migration has been subsumed by the identical logic for migrating\n // to v12 (i.e. a trigger upgrade).\n\n // Adds the `mutations` table used to track mutation results.\n 10: {\n migrateSchema: async (lc, sql) => {\n await sql.unsafe(/*sql*/ `\n ${getMutationsTableDefinition(upstreamSchema(shard))}\n ALTER PUBLICATION ${id(metadataPublicationName(shard.appID, shard.shardNum))} ADD TABLE ${id(upstreamSchema(shard))}.\"mutations\";\n `);\n lc.info?.('Upgraded schema with new mutations table');\n },\n },\n\n // v11: Formerly dropped the schemaVersions table, but restored in the v13\n // migration for rollback safety.\n\n // v12: Upgrade DDL trigger to query schemaOID, needed information for auto-backfill.\n // (subsumed by v14)\n\n // Recreates the legacy schemaVersions table that was prematurely dropped\n // in the (former) v11 migration. It needs to remain present for at least one\n // release in order to be rollback safe.\n //\n // TODO: Drop the table once a release that no longer reads the table has\n // been rolled out.\n 13: {\n migrateSchema: async (_, sql) => {\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql(upstreamSchema(shard))}.\"schemaVersions\" (\n \"minSupportedVersion\" INT4,\n \"maxSupportedVersion\" INT4,\n \"lock\" BOOL PRIMARY KEY DEFAULT true CHECK (lock)\n );`;\n await sql`\n INSERT INTO ${sql(upstreamSchema(shard))}.\"schemaVersions\" \n (\"lock\", \"minSupportedVersion\", \"maxSupportedVersion\")\n VALUES (true, 1, 1)\n ON CONFLICT DO NOTHING;\n `;\n },\n },\n\n // v14: Upgrade DDL trigger to log more info to PG logs.\n // (subsumed by v16)\n\n // Add initialSyncContext column to replicas table.\n 15: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas\n ADD COLUMN \"initialSyncContext\" JSON,\n ADD COLUMN \"subscriberContext\" JSON\n `;\n },\n },\n\n // v16: Upgrade DDL trigger to fire on all ALTER TABLE statements\n // to catch the *removal* of a table from the published set.\n // v17 (1.0.0): Upgrade DDL triggers to support the COMMENT ON PUBLICATION hook for\n // working around the lack of event trigger support for PUBLICATION\n // changes in supabase.\n // This also adds forwards-compatible support for hierarchical logical\n // message prefixes and unknown ddl event types.\n // v18: Pure refactoring of event trigger code.\n // v19 (1.4.0): Correctly handle concurrently issued DDL statements.\n // v20 (1.4.0): Handle nested DDL triggers\n // v21 (1.5.0): Handle cross-transaction DDL operations (i.e. concurrent\n // index operations), and support manual invocation of update_schemas().\n\n 22: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ALTER \"initialSchema\" DROP NOT NULL;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n DROP CONSTRAINT replicas_pkey;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN id TEXT PRIMARY KEY DEFAULT replace(gen_random_uuid()::text, '-', '');\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN rank BIGSERIAL;\n `;\n },\n },\n\n // v23 (1.6.0): Event triggers: Handle the case where current_query()\n // returns NULL. Add more logging to debug unexpected messages\n 23: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(lc, sql, {...shard, publications});\n lc.info?.(`Upgraded DDL event triggers`);\n },\n },\n\n // v24 (1.10.0):\n // - adds the \"backupPath\" column for per-replica backups.\n // - adds the \"generation\" column to replace \"version\".\n 24: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN \"backupPath\" TEXT;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN \"generation\" TEXT;\n `;\n },\n\n migrateData: async (_, sql) => {\n // Backfill the \"generation\" column to eventually replace \"version\"\n await sql`\n UPDATE ${sql(upstreamSchema(shard))}.replicas SET \"generation\" = \"version\";\n `;\n },\n },\n\n // v25 (1.10.0):\n // - adds the \"backupV5\" column to signal the current semantics\n // of the replication slot's confirmed_flush_lsn with respect to what\n // has been backed up.\n 25: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN \"backupV5\" BOOL DEFAULT false;\n `;\n },\n },\n\n // v27 (1.11.0):\n // - make `generation` NOT NULL and stop reading `version`\n 27: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas ALTER \"generation\" SET NOT NULL;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas ALTER \"version\" DROP NOT NULL;\n `;\n },\n },\n\n 28: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas ADD \"epoch\" INT4 DEFAULT 0;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas ADD \"stage\" INT4 DEFAULT 0; -- ReplicaStage.InitialSync\n `;\n\n const metapub = metadataPublicationName(shard.appID, shard.shardNum);\n await sql`\n ALTER PUBLICATION ${sql(metapub)} ADD TABLE ${sql(upstreamSchema(shard))}.replicas (id);\n `;\n // Make sure supabase gets the ALTER PUBLICATION change\n await sql`\n SELECT ${sql(upstreamSchema(shard))}.update_schemas();\n `;\n },\n\n migrateData: async (_, sql) => {\n await sql`\n UPDATE ${sql(upstreamSchema(shard))}.replicas SET \"stage\" = ${ReplicaStage.Replicate}\n WHERE \"subscriberContext\" IS NOT NULL;\n `;\n },\n },\n\n // v30: Adds the \"pgChangeLog\" column, which records whether the\n // replication-manager that took over a replica's slot acks it only after\n // storing transactions in the PG change log (RMv1.5), in which case a\n // slot position past the change log's head reflects acked keepalives\n // rather than missing transactions.\n //\n // The column defaults to false (i.e. unknown), so that a slot is assumed\n // to be possibly ahead of the change log until it is taken over by a\n // replication-manager that sets it. Existing replicas that have been taken\n // over are backfilled as true (see migrateData). Note that a replication-manager that\n // predates this column does not reset it when taking over a slot, so\n // once the column is set, RMv2 (in which acks are not gated on the PG\n // change log) must run at least this version.\n 30: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN IF NOT EXISTS \"pgChangeLog\" BOOL DEFAULT false;\n `;\n },\n\n // Existing replicas whose slots have been taken over (i.e. that have a\n // subscriberContext) were acked by RMv1 or RMv1.5, which store\n // transactions in the PG change log before acking them. This assumes\n // that no RMv2 is running when the migration is run. Replicas that have\n // not been taken over (e.g. fork destinations) remain unknown, as their\n // slots have not been acked.\n migrateData: async (_, sql) => {\n await sql`\n UPDATE ${sql(upstreamSchema(shard))}.replicas SET \"pgChangeLog\" = true\n WHERE \"subscriberContext\" IS NOT NULL;\n `;\n },\n },\n\n // v32: Upgrade the DDL event functions to include the shard's event\n // secret in every ddl event, and install the secret.\n 32: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(\n lc,\n sql,\n {...shard, publications},\n installPartialIndexTriggers,\n );\n lc.info?.(`Upgraded DDL event triggers`);\n },\n },\n\n // Note: While this is conditional, it always has to be bumped to the last\n // version. (It was v29 and v31, and is re-run for shards at those versions\n // when it is bumped, which is harmless as setupTriggers() is idempotent.)\n ...(installPartialIndexTriggers\n ? {\n // v33: Upgrade the DDL event triggers to include partial indexes in\n // schema snapshots. Note that setupTriggers() also refreshes the\n // stored \"publishedSchema\" so that the change in format does not\n // manifest as a spurious schema change.\n 33: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(lc, sql, {...shard, publications});\n lc.info?.(`Upgraded DDL event triggers`);\n },\n },\n }\n : {}),\n };\n}\n\n// Referenced in tests.\nexport const CURRENT_SCHEMA_VERSION = Object.keys(\n getIncrementalMigrations(\n {\n appID: 'unused',\n shardNum: 0,\n publications: ['foo'],\n },\n true,\n ),\n).reduce((prev, curr) => Math.max(prev, parseInt(curr)), 0);\n"],"mappings":";;;;;;;;;;;;;AAyBA,eAAsB,kBACpB,IACA,IACA,OACA,8BAA8B,MACf;CAMf,MAAM,oBACJ,IACA,kBAAkB,MAAM,SACxB,eAAe,KAAK,GACpB,IACA;EATA,gBAAgB,IAAI,OAClB,0BAA0B,IAAI,IAAI,OAAO,2BAA2B;EACtE,gBAAgB;CAOhB,GAIA,yBAAyB,OAAO,2BAA2B,CAC7D;AACF;AAEA,SAAS,yBACP,OACA,6BACyB;CACzB,MAAM,mBAAmB,GAAG,eAAe,KAAK,EAAE;CAElD,OAAO;EACL,GAAG,EACD,qBAAqB;GACnB,MAAM,IAAI,gBAAgB,mCAAmC;EAC/D,EACF;EAQA,GAAG,EACD,eAAe,OAAO,IAAI,QAAQ;GAChC,MAAM,0BAA0BA,eAAE,OAAO;IACvC,gBAAgBA,eAAE,OAAO,CAAC,CAAC,SAAS;IACpC,eAAe,gBAAgB,SAAS;GAC1C,CAAC;GACD,MAAM,SAAS,MAAM,GAAG;0DAC0B,IAAI,gBAAgB;GACtE,OACE,OAAO,WAAW,SACZ,6CAA6C,OAAO,QAC5D;GACA,MAAM,EAAC,gBAAgB,kBAAiBC,MACtC,OAAO,IACP,yBACA,aACF;GAEA,MAAM,QAAQ,IAAI;IAChB,GAAG;yBACY,IAAI,eAAe,KAAK,CAAC,EAAE;;;;;;IAM1C,GAAG;wBACW,IAAI,eAAe,KAAK,CAAC,EAAE,YAAY,IAAI;KACvD,MAAM,sBAAsB,KAAK;KACjC,SA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,IACA,KACA;IAAC,GAAG;IAAO;GAAY,GACvB,2BACF;GACA,GAAG,OAAO,6BAA6B;EACzC,EACF;EAKA,GAAI,8BACA,EAKE,IAAI,EACF,eAAe,OAAO,IAAI,QAAQ;GAChC,MAAM,CAAC,EAAC,kBAAiB,MAAM,GAA+B;2CACjC,IAAI,gBAAgB;GACjD,MAAM,cAAc,IAAI,KAAK;IAAC,GAAG;IAAO;GAAY,CAAC;GACrD,GAAG,OAAO,6BAA6B;EACzC,EACF,EACF,IACA,CAAC;CACP;AACF;AAGsC,OAAO,KAC3C,yBACE;CACE,OAAO;CACP,UAAU;CACV,cAAc,CAAC,KAAK;AACtB,GACA,IACF,CACF,CAAC,CAAC,QAAQ,MAAM,SAAS,KAAK,IAAI,MAAM,SAAS,IAAI,CAAC,GAAG,CAAC"}
|
|
1
|
+
{"version":3,"file":"init.js","names":["v","v.parse"],"sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/init.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../../../shared/src/asserts.ts';\nimport * as v from '../../../../../../shared/src/valita.ts';\nimport {\n runSchemaMigrations,\n type IncrementalMigrationMap,\n type Migration,\n} from '../../../../db/migration.ts';\nimport type {PostgresDB} from '../../../../types/pg.ts';\nimport {upstreamSchema, type ShardConfig} from '../../../../types/shards.ts';\nimport {id} from '../../../../types/sql.ts';\nimport {AutoResetSignal} from '../../../change-streamer/schema/tables.ts';\nimport {getPublicationInfo, publishedSchema} from './published.ts';\nimport * as ReplicaStage from './replica-stage-enum.ts';\nimport {\n getMutationsTableDefinition,\n legacyReplicationSlot,\n metadataPublicationName,\n replicaIdentitiesForTablesWithoutPrimaryKeys,\n setupTablesAndReplication,\n setupTriggers,\n} from './shard.ts';\n\n/**\n * Ensures that a shard is set up for initial sync.\n */\nexport async function ensureShardSchema(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardConfig,\n installPartialIndexTriggers = true,\n): Promise<void> {\n const initialSetup: Migration = {\n migrateSchema: (lc, tx) =>\n setupTablesAndReplication(lc, tx, shard, installPartialIndexTriggers),\n minSafeVersion: 1,\n };\n await runSchemaMigrations(\n lc,\n `upstream-shard-${shard.appID}`,\n upstreamSchema(shard),\n db,\n initialSetup,\n // The incremental migration of any existing replicas will be replaced by\n // the incoming replica being synced, so the replicaVersion here is\n // unnecessary.\n getIncrementalMigrations(shard, installPartialIndexTriggers),\n );\n}\n\nfunction getIncrementalMigrations(\n shard: ShardConfig,\n installPartialIndexTriggers: boolean,\n): IncrementalMigrationMap {\n const shardConfigTable = `${upstreamSchema(shard)}.shardConfig`;\n\n return {\n 6: {\n migrateSchema: () => {\n throw new AutoResetSignal('resetting to upgrade shard schema');\n },\n },\n\n // v7: Updates the DDL event trigger protocol to v2, and adds support for\n // ALTER SCHEMA x RENAME TO y\n // (migration logic subsumbed by v23)\n\n // v8: Adds support for non-disruptive resyncs, which tracks multiple\n // replicas with different slot names.\n 8: {\n migrateSchema: async (lc, sql) => {\n const legacyShardConfigSchema = v.object({\n replicaVersion: v.string().nullable(),\n initialSchema: publishedSchema.nullable(),\n });\n const result = await sql`\n SELECT \"replicaVersion\", \"initialSchema\" FROM ${sql(shardConfigTable)}`;\n assert(\n result.length === 1,\n () => `Expected exactly one shardConfig row, got ${result.length}`,\n );\n const {replicaVersion, initialSchema} = v.parse(\n result[0],\n legacyShardConfigSchema,\n 'passthrough',\n );\n\n await Promise.all([\n sql`\n CREATE TABLE ${sql(upstreamSchema(shard))}.replicas (\n \"slot\" TEXT PRIMARY KEY,\n \"version\" TEXT NOT NULL,\n \"initialSchema\" JSON NOT NULL\n );\n `,\n sql`\n INSERT INTO ${sql(upstreamSchema(shard))}.replicas ${sql({\n slot: legacyReplicationSlot(shard),\n version: replicaVersion,\n initialSchema,\n })}\n `,\n sql`\n ALTER TABLE ${sql(shardConfigTable)} DROP \"replicaVersion\", DROP \"initialSchema\"\n `,\n ]);\n lc.info?.(`Upgraded schema to support non-disruptive resyncs`);\n },\n },\n\n // v9: Fixes field ordering of compound indexes. This incremental migration\n // only fixes indexes resulting from new schema changes. A full resync is\n // required to fix existing indexes.\n //\n // The migration has been subsumed by the identical logic for migrating\n // to v12 (i.e. a trigger upgrade).\n\n // Adds the `mutations` table used to track mutation results.\n 10: {\n migrateSchema: async (lc, sql) => {\n await sql.unsafe(/*sql*/ `\n ${getMutationsTableDefinition(upstreamSchema(shard))}\n ALTER PUBLICATION ${id(metadataPublicationName(shard.appID, shard.shardNum))} ADD TABLE ${id(upstreamSchema(shard))}.\"mutations\";\n `);\n lc.info?.('Upgraded schema with new mutations table');\n },\n },\n\n // v11: Formerly dropped the schemaVersions table, but restored in the v13\n // migration for rollback safety.\n\n // v12: Upgrade DDL trigger to query schemaOID, needed information for auto-backfill.\n // (subsumed by v14)\n\n // Recreates the legacy schemaVersions table that was prematurely dropped\n // in the (former) v11 migration. It needs to remain present for at least one\n // release in order to be rollback safe.\n //\n // TODO: Drop the table once a release that no longer reads the table has\n // been rolled out.\n 13: {\n migrateSchema: async (_, sql) => {\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql(upstreamSchema(shard))}.\"schemaVersions\" (\n \"minSupportedVersion\" INT4,\n \"maxSupportedVersion\" INT4,\n \"lock\" BOOL PRIMARY KEY DEFAULT true CHECK (lock)\n );`;\n await sql`\n INSERT INTO ${sql(upstreamSchema(shard))}.\"schemaVersions\" \n (\"lock\", \"minSupportedVersion\", \"maxSupportedVersion\")\n VALUES (true, 1, 1)\n ON CONFLICT DO NOTHING;\n `;\n },\n },\n\n // v14: Upgrade DDL trigger to log more info to PG logs.\n // (subsumed by v16)\n\n // Add initialSyncContext column to replicas table.\n 15: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas\n ADD COLUMN \"initialSyncContext\" JSON,\n ADD COLUMN \"subscriberContext\" JSON\n `;\n },\n },\n\n // v16: Upgrade DDL trigger to fire on all ALTER TABLE statements\n // to catch the *removal* of a table from the published set.\n // v17 (1.0.0): Upgrade DDL triggers to support the COMMENT ON PUBLICATION hook for\n // working around the lack of event trigger support for PUBLICATION\n // changes in supabase.\n // This also adds forwards-compatible support for hierarchical logical\n // message prefixes and unknown ddl event types.\n // v18: Pure refactoring of event trigger code.\n // v19 (1.4.0): Correctly handle concurrently issued DDL statements.\n // v20 (1.4.0): Handle nested DDL triggers\n // v21 (1.5.0): Handle cross-transaction DDL operations (i.e. concurrent\n // index operations), and support manual invocation of update_schemas().\n\n 22: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ALTER \"initialSchema\" DROP NOT NULL;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n DROP CONSTRAINT replicas_pkey;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN id TEXT PRIMARY KEY DEFAULT replace(gen_random_uuid()::text, '-', '');\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN rank BIGSERIAL;\n `;\n },\n },\n\n // v23 (1.6.0): Event triggers: Handle the case where current_query()\n // returns NULL. Add more logging to debug unexpected messages\n 23: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(lc, sql, {...shard, publications});\n lc.info?.(`Upgraded DDL event triggers`);\n },\n },\n\n // v24 (1.10.0):\n // - adds the \"backupPath\" column for per-replica backups.\n // - adds the \"generation\" column to replace \"version\".\n 24: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN \"backupPath\" TEXT;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN \"generation\" TEXT;\n `;\n },\n\n migrateData: async (_, sql) => {\n // Backfill the \"generation\" column to eventually replace \"version\"\n await sql`\n UPDATE ${sql(upstreamSchema(shard))}.replicas SET \"generation\" = \"version\";\n `;\n },\n },\n\n // v25 (1.10.0):\n // - adds the \"backupV5\" column to signal the current semantics\n // of the replication slot's confirmed_flush_lsn with respect to what\n // has been backed up.\n 25: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN \"backupV5\" BOOL DEFAULT false;\n `;\n },\n },\n\n // v27 (1.11.0):\n // - make `generation` NOT NULL and stop reading `version`\n 27: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas ALTER \"generation\" SET NOT NULL;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas ALTER \"version\" DROP NOT NULL;\n `;\n },\n },\n\n 28: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas ADD \"epoch\" INT4 DEFAULT 0;\n `;\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas ADD \"stage\" INT4 DEFAULT 0; -- ReplicaStage.InitialSync\n `;\n\n const metapub = metadataPublicationName(shard.appID, shard.shardNum);\n await sql`\n ALTER PUBLICATION ${sql(metapub)} ADD TABLE ${sql(upstreamSchema(shard))}.replicas (id);\n `;\n // Make sure supabase gets the ALTER PUBLICATION change\n await sql`\n SELECT ${sql(upstreamSchema(shard))}.update_schemas();\n `;\n },\n\n migrateData: async (_, sql) => {\n await sql`\n UPDATE ${sql(upstreamSchema(shard))}.replicas SET \"stage\" = ${ReplicaStage.Replicate}\n WHERE \"subscriberContext\" IS NOT NULL;\n `;\n },\n },\n\n // v30: Adds the \"pgChangeLog\" column, which records whether the\n // replication-manager that took over a replica's slot acks it only after\n // storing transactions in the PG change log (RMv1.5), in which case a\n // slot position past the change log's head reflects acked keepalives\n // rather than missing transactions.\n //\n // The column defaults to false (i.e. unknown), so that a slot is assumed\n // to be possibly ahead of the change log until it is taken over by a\n // replication-manager that sets it. Existing replicas that have been taken\n // over are backfilled as true (see migrateData). Note that a replication-manager that\n // predates this column does not reset it when taking over a slot, so\n // once the column is set, RMv2 (in which acks are not gated on the PG\n // change log) must run at least this version.\n 30: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas \n ADD COLUMN IF NOT EXISTS \"pgChangeLog\" BOOL DEFAULT false;\n `;\n },\n\n // Existing replicas whose slots have been taken over (i.e. that have a\n // subscriberContext) were acked by RMv1 or RMv1.5, which store\n // transactions in the PG change log before acking them. This assumes\n // that no RMv2 is running when the migration is run. Replicas that have\n // not been taken over (e.g. fork destinations) remain unknown, as their\n // slots have not been acked.\n migrateData: async (_, sql) => {\n await sql`\n UPDATE ${sql(upstreamSchema(shard))}.replicas SET \"pgChangeLog\" = true\n WHERE \"subscriberContext\" IS NOT NULL;\n `;\n },\n },\n\n // v32: Upgrade the DDL event functions to include the shard's event\n // secret in every ddl event, and install the secret.\n // Superseded by v40.\n\n // v34: Upgrade the DDL event functions to classify a column as an array\n // only if its type is the array type of its element, and to report\n // deferrable unique constraints as non-unique.\n // Superseded by v40.\n\n // v36: Upgrade the DDL event triggers to fire for CREATE TABLE AS and\n // SELECT INTO.\n // Superseded by v40.\n\n // v37: Upgrade the DDL event functions to report the partitions of a\n // partitioned table.\n // Superseded by v40.\n\n // v38: Upgrade the DDL event triggers to fire for the commands that drop\n // the columns of a table with CASCADE, such as DROP TYPE.\n // Superseded by v40.\n\n // v39: Upgrade the DDL event functions to report a unique index as not\n // unique when distinct values of its columns are the same on the replica.\n // Superseded by v40.\n\n // v40: Upgrade the DDL event functions to report no primary key for one\n // with a column that is not published, and set the replica identity of\n // the tables that have such a key.\n 40: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(\n lc,\n sql,\n {...shard, publications},\n installPartialIndexTriggers,\n );\n lc.info?.(`Upgraded DDL event triggers`);\n // After the triggers, so that the events of these ALTER TABLEs\n // describe the tables as the upgraded functions do.\n const pubs = await getPublicationInfo(sql, publications);\n await replicaIdentitiesForTablesWithoutPrimaryKeys(pubs)?.apply(\n lc,\n sql,\n );\n },\n },\n\n // Note: While this is conditional, it always has to be bumped to the last\n // version. (It was v29, v31, v33, v35, v37, v38, v39 and v40, and is re-run for shards at those\n // versions when it is bumped, which is harmless as setupTriggers() is\n // idempotent.)\n ...(installPartialIndexTriggers\n ? {\n // v41: Upgrade the DDL event triggers to include partial indexes in\n // schema snapshots. Note that setupTriggers() also refreshes the\n // stored \"publishedSchema\" so that the change in format does not\n // manifest as a spurious schema change.\n 41: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(lc, sql, {...shard, publications});\n lc.info?.(`Upgraded DDL event triggers`);\n },\n },\n }\n : {}),\n };\n}\n\n// Referenced in tests.\nexport const CURRENT_SCHEMA_VERSION = Object.keys(\n getIncrementalMigrations(\n {\n appID: 'unused',\n shardNum: 0,\n publications: ['foo'],\n },\n true,\n ),\n).reduce((prev, curr) => Math.max(prev, parseInt(curr)), 0);\n"],"mappings":";;;;;;;;;;;;;AA0BA,eAAsB,kBACpB,IACA,IACA,OACA,8BAA8B,MACf;CAMf,MAAM,oBACJ,IACA,kBAAkB,MAAM,SACxB,eAAe,KAAK,GACpB,IACA;EATA,gBAAgB,IAAI,OAClB,0BAA0B,IAAI,IAAI,OAAO,2BAA2B;EACtE,gBAAgB;CAOhB,GAIA,yBAAyB,OAAO,2BAA2B,CAC7D;AACF;AAEA,SAAS,yBACP,OACA,6BACyB;CACzB,MAAM,mBAAmB,GAAG,eAAe,KAAK,EAAE;CAElD,OAAO;EACL,GAAG,EACD,qBAAqB;GACnB,MAAM,IAAI,gBAAgB,mCAAmC;EAC/D,EACF;EAQA,GAAG,EACD,eAAe,OAAO,IAAI,QAAQ;GAChC,MAAM,0BAA0BA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,OAAO,GAAG,QAAQ;IAC7B,MAAM,GAAG;mBACE,IAAI,eAAe,KAAK,CAAC,EAAE,0BAA0B,EAAuB;;;GAGzF;EACF;EAeA,IAAI;GACF,eAAe,OAAO,GAAG,QAAQ;IAC/B,MAAM,GAAG;wBACO,IAAI,eAAe,KAAK,CAAC,EAAE;;;GAG7C;GAQA,aAAa,OAAO,GAAG,QAAQ;IAC7B,MAAM,GAAG;mBACE,IAAI,eAAe,KAAK,CAAC,EAAE;;;GAGxC;EACF;EA8BA,IAAI,EACF,eAAe,OAAO,IAAI,QAAQ;GAChC,MAAM,CAAC,EAAC,kBAAiB,MAAM,GAA+B;qCACjC,IAAI,gBAAgB;GACjD,MAAM,cACJ,IACA,KACA;IAAC,GAAG;IAAO;GAAY,GACvB,2BACF;GACA,GAAG,OAAO,6BAA6B;GAGvC,MAAM,OAAO,MAAM,mBAAmB,KAAK,YAAY;GACvD,MAAM,6CAA6C,IAAI,CAAC,EAAE,MACxD,IACA,GACF;EACF,EACF;EAMA,GAAI,8BACA,EAKE,IAAI,EACF,eAAe,OAAO,IAAI,QAAQ;GAChC,MAAM,CAAC,EAAC,kBAAiB,MAAM,GAA+B;2CACjC,IAAI,gBAAgB;GACjD,MAAM,cAAc,IAAI,KAAK;IAAC,GAAG;IAAO;GAAY,CAAC;GACrD,GAAG,OAAO,6BAA6B;EACzC,EACF,EACF,IACA,CAAC;CACP;AACF;AAGsC,OAAO,KAC3C,yBACE;CACE,OAAO;CACP,UAAU;CACV,cAAc,CAAC,KAAK;AACtB,GACA,IACF,CACF,CAAC,CAAC,QAAQ,MAAM,SAAS,KAAK,IAAI,MAAM,SAAS,IAAI,CAAC,GAAG,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"published.d.ts","sourceRoot":"","sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/published.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AAIrC,OAAO,KAAK,CAAC,MAAM,wCAAwC,CAAC;AAc5D,OAAO,EAEL,KAAK,0BAA0B,EAChC,MAAM,sBAAsB,CAAC;AAE9B,wBAAgB,oBAAoB,CAClC,YAAY,EAAE,SAAS,MAAM,EAAE,EAC/B,qBAAqB,UAAO,
|
|
1
|
+
{"version":3,"file":"published.d.ts","sourceRoot":"","sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/published.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AAIrC,OAAO,KAAK,CAAC,MAAM,wCAAwC,CAAC;AAc5D,OAAO,EAEL,KAAK,0BAA0B,EAChC,MAAM,sBAAsB,CAAC;AAE9B,wBAAgB,oBAAoB,CAClC,YAAY,EAAE,SAAS,MAAM,EAAE,EAC/B,qBAAqB,UAAO,UAuN7B;AAiBD,MAAM,MAAM,sBAAsB,GAAG;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,0BAA0B,CAAC;CAC7C,CAAC;AAMF,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,eAAe,GACtB,SAAS,sBAAsB,EAAE,CAEnC;AAED,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,eAAe,EACvB,MAAM,GAAE,GAAG,CAAC,MAAM,CAAa,GAC9B,IAAI,CAWN;AAED,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6FxB,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AAE9D,MAAM,MAAM,iCAAiC,GAC3C,eAAe,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC;AAUpC,QAAA,MAAM,wBAAwB;;;;;;cAA6B,CAAC;AAE5D,MAAM,MAAM,eAAe,GAAG,eAAe,GAAG;IAC9C,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;CACxD,CAAC;AAEF;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,QAAQ,CAAC,GAAG,EACjB,YAAY,EAAE,MAAM,EAAE,GACrB,OAAO,CAAC,eAAe,CAAC,CAsD1B"}
|
|
@@ -18,25 +18,43 @@ WITH published_columns AS (SELECT
|
|
|
18
18
|
pc.relnamespace::int8 AS "schemaOID" ,
|
|
19
19
|
pc.relname AS "name",
|
|
20
20
|
pc.relreplident AS "replicaIdentity",
|
|
21
|
+
-- The partitions that hold the rows of a partitioned table.
|
|
22
|
+
CASE WHEN pc.relkind = 'p' THEN ARRAY(
|
|
23
|
+
SELECT relid::oid::int8 FROM pg_partition_tree(pc.oid)
|
|
24
|
+
WHERE isleaf ORDER BY 1
|
|
25
|
+
) END AS "partitions",
|
|
21
26
|
attnum AS "pos",
|
|
22
27
|
attname AS "col",
|
|
23
|
-
|
|
28
|
+
-- A type name is a label on the replica, in which '|' delimits the attributes
|
|
29
|
+
-- of the type and '[]' marks an array.
|
|
30
|
+
replace(replace(COALESCE(elem_pt.typname, pt.typname), '|', '_'), '[]', '__') AS "type",
|
|
24
31
|
atttypid::int8 AS "typeOID",
|
|
25
32
|
pt.typtype,
|
|
26
33
|
elem_pt.typtype AS "elemTyptype",
|
|
27
34
|
coll.collisdeterministic AS "collationIsDeterministic",
|
|
28
35
|
NULLIF(atttypmod, -1) AS "maxLen",
|
|
29
|
-
attndims
|
|
36
|
+
-- attndims is only declarative: it is 0 for an array column made by
|
|
37
|
+
-- CREATE TABLE AS or declared as e.g. _int4.
|
|
38
|
+
CASE WHEN elem_pt.oid IS NULL THEN 0 ELSE GREATEST(attndims, 1) END AS "arrayDims",
|
|
30
39
|
attnotnull AS "notNull",
|
|
31
40
|
pg_get_expr(pd.adbin, pd.adrelid) as "dflt",
|
|
32
|
-
|
|
41
|
+
-- A primary key with a column that is not published, such as a generated
|
|
42
|
+
-- column, does not identify rows in the replication stream.
|
|
43
|
+
CASE WHEN EXISTS (
|
|
44
|
+
SELECT 1 FROM pg_attribute ka
|
|
45
|
+
WHERE ka.attrelid = pk.conrelid AND ka.attnum = ANY(pk.conkey) AND (
|
|
46
|
+
NOT ka.attname = ANY(pb.attnames) OR
|
|
47
|
+
(current_setting('server_version_num')::int < 160000 AND ka.attgenerated != ''))
|
|
48
|
+
) THEN NULL ELSE NULLIF(ARRAY_POSITION(conkey, attnum), -1) END AS "keyPos",
|
|
33
49
|
pb.rowfilter as "rowFilter",
|
|
34
50
|
pb.pubname as "publication"
|
|
35
51
|
FROM pg_attribute
|
|
36
52
|
JOIN pg_class pc ON pc.oid = attrelid
|
|
37
53
|
JOIN pg_namespace pns ON pns.oid = relnamespace
|
|
38
54
|
JOIN pg_type pt ON atttypid = pt.oid
|
|
39
|
-
|
|
55
|
+
-- Not pt.typelem, which is also set for types that aren't arrays, such as
|
|
56
|
+
-- point, name and int2vector.
|
|
57
|
+
LEFT JOIN pg_type elem_pt ON elem_pt.typarray = pt.oid
|
|
40
58
|
LEFT JOIN pg_collation coll ON coll.oid = pg_attribute.attcollation
|
|
41
59
|
JOIN pg_publication_tables as pb ON
|
|
42
60
|
pb.schemaname = nspname AND
|
|
@@ -54,14 +72,13 @@ tables AS (SELECT json_build_object(
|
|
|
54
72
|
'schemaOID', "schemaOID",
|
|
55
73
|
'name', "name",
|
|
56
74
|
'replicaIdentity', "replicaIdentity",
|
|
75
|
+
'partitions', "partitions",
|
|
57
76
|
'columns', json_object_agg(
|
|
58
77
|
DISTINCT
|
|
59
78
|
col,
|
|
60
79
|
jsonb_build_object(
|
|
61
80
|
'pos', "pos",
|
|
62
|
-
'dataType',
|
|
63
|
-
THEN "type"
|
|
64
|
-
ELSE substring("type" from 2) || repeat('[]', "arrayDims") END,
|
|
81
|
+
'dataType', "type" || repeat('[]', "arrayDims"),
|
|
65
82
|
'pgTypeClass', "typtype",
|
|
66
83
|
'elemPgTypeClass', "elemTyptype",
|
|
67
84
|
'typeOID', "typeOID",
|
|
@@ -87,7 +104,7 @@ tables AS (SELECT json_build_object(
|
|
|
87
104
|
jsonb_build_object('rowFilter', "rowFilter")
|
|
88
105
|
)
|
|
89
106
|
) AS "table" FROM published_columns
|
|
90
|
-
GROUP BY "schema", "schemaOID", "name", "oid", "replicaIdentity"),
|
|
107
|
+
GROUP BY "schema", "schemaOID", "name", "oid", "replicaIdentity", "partitions"),
|
|
91
108
|
|
|
92
109
|
indexed_columns AS (SELECT
|
|
93
110
|
pg_indexes.schemaname as "schema",
|
|
@@ -101,7 +118,19 @@ tables AS (SELECT json_build_object(
|
|
|
101
118
|
-- format compatible with older versions of the zero-cache, which
|
|
102
119
|
-- ignore "predicateSQL" and would otherwise create a full UNIQUE index
|
|
103
120
|
-- on the replica.
|
|
104
|
-
|
|
121
|
+
--
|
|
122
|
+
-- A deferrable unique constraint is reported as non-unique for a similar
|
|
123
|
+
-- reason: a transaction can pass through states that violate it, which
|
|
124
|
+
-- the replica would reject as they are replicated. The exception is a
|
|
125
|
+
-- primary key, which clients rely on.
|
|
126
|
+
--
|
|
127
|
+
-- So is a unique index over a type that the replica stores with less
|
|
128
|
+
-- precision, in which distinct values can be the same value on the
|
|
129
|
+
-- replica: numeric, a double there, and time, in milliseconds. The
|
|
130
|
+
-- exceptions are a primary key and a replica identity, which are keys.
|
|
131
|
+
(pg_index.indisunique AND pg_index.indpred IS NULL AND
|
|
132
|
+
(pg_index.indimmediate OR pg_index.indisprimary) AND
|
|
133
|
+
(pg_index.indisprimary OR pg_index.indisreplident OR NOT indexed.lossy)) as "unique",
|
|
105
134
|
pg_index.indisprimary as "isPrimaryKey",
|
|
106
135
|
pg_index.indisreplident as "isReplicaIdentity",
|
|
107
136
|
pg_index.indimmediate as "isImmediate",
|
|
@@ -116,7 +145,18 @@ tables AS (SELECT json_build_object(
|
|
|
116
145
|
pb.tablename = pg_indexes.tablename
|
|
117
146
|
JOIN pg_index ON pg_index.indexrelid = pc.oid
|
|
118
147
|
JOIN LATERAL (
|
|
119
|
-
SELECT array_agg(attname) as attnames, array_agg(attgenerated != '') as generated
|
|
148
|
+
SELECT array_agg(attname) as attnames, array_agg(attgenerated != '') as generated,
|
|
149
|
+
-- numeric, time and timetz, and the arrays of and domains over them
|
|
150
|
+
bool_or(EXISTS (
|
|
151
|
+
WITH RECURSIVE types(oid) AS (
|
|
152
|
+
SELECT atttypid
|
|
153
|
+
UNION ALL
|
|
154
|
+
SELECT CASE WHEN t.typtype = 'd' THEN t.typbasetype ELSE t.typelem END
|
|
155
|
+
FROM types JOIN pg_type t ON t.oid = types.oid
|
|
156
|
+
WHERE t.typtype = 'd' OR (t.typcategory = 'A' AND t.typelem != 0)
|
|
157
|
+
) SELECT 1 FROM types WHERE types.oid IN (1700, 1083, 1266)
|
|
158
|
+
)) as lossy
|
|
159
|
+
FROM pg_attribute
|
|
120
160
|
WHERE attrelid = pg_index.indrelid
|
|
121
161
|
AND attnum = ANY( (pg_index.indkey::smallint[] )[:pg_index.indnkeyatts - 1] )
|
|
122
162
|
) as indexed ON true
|
|
@@ -160,7 +200,10 @@ tables AS (SELECT json_build_object(
|
|
|
160
200
|
`;
|
|
161
201
|
}
|
|
162
202
|
var rawPublishedColumnSpec = publishedColumnSpec.extend({ collationIsDeterministic: valita_exports.boolean().nullable().optional() });
|
|
163
|
-
var rawPublishedTableSpec = publishedTableSpec.extend({
|
|
203
|
+
var rawPublishedTableSpec = publishedTableSpec.extend({
|
|
204
|
+
columns: valita_exports.record(rawPublishedColumnSpec),
|
|
205
|
+
partitions: valita_exports.array(valita_exports.number()).nullable().optional()
|
|
206
|
+
});
|
|
164
207
|
var rawPublishedIndexSpec = publishedIndexSpec.extend({ predicateSQL: valita_exports.string().nullable().optional() });
|
|
165
208
|
var skippedIndexDiagnostics = /* @__PURE__ */ new WeakMap();
|
|
166
209
|
function getSkippedIndexDiagnostics(schema) {
|
|
@@ -210,8 +253,9 @@ var publishedSchema = valita_exports.object({
|
|
|
210
253
|
});
|
|
211
254
|
} else indexes.push(index);
|
|
212
255
|
}
|
|
213
|
-
const tables = rawTables.map((table) => ({
|
|
256
|
+
const tables = rawTables.map(({ partitions, ...table }) => ({
|
|
214
257
|
...table,
|
|
258
|
+
...partitions ? { partitions } : {},
|
|
215
259
|
columns: Object.fromEntries(Object.entries(table.columns).map(([name, { collationIsDeterministic: _, ...column }]) => [name, column]))
|
|
216
260
|
}));
|
|
217
261
|
const zqlSpecs = computeZqlSpecsFromLiteSpecs(tables.map((t) => mapPostgresToLite(t)), indexes.map(mapPostgresToLiteIndex), { includeBackfillingColumns: true });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"published.js","names":["v","v.parse"],"sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/published.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {literal} from 'pg-format';\nimport type postgres from 'postgres';\nimport {assert} from '../../../../../../shared/src/asserts.ts';\nimport {BigIntJSON} from '../../../../../../shared/src/bigint-json.ts';\nimport {equals} from '../../../../../../shared/src/set-utils.ts';\nimport * as v from '../../../../../../shared/src/valita.ts';\nimport {computeZqlSpecsFromLiteSpecs} from '../../../../db/lite-tables.ts';\nimport {\n mapPostgresToLite,\n mapPostgresToLiteIndex,\n} from '../../../../db/pg-to-lite.ts';\nimport {\n publishedColumnSpec,\n publishedIndexSpec,\n publishedTableSpec,\n type PublishedIndexSpec,\n} from '../../../../db/specs.ts';\nimport {getOrCreateCounter} from '../../../../observability/metrics.ts';\nimport {liteTableName} from '../../../../types/names.ts';\nimport {\n translatePostgresIndexPredicate,\n type UnsupportedPredicateReason,\n} from './index-predicate.ts';\n\nexport function publishedSchemaQuery(\n publications: readonly string[],\n includePartialIndexes = true,\n) {\n // Notes:\n // * There's a bug in PG15 in which generated columns are incorrectly\n // included in pg_publication_tables.attnames, (even though the generated\n // column values are not be included in the replication stream).\n // The WHERE condition `attgenerated = ''` fixes this by explicitly excluding\n // generated columns from the list.\n return (\n /*sql*/ `\nWITH published_columns AS (SELECT \n pc.oid::int8 AS \"oid\",\n nspname AS \"schema\",\n pc.relnamespace::int8 AS \"schemaOID\" ,\n pc.relname AS \"name\", \n pc.relreplident AS \"replicaIdentity\",\n attnum AS \"pos\", \n attname AS \"col\", \n pt.typname AS \"type\", \n atttypid::int8 AS \"typeOID\", \n pt.typtype,\n elem_pt.typtype AS \"elemTyptype\",\n coll.collisdeterministic AS \"collationIsDeterministic\",\n NULLIF(atttypmod, -1) AS \"maxLen\", \n attndims \"arrayDims\", \n attnotnull AS \"notNull\",\n pg_get_expr(pd.adbin, pd.adrelid) as \"dflt\",\n NULLIF(ARRAY_POSITION(conkey, attnum), -1) AS \"keyPos\", \n pb.rowfilter as \"rowFilter\",\n pb.pubname as \"publication\"\nFROM pg_attribute\nJOIN pg_class pc ON pc.oid = attrelid\nJOIN pg_namespace pns ON pns.oid = relnamespace\nJOIN pg_type pt ON atttypid = pt.oid\nLEFT JOIN pg_type elem_pt ON elem_pt.oid = pt.typelem\nLEFT JOIN pg_collation coll ON coll.oid = pg_attribute.attcollation\nJOIN pg_publication_tables as pb ON \n pb.schemaname = nspname AND \n pb.tablename = pc.relname AND\n attname = ANY(pb.attnames)\nLEFT JOIN pg_constraint pk ON pk.contype = 'p' AND pk.connamespace = relnamespace AND pk.conrelid = attrelid\nLEFT JOIN pg_attrdef pd ON pd.adrelid = attrelid AND pd.adnum = attnum\nWHERE pb.pubname IN (${literal(publications)}) AND \n (current_setting('server_version_num')::int >= 160000 OR attgenerated = '')\nORDER BY nspname, pc.relname),\n\ntables AS (SELECT json_build_object(\n 'oid', \"oid\",\n 'schema', \"schema\", \n 'schemaOID', \"schemaOID\",\n 'name', \"name\", \n 'replicaIdentity', \"replicaIdentity\",\n 'columns', json_object_agg(\n DISTINCT\n col,\n jsonb_build_object(\n 'pos', \"pos\",\n 'dataType', CASE WHEN \"arrayDims\" = 0 \n THEN \"type\" \n ELSE substring(\"type\" from 2) || repeat('[]', \"arrayDims\") END,\n 'pgTypeClass', \"typtype\",\n 'elemPgTypeClass', \"elemTyptype\",\n 'typeOID', \"typeOID\",\n 'collationIsDeterministic', \"collationIsDeterministic\",\n -- https://stackoverflow.com/a/52376230\n 'characterMaximumLength', CASE WHEN \"typeOID\" = 1043 OR \"typeOID\" = 1042 \n THEN \"maxLen\" - 4 \n ELSE \"maxLen\" END,\n 'notNull', \"notNull\",\n 'dflt', \"dflt\"\n )\n ),\n 'primaryKey', ARRAY( SELECT json_object_keys(\n json_strip_nulls(\n json_object_agg(\n DISTINCT \"col\", \"keyPos\" ORDER BY \"keyPos\"\n )\n )\n )),\n 'publications', json_object_agg(\n DISTINCT \n \"publication\", \n jsonb_build_object('rowFilter', \"rowFilter\")\n )\n) AS \"table\" FROM published_columns \n GROUP BY \"schema\", \"schemaOID\", \"name\", \"oid\", \"replicaIdentity\"),\n ` +\n // Note: pg_attribute contains column names for tables and for indexes.\n // However, the latter does not get updated when a column in a table is\n // renamed.\n //\n // https://www.postgresql.org/message-id/5860814f-c91d-4ab0-b771-ded90d7b9c55%40www.fastmail.com\n //\n // To address this, the pg_attribute rows are looked up for the index's\n // table rather than the index itself, using the pg_index.indkey array\n // to determine the set and order of columns to include.\n //\n // Notes:\n // * The first bit of indoption is 1 for DESC and 0 for ASC:\n // https://github.com/postgres/postgres/blob/4e1fad37872e49a711adad5d9870516e5c71a375/src/include/catalog/pg_index.h#L89\n // * pg_index.indkey is an int2vector which is 0-based instead of 1-based.\n // * The additional check for attgenerated is required for the aforementioned\n // (in publishedTableQuery) bug in PG15 in which generated columns are\n // incorrectly included in pg_publication_tables.attnames\n /*sql*/ `\n indexed_columns AS (SELECT\n pg_indexes.schemaname as \"schema\",\n pg_indexes.tablename as \"tableName\",\n pg_indexes.indexname as \"name\",\n index_column.name as \"col\",\n CASE WHEN pg_index.indoption[index_column.pos-1] & 1 = 1 THEN 'DESC' ELSE 'ASC' END as \"dir\",\n -- Partial indexes are always reported as non-unique. Nothing on the\n -- replica relies on the uniqueness of a partial index (it cannot serve\n -- as a row key), and reporting it as non-unique keeps the ddl event\n -- format compatible with older versions of the zero-cache, which\n -- ignore \"predicateSQL\" and would otherwise create a full UNIQUE index\n -- on the replica.\n (pg_index.indisunique AND pg_index.indpred IS NULL) as \"unique\",\n pg_index.indisprimary as \"isPrimaryKey\",\n pg_index.indisreplident as \"isReplicaIdentity\",\n pg_index.indimmediate as \"isImmediate\",\n pg_get_expr(pg_index.indpred, pg_index.indrelid, false) as \"predicateSQL\"\n FROM pg_indexes\n JOIN pg_namespace ON pg_indexes.schemaname = pg_namespace.nspname\n JOIN pg_class pc ON\n pc.relname = pg_indexes.indexname\n AND pc.relnamespace = pg_namespace.oid\n JOIN pg_publication_tables as pb ON \n pb.schemaname = pg_indexes.schemaname AND \n pb.tablename = pg_indexes.tablename\n JOIN pg_index ON pg_index.indexrelid = pc.oid\n JOIN LATERAL (\n SELECT array_agg(attname) as attnames, array_agg(attgenerated != '') as generated FROM pg_attribute\n WHERE attrelid = pg_index.indrelid\n AND attnum = ANY( (pg_index.indkey::smallint[] )[:pg_index.indnkeyatts - 1] )\n ) as indexed ON true\n JOIN LATERAL (\n SELECT pg_attribute.attname as name, col.index_pos as pos\n FROM UNNEST( (pg_index.indkey::smallint[])[:pg_index.indnkeyatts - 1] ) \n WITH ORDINALITY as col(table_pos, index_pos)\n JOIN pg_attribute ON attrelid = pg_index.indrelid AND attnum = col.table_pos\n ) AS index_column ON true\n LEFT JOIN pg_constraint ON pg_constraint.conindid = pc.oid\n WHERE pb.pubname IN (${literal(publications)})\n AND pg_index.indexprs IS NULL\n AND (${includePartialIndexes} OR pg_index.indpred IS NULL)\n AND (pg_constraint.contype IS NULL OR pg_constraint.contype IN ('p', 'u'))\n AND indexed.attnames <@ pb.attnames\n AND (current_setting('server_version_num')::int >= 160000 OR false = ALL(indexed.generated))\n ORDER BY\n pg_indexes.schemaname,\n pg_indexes.tablename,\n pg_indexes.indexname,\n index_column.pos ASC),\n \n indexes AS (SELECT json_build_object(\n 'schema', \"schema\",\n 'tableName', \"tableName\",\n 'name', \"name\",\n 'unique', \"unique\",\n 'isPrimaryKey', \"isPrimaryKey\",\n 'isReplicaIdentity', \"isReplicaIdentity\",\n 'isImmediate', \"isImmediate\",\n 'predicateSQL', \"predicateSQL\",\n 'columns', json_object_agg(\"col\", \"dir\")\n ) AS index FROM indexed_columns \n GROUP BY \"schema\", \"tableName\", \"name\", \"unique\", \n \"isPrimaryKey\", \"isReplicaIdentity\", \"isImmediate\", \"predicateSQL\")\n\n SELECT json_build_object(\n 'tables', COALESCE((SELECT json_agg(\"table\") FROM tables), '[]'::json),\n 'indexes', COALESCE((SELECT json_agg(\"index\") FROM indexes), '[]'::json)\n ) as \"publishedSchema\"\n `\n );\n}\n\nconst rawPublishedColumnSpec = publishedColumnSpec.extend({\n collationIsDeterministic: v.boolean().nullable().optional(),\n});\n\nconst rawPublishedTableSpec = publishedTableSpec.extend({\n columns: v.record(rawPublishedColumnSpec),\n});\n\nconst rawPublishedIndexSpec = publishedIndexSpec.extend({\n predicateSQL: v.string().nullable().optional(),\n});\n\nexport type SkippedIndexDiagnostic = {\n readonly schema: string;\n readonly index: string;\n readonly predicate: string;\n readonly reason: UnsupportedPredicateReason;\n};\n\nconst skippedIndexDiagnostics = new WeakMap<\n object,\n readonly SkippedIndexDiagnostic[]\n>();\nexport function getSkippedIndexDiagnostics(\n schema: PublishedSchema,\n): readonly SkippedIndexDiagnostic[] {\n return skippedIndexDiagnostics.get(schema) ?? [];\n}\n\nexport function warnForSkippedIndexes(\n lc: LogContext,\n schema: PublishedSchema,\n warned: Set<string> = new Set(),\n): void {\n for (const diagnostic of getSkippedIndexDiagnostics(schema)) {\n const key = JSON.stringify(diagnostic);\n if (warned.has(key)) continue;\n warned.add(key);\n lc.warn?.('Skipping unsupported PostgreSQL partial index', diagnostic);\n getOrCreateCounter('replication', 'skipped_index', {\n description: 'Number of PostgreSQL indexes skipped during replication.',\n unit: '{index}',\n }).add(1, {reason: diagnostic.reason, partial: true});\n }\n}\n\nexport const publishedSchema = v\n .object({\n tables: v.array(rawPublishedTableSpec),\n indexes: v.array(rawPublishedIndexSpec),\n })\n .map(({tables: rawTables, indexes: rawIndexes}) => {\n const diagnostics: SkippedIndexDiagnostic[] = [];\n const indexes: PublishedIndexSpec[] = [];\n for (const rawIndex of rawIndexes) {\n const {predicateSQL, ...index} = rawIndex;\n if (predicateSQL !== null && predicateSQL !== undefined) {\n const table = rawTables.find(\n candidate =>\n candidate.schema === index.schema &&\n candidate.name === index.tableName,\n );\n const translation = table\n ? translatePostgresIndexPredicate(predicateSQL, table)\n : {supported: false as const, reason: 'unpublished-column' as const};\n if (!translation.supported) {\n diagnostics.push({\n schema: index.schema,\n index: index.name,\n predicate: predicateSQL,\n reason: translation.reason,\n });\n continue;\n }\n indexes.push({...index, predicate: translation.predicate});\n } else {\n indexes.push(index);\n }\n }\n\n const tables = rawTables.map(table => ({\n ...table,\n columns: Object.fromEntries(\n Object.entries(table.columns).map(\n ([name, {collationIsDeterministic: _, ...column}]) => [name, column],\n ),\n ),\n }));\n const zqlSpecs = computeZqlSpecsFromLiteSpecs(\n tables.map(t => mapPostgresToLite(t)),\n indexes.map(mapPostgresToLiteIndex),\n {includeBackfillingColumns: true},\n );\n const result = {\n indexes,\n\n // Denormalize the schema such that each `table` includes the\n // `replicaIdentityColumns` corresponding to the table's\n // replica identity and associated primary key or index.\n tables: tables.map(table => {\n const replicaIdentityColumns: string[] = [];\n switch (table.replicaIdentity) {\n case 'd':\n replicaIdentityColumns.push(...(table.primaryKey ?? []));\n break;\n case 'i':\n replicaIdentityColumns.push(\n ...Object.keys(\n indexes.find(\n ind =>\n ind.schema === table.schema &&\n ind.tableName === table.name &&\n ind.isReplicaIdentity,\n )?.columns ?? {},\n ),\n );\n break;\n case 'f': {\n // For the key columns of replica identity \"full\", use the columns\n // that the replicator/change-processor will end up using\n // (in #getKey()) as the row key.\n const zqlTable = zqlSpecs.get(liteTableName(table));\n // Note: There zql spec will be absent if the table is not synced,\n // e.g. if it has no suitable unique indexes.\n if (zqlTable) {\n replicaIdentityColumns.push(...zqlTable.tableSpec.primaryKey);\n }\n break;\n }\n }\n return {\n ...table,\n replicaIdentityColumns,\n };\n }),\n };\n skippedIndexDiagnostics.set(result, diagnostics);\n return result;\n });\n\nexport type PublishedSchema = v.Infer<typeof publishedSchema>;\n\nexport type PublishedTableWithReplicaIdentity =\n PublishedSchema['tables'][number];\n\nconst publicationSchema = v.object({\n pubname: v.string(),\n pubinsert: v.boolean(),\n pubupdate: v.boolean(),\n pubdelete: v.boolean(),\n pubtruncate: v.boolean(),\n});\n\nconst publicationsResultSchema = v.array(publicationSchema);\n\nexport type PublicationInfo = PublishedSchema & {\n publications: v.Infer<typeof publicationsResultSchema>;\n};\n\n/**\n * Retrieves published tables and columns.\n */\nexport async function getPublicationInfo(\n sql: postgres.Sql,\n publications: string[],\n): Promise<PublicationInfo> {\n const result = await sql.unsafe(/*sql*/ `\n SELECT \n schemaname AS \"schema\",\n tablename AS \"table\", \n json_object_agg(pubname, attnames) AS \"publications\"\n FROM pg_publication_tables pb\n WHERE pb.pubname IN (${literal(publications)})\n GROUP BY schemaname, tablename;\n\n SELECT ${Object.keys(publicationSchema.shape).join(\n ',',\n )} FROM pg_publication pb\n WHERE pb.pubname IN (${literal(publications)})\n ORDER BY pubname;\n\n ${publishedSchemaQuery(publications)};\n`);\n\n // The first query is used to check that tables in multiple publications\n // always publish the same set of columns.\n const publishedColumns = result[0] as {\n schema: string;\n table: string;\n publications: Record<string, string[]>;\n }[];\n for (const {table, publications} of publishedColumns) {\n let expected: Set<string>;\n Object.entries(publications).forEach(([_, columns], i) => {\n const cols = new Set(columns);\n if (i === 0) {\n expected = cols;\n } else if (!equals(expected, cols)) {\n throw new Error(\n `Table ${table} is exported with different columns: [${[\n ...expected,\n ]}] vs [${[...cols]}]`,\n );\n }\n });\n }\n\n assert(\n result[2][0].publishedSchema,\n () => `Invalid publishedSchema result ${BigIntJSON.stringify(result[2])}`,\n );\n\n const schema = v.parse(result[2][0].publishedSchema, publishedSchema);\n const info = {\n publications: v.parse(result[1], publicationsResultSchema),\n ...schema,\n };\n skippedIndexDiagnostics.set(info, getSkippedIndexDiagnostics(schema));\n return info;\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,SAAgB,qBACd,cACA,wBAAwB,MACxB;CAOA,OACU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAiCW,QAAQ,YAAY,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BAqGlB,QAAQ,YAAY,EAAE;;aAEpC,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BnC;AAEA,IAAM,yBAAyB,oBAAoB,OAAO,EACxD,0BAA0BA,eAAE,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,EAC5D,CAAC;AAED,IAAM,wBAAwB,mBAAmB,OAAO,EACtD,SAASA,eAAE,OAAO,sBAAsB,EAC1C,CAAC;AAED,IAAM,wBAAwB,mBAAmB,OAAO,EACtD,cAAcA,eAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,EAC/C,CAAC;AASD,IAAM,0CAA0B,IAAI,QAGlC;AACF,SAAgB,2BACd,QACmC;CACnC,OAAO,wBAAwB,IAAI,MAAM,KAAK,CAAC;AACjD;AAEA,SAAgB,sBACd,IACA,QACA,yBAAsB,IAAI,IAAI,GACxB;CACN,KAAK,MAAM,cAAc,2BAA2B,MAAM,GAAG;EAC3D,MAAM,MAAM,KAAK,UAAU,UAAU;EAC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AAM;GACxD,MAAM,OAAO,IAAI,IAAI,OAAO;GAC5B,IAAI,MAAM,GACR,WAAW;QACN,IAAI,CAAC,OAAO,UAAU,IAAI,GAC/B,MAAM,IAAI,MACR,SAAS,MAAM,wCAAwC,CACrD,GAAG,QACL,EAAE,QAAQ,CAAC,GAAG,IAAI,EAAE,EACtB;EAEJ,CAAC;CACH;CAEA,OACE,OAAO,EAAE,CAAC,EAAE,CAAC,uBACP,kCAAkC,WAAW,UAAU,OAAO,EAAE,GACxE;CAEA,MAAM,SAASC,MAAQ,OAAO,EAAE,CAAC,EAAE,CAAC,iBAAiB,eAAe;CACpE,MAAM,OAAO;EACX,cAAcA,MAAQ,OAAO,IAAI,wBAAwB;EACzD,GAAG;CACL;CACA,wBAAwB,IAAI,MAAM,2BAA2B,MAAM,CAAC;CACpE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"published.js","names":["v","v.parse"],"sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/published.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {literal} from 'pg-format';\nimport type postgres from 'postgres';\nimport {assert} from '../../../../../../shared/src/asserts.ts';\nimport {BigIntJSON} from '../../../../../../shared/src/bigint-json.ts';\nimport {equals} from '../../../../../../shared/src/set-utils.ts';\nimport * as v from '../../../../../../shared/src/valita.ts';\nimport {computeZqlSpecsFromLiteSpecs} from '../../../../db/lite-tables.ts';\nimport {\n mapPostgresToLite,\n mapPostgresToLiteIndex,\n} from '../../../../db/pg-to-lite.ts';\nimport {\n publishedColumnSpec,\n publishedIndexSpec,\n publishedTableSpec,\n type PublishedIndexSpec,\n} from '../../../../db/specs.ts';\nimport {getOrCreateCounter} from '../../../../observability/metrics.ts';\nimport {liteTableName} from '../../../../types/names.ts';\nimport {\n translatePostgresIndexPredicate,\n type UnsupportedPredicateReason,\n} from './index-predicate.ts';\n\nexport function publishedSchemaQuery(\n publications: readonly string[],\n includePartialIndexes = true,\n) {\n // Notes:\n // * There's a bug in PG15 in which generated columns are incorrectly\n // included in pg_publication_tables.attnames, (even though the generated\n // column values are not be included in the replication stream).\n // The WHERE condition `attgenerated = ''` fixes this by explicitly excluding\n // generated columns from the list.\n return (\n /*sql*/ `\nWITH published_columns AS (SELECT \n pc.oid::int8 AS \"oid\",\n nspname AS \"schema\",\n pc.relnamespace::int8 AS \"schemaOID\" ,\n pc.relname AS \"name\", \n pc.relreplident AS \"replicaIdentity\",\n -- The partitions that hold the rows of a partitioned table.\n CASE WHEN pc.relkind = 'p' THEN ARRAY(\n SELECT relid::oid::int8 FROM pg_partition_tree(pc.oid)\n WHERE isleaf ORDER BY 1\n ) END AS \"partitions\",\n attnum AS \"pos\", \n attname AS \"col\", \n -- A type name is a label on the replica, in which '|' delimits the attributes\n -- of the type and '[]' marks an array.\n replace(replace(COALESCE(elem_pt.typname, pt.typname), '|', '_'), '[]', '__') AS \"type\",\n atttypid::int8 AS \"typeOID\", \n pt.typtype,\n elem_pt.typtype AS \"elemTyptype\",\n coll.collisdeterministic AS \"collationIsDeterministic\",\n NULLIF(atttypmod, -1) AS \"maxLen\", \n -- attndims is only declarative: it is 0 for an array column made by\n -- CREATE TABLE AS or declared as e.g. _int4.\n CASE WHEN elem_pt.oid IS NULL THEN 0 ELSE GREATEST(attndims, 1) END AS \"arrayDims\",\n attnotnull AS \"notNull\",\n pg_get_expr(pd.adbin, pd.adrelid) as \"dflt\",\n -- A primary key with a column that is not published, such as a generated\n -- column, does not identify rows in the replication stream.\n CASE WHEN EXISTS (\n SELECT 1 FROM pg_attribute ka\n WHERE ka.attrelid = pk.conrelid AND ka.attnum = ANY(pk.conkey) AND (\n NOT ka.attname = ANY(pb.attnames) OR\n (current_setting('server_version_num')::int < 160000 AND ka.attgenerated != ''))\n ) THEN NULL ELSE NULLIF(ARRAY_POSITION(conkey, attnum), -1) END AS \"keyPos\", \n pb.rowfilter as \"rowFilter\",\n pb.pubname as \"publication\"\nFROM pg_attribute\nJOIN pg_class pc ON pc.oid = attrelid\nJOIN pg_namespace pns ON pns.oid = relnamespace\nJOIN pg_type pt ON atttypid = pt.oid\n-- Not pt.typelem, which is also set for types that aren't arrays, such as\n-- point, name and int2vector.\nLEFT JOIN pg_type elem_pt ON elem_pt.typarray = pt.oid\nLEFT JOIN pg_collation coll ON coll.oid = pg_attribute.attcollation\nJOIN pg_publication_tables as pb ON \n pb.schemaname = nspname AND \n pb.tablename = pc.relname AND\n attname = ANY(pb.attnames)\nLEFT JOIN pg_constraint pk ON pk.contype = 'p' AND pk.connamespace = relnamespace AND pk.conrelid = attrelid\nLEFT JOIN pg_attrdef pd ON pd.adrelid = attrelid AND pd.adnum = attnum\nWHERE pb.pubname IN (${literal(publications)}) AND \n (current_setting('server_version_num')::int >= 160000 OR attgenerated = '')\nORDER BY nspname, pc.relname),\n\ntables AS (SELECT json_build_object(\n 'oid', \"oid\",\n 'schema', \"schema\", \n 'schemaOID', \"schemaOID\",\n 'name', \"name\", \n 'replicaIdentity', \"replicaIdentity\",\n 'partitions', \"partitions\",\n 'columns', json_object_agg(\n DISTINCT\n col,\n jsonb_build_object(\n 'pos', \"pos\",\n 'dataType', \"type\" || repeat('[]', \"arrayDims\"),\n 'pgTypeClass', \"typtype\",\n 'elemPgTypeClass', \"elemTyptype\",\n 'typeOID', \"typeOID\",\n 'collationIsDeterministic', \"collationIsDeterministic\",\n -- https://stackoverflow.com/a/52376230\n 'characterMaximumLength', CASE WHEN \"typeOID\" = 1043 OR \"typeOID\" = 1042 \n THEN \"maxLen\" - 4 \n ELSE \"maxLen\" END,\n 'notNull', \"notNull\",\n 'dflt', \"dflt\"\n )\n ),\n 'primaryKey', ARRAY( SELECT json_object_keys(\n json_strip_nulls(\n json_object_agg(\n DISTINCT \"col\", \"keyPos\" ORDER BY \"keyPos\"\n )\n )\n )),\n 'publications', json_object_agg(\n DISTINCT \n \"publication\", \n jsonb_build_object('rowFilter', \"rowFilter\")\n )\n) AS \"table\" FROM published_columns \n GROUP BY \"schema\", \"schemaOID\", \"name\", \"oid\", \"replicaIdentity\", \"partitions\"),\n ` +\n // Note: pg_attribute contains column names for tables and for indexes.\n // However, the latter does not get updated when a column in a table is\n // renamed.\n //\n // https://www.postgresql.org/message-id/5860814f-c91d-4ab0-b771-ded90d7b9c55%40www.fastmail.com\n //\n // To address this, the pg_attribute rows are looked up for the index's\n // table rather than the index itself, using the pg_index.indkey array\n // to determine the set and order of columns to include.\n //\n // Notes:\n // * The first bit of indoption is 1 for DESC and 0 for ASC:\n // https://github.com/postgres/postgres/blob/4e1fad37872e49a711adad5d9870516e5c71a375/src/include/catalog/pg_index.h#L89\n // * pg_index.indkey is an int2vector which is 0-based instead of 1-based.\n // * The additional check for attgenerated is required for the aforementioned\n // (in publishedTableQuery) bug in PG15 in which generated columns are\n // incorrectly included in pg_publication_tables.attnames\n /*sql*/ `\n indexed_columns AS (SELECT\n pg_indexes.schemaname as \"schema\",\n pg_indexes.tablename as \"tableName\",\n pg_indexes.indexname as \"name\",\n index_column.name as \"col\",\n CASE WHEN pg_index.indoption[index_column.pos-1] & 1 = 1 THEN 'DESC' ELSE 'ASC' END as \"dir\",\n -- Partial indexes are always reported as non-unique. Nothing on the\n -- replica relies on the uniqueness of a partial index (it cannot serve\n -- as a row key), and reporting it as non-unique keeps the ddl event\n -- format compatible with older versions of the zero-cache, which\n -- ignore \"predicateSQL\" and would otherwise create a full UNIQUE index\n -- on the replica.\n --\n -- A deferrable unique constraint is reported as non-unique for a similar\n -- reason: a transaction can pass through states that violate it, which\n -- the replica would reject as they are replicated. The exception is a\n -- primary key, which clients rely on.\n --\n -- So is a unique index over a type that the replica stores with less\n -- precision, in which distinct values can be the same value on the\n -- replica: numeric, a double there, and time, in milliseconds. The\n -- exceptions are a primary key and a replica identity, which are keys.\n (pg_index.indisunique AND pg_index.indpred IS NULL AND\n (pg_index.indimmediate OR pg_index.indisprimary) AND\n (pg_index.indisprimary OR pg_index.indisreplident OR NOT indexed.lossy)) as \"unique\",\n pg_index.indisprimary as \"isPrimaryKey\",\n pg_index.indisreplident as \"isReplicaIdentity\",\n pg_index.indimmediate as \"isImmediate\",\n pg_get_expr(pg_index.indpred, pg_index.indrelid, false) as \"predicateSQL\"\n FROM pg_indexes\n JOIN pg_namespace ON pg_indexes.schemaname = pg_namespace.nspname\n JOIN pg_class pc ON\n pc.relname = pg_indexes.indexname\n AND pc.relnamespace = pg_namespace.oid\n JOIN pg_publication_tables as pb ON \n pb.schemaname = pg_indexes.schemaname AND \n pb.tablename = pg_indexes.tablename\n JOIN pg_index ON pg_index.indexrelid = pc.oid\n JOIN LATERAL (\n SELECT array_agg(attname) as attnames, array_agg(attgenerated != '') as generated,\n -- numeric, time and timetz, and the arrays of and domains over them\n bool_or(EXISTS (\n WITH RECURSIVE types(oid) AS (\n SELECT atttypid\n UNION ALL\n SELECT CASE WHEN t.typtype = 'd' THEN t.typbasetype ELSE t.typelem END\n FROM types JOIN pg_type t ON t.oid = types.oid\n WHERE t.typtype = 'd' OR (t.typcategory = 'A' AND t.typelem != 0)\n ) SELECT 1 FROM types WHERE types.oid IN (1700, 1083, 1266)\n )) as lossy\n FROM pg_attribute\n WHERE attrelid = pg_index.indrelid\n AND attnum = ANY( (pg_index.indkey::smallint[] )[:pg_index.indnkeyatts - 1] )\n ) as indexed ON true\n JOIN LATERAL (\n SELECT pg_attribute.attname as name, col.index_pos as pos\n FROM UNNEST( (pg_index.indkey::smallint[])[:pg_index.indnkeyatts - 1] ) \n WITH ORDINALITY as col(table_pos, index_pos)\n JOIN pg_attribute ON attrelid = pg_index.indrelid AND attnum = col.table_pos\n ) AS index_column ON true\n LEFT JOIN pg_constraint ON pg_constraint.conindid = pc.oid\n WHERE pb.pubname IN (${literal(publications)})\n AND pg_index.indexprs IS NULL\n AND (${includePartialIndexes} OR pg_index.indpred IS NULL)\n AND (pg_constraint.contype IS NULL OR pg_constraint.contype IN ('p', 'u'))\n AND indexed.attnames <@ pb.attnames\n AND (current_setting('server_version_num')::int >= 160000 OR false = ALL(indexed.generated))\n ORDER BY\n pg_indexes.schemaname,\n pg_indexes.tablename,\n pg_indexes.indexname,\n index_column.pos ASC),\n \n indexes AS (SELECT json_build_object(\n 'schema', \"schema\",\n 'tableName', \"tableName\",\n 'name', \"name\",\n 'unique', \"unique\",\n 'isPrimaryKey', \"isPrimaryKey\",\n 'isReplicaIdentity', \"isReplicaIdentity\",\n 'isImmediate', \"isImmediate\",\n 'predicateSQL', \"predicateSQL\",\n 'columns', json_object_agg(\"col\", \"dir\")\n ) AS index FROM indexed_columns \n GROUP BY \"schema\", \"tableName\", \"name\", \"unique\", \n \"isPrimaryKey\", \"isReplicaIdentity\", \"isImmediate\", \"predicateSQL\")\n\n SELECT json_build_object(\n 'tables', COALESCE((SELECT json_agg(\"table\") FROM tables), '[]'::json),\n 'indexes', COALESCE((SELECT json_agg(\"index\") FROM indexes), '[]'::json)\n ) as \"publishedSchema\"\n `\n );\n}\n\nconst rawPublishedColumnSpec = publishedColumnSpec.extend({\n collationIsDeterministic: v.boolean().nullable().optional(),\n});\n\nconst rawPublishedTableSpec = publishedTableSpec.extend({\n columns: v.record(rawPublishedColumnSpec),\n // The OIDs of the partitions that hold the rows of a partitioned table.\n // Absent in schemas stored before this was reported.\n partitions: v.array(v.number()).nullable().optional(),\n});\n\nconst rawPublishedIndexSpec = publishedIndexSpec.extend({\n predicateSQL: v.string().nullable().optional(),\n});\n\nexport type SkippedIndexDiagnostic = {\n readonly schema: string;\n readonly index: string;\n readonly predicate: string;\n readonly reason: UnsupportedPredicateReason;\n};\n\nconst skippedIndexDiagnostics = new WeakMap<\n object,\n readonly SkippedIndexDiagnostic[]\n>();\nexport function getSkippedIndexDiagnostics(\n schema: PublishedSchema,\n): readonly SkippedIndexDiagnostic[] {\n return skippedIndexDiagnostics.get(schema) ?? [];\n}\n\nexport function warnForSkippedIndexes(\n lc: LogContext,\n schema: PublishedSchema,\n warned: Set<string> = new Set(),\n): void {\n for (const diagnostic of getSkippedIndexDiagnostics(schema)) {\n const key = JSON.stringify(diagnostic);\n if (warned.has(key)) continue;\n warned.add(key);\n lc.warn?.('Skipping unsupported PostgreSQL partial index', diagnostic);\n getOrCreateCounter('replication', 'skipped_index', {\n description: 'Number of PostgreSQL indexes skipped during replication.',\n unit: '{index}',\n }).add(1, {reason: diagnostic.reason, partial: true});\n }\n}\n\nexport const publishedSchema = v\n .object({\n tables: v.array(rawPublishedTableSpec),\n indexes: v.array(rawPublishedIndexSpec),\n })\n .map(({tables: rawTables, indexes: rawIndexes}) => {\n const diagnostics: SkippedIndexDiagnostic[] = [];\n const indexes: PublishedIndexSpec[] = [];\n for (const rawIndex of rawIndexes) {\n const {predicateSQL, ...index} = rawIndex;\n if (predicateSQL !== null && predicateSQL !== undefined) {\n const table = rawTables.find(\n candidate =>\n candidate.schema === index.schema &&\n candidate.name === index.tableName,\n );\n const translation = table\n ? translatePostgresIndexPredicate(predicateSQL, table)\n : {supported: false as const, reason: 'unpublished-column' as const};\n if (!translation.supported) {\n diagnostics.push({\n schema: index.schema,\n index: index.name,\n predicate: predicateSQL,\n reason: translation.reason,\n });\n continue;\n }\n indexes.push({...index, predicate: translation.predicate});\n } else {\n indexes.push(index);\n }\n }\n\n const tables = rawTables.map(({partitions, ...table}) => ({\n ...table,\n ...(partitions ? {partitions} : {}),\n columns: Object.fromEntries(\n Object.entries(table.columns).map(\n ([name, {collationIsDeterministic: _, ...column}]) => [name, column],\n ),\n ),\n }));\n const zqlSpecs = computeZqlSpecsFromLiteSpecs(\n tables.map(t => mapPostgresToLite(t)),\n indexes.map(mapPostgresToLiteIndex),\n {includeBackfillingColumns: true},\n );\n const result = {\n indexes,\n\n // Denormalize the schema such that each `table` includes the\n // `replicaIdentityColumns` corresponding to the table's\n // replica identity and associated primary key or index.\n tables: tables.map(table => {\n const replicaIdentityColumns: string[] = [];\n switch (table.replicaIdentity) {\n case 'd':\n replicaIdentityColumns.push(...(table.primaryKey ?? []));\n break;\n case 'i':\n replicaIdentityColumns.push(\n ...Object.keys(\n indexes.find(\n ind =>\n ind.schema === table.schema &&\n ind.tableName === table.name &&\n ind.isReplicaIdentity,\n )?.columns ?? {},\n ),\n );\n break;\n case 'f': {\n // For the key columns of replica identity \"full\", use the columns\n // that the replicator/change-processor will end up using\n // (in #getKey()) as the row key.\n const zqlTable = zqlSpecs.get(liteTableName(table));\n // Note: There zql spec will be absent if the table is not synced,\n // e.g. if it has no suitable unique indexes.\n if (zqlTable) {\n replicaIdentityColumns.push(...zqlTable.tableSpec.primaryKey);\n }\n break;\n }\n }\n return {\n ...table,\n replicaIdentityColumns,\n };\n }),\n };\n skippedIndexDiagnostics.set(result, diagnostics);\n return result;\n });\n\nexport type PublishedSchema = v.Infer<typeof publishedSchema>;\n\nexport type PublishedTableWithReplicaIdentity =\n PublishedSchema['tables'][number];\n\nconst publicationSchema = v.object({\n pubname: v.string(),\n pubinsert: v.boolean(),\n pubupdate: v.boolean(),\n pubdelete: v.boolean(),\n pubtruncate: v.boolean(),\n});\n\nconst publicationsResultSchema = v.array(publicationSchema);\n\nexport type PublicationInfo = PublishedSchema & {\n publications: v.Infer<typeof publicationsResultSchema>;\n};\n\n/**\n * Retrieves published tables and columns.\n */\nexport async function getPublicationInfo(\n sql: postgres.Sql,\n publications: string[],\n): Promise<PublicationInfo> {\n const result = await sql.unsafe(/*sql*/ `\n SELECT \n schemaname AS \"schema\",\n tablename AS \"table\", \n json_object_agg(pubname, attnames) AS \"publications\"\n FROM pg_publication_tables pb\n WHERE pb.pubname IN (${literal(publications)})\n GROUP BY schemaname, tablename;\n\n SELECT ${Object.keys(publicationSchema.shape).join(\n ',',\n )} FROM pg_publication pb\n WHERE pb.pubname IN (${literal(publications)})\n ORDER BY pubname;\n\n ${publishedSchemaQuery(publications)};\n`);\n\n // The first query is used to check that tables in multiple publications\n // always publish the same set of columns.\n const publishedColumns = result[0] as {\n schema: string;\n table: string;\n publications: Record<string, string[]>;\n }[];\n for (const {table, publications} of publishedColumns) {\n let expected: Set<string>;\n Object.entries(publications).forEach(([_, columns], i) => {\n const cols = new Set(columns);\n if (i === 0) {\n expected = cols;\n } else if (!equals(expected, cols)) {\n throw new Error(\n `Table ${table} is exported with different columns: [${[\n ...expected,\n ]}] vs [${[...cols]}]`,\n );\n }\n });\n }\n\n assert(\n result[2][0].publishedSchema,\n () => `Invalid publishedSchema result ${BigIntJSON.stringify(result[2])}`,\n );\n\n const schema = v.parse(result[2][0].publishedSchema, publishedSchema);\n const info = {\n publications: v.parse(result[1], publicationsResultSchema),\n ...schema,\n };\n skippedIndexDiagnostics.set(info, getSkippedIndexDiagnostics(schema));\n return info;\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,SAAgB,qBACd,cACA,wBAAwB,MACxB;CAOA,OACU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAmDW,QAAQ,YAAY,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BA2HlB,QAAQ,YAAY,EAAE;;aAEpC,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BnC;AAEA,IAAM,yBAAyB,oBAAoB,OAAO,EACxD,0BAA0BA,eAAE,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,EAC5D,CAAC;AAED,IAAM,wBAAwB,mBAAmB,OAAO;CACtD,SAASA,eAAE,OAAO,sBAAsB;CAGxC,YAAYA,eAAE,MAAMA,eAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;AACtD,CAAC;AAED,IAAM,wBAAwB,mBAAmB,OAAO,EACtD,cAAcA,eAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,EAC/C,CAAC;AASD,IAAM,0CAA0B,IAAI,QAGlC;AACF,SAAgB,2BACd,QACmC;CACnC,OAAO,wBAAwB,IAAI,MAAM,KAAK,CAAC;AACjD;AAEA,SAAgB,sBACd,IACA,QAC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AqB,YAAY,EAAE;CACtC;CAIC,MAAM,mBAAmB,OAAO;CAKhC,KAAK,MAAM,EAAC,OAAO,kBAAiB,kBAAkB;EACpD,IAAI;EACJ,OAAO,QAAQ,YAAY,CAAC,CAAC,SAAS,CAAC,GAAG,UAAU,MAAM;GACxD,MAAM,OAAO,IAAI,IAAI,OAAO;GAC5B,IAAI,MAAM,GACR,WAAW;QACN,IAAI,CAAC,OAAO,UAAU,IAAI,GAC/B,MAAM,IAAI,MACR,SAAS,MAAM,wCAAwC,CACrD,GAAG,QACL,EAAE,QAAQ,CAAC,GAAG,IAAI,EAAE,EACtB;EAEJ,CAAC;CACH;CAEA,OACE,OAAO,EAAE,CAAC,EAAE,CAAC,uBACP,kCAAkC,WAAW,UAAU,OAAO,EAAE,GACxE;CAEA,MAAM,SAASC,MAAQ,OAAO,EAAE,CAAC,EAAE,CAAC,iBAAiB,eAAe;CACpE,MAAM,OAAO;EACX,cAAcA,MAAQ,OAAO,IAAI,wBAAwB;EACzD,GAAG;CACL;CACA,wBAAwB,IAAI,MAAM,2BAA2B,MAAM,CAAC;CACpE,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shard.d.ts","sourceRoot":"","sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/shard.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,EAGL,KAAK,UAAU,EAChB,MAAM,6CAA6C,CAAC;AACrD,OAAO,KAAK,CAAC,MAAM,wCAAwC,CAAC;AAE5D,OAAO,KAAK,EAAC,UAAU,EAAE,mBAAmB,EAAC,MAAM,yBAAyB,CAAC;AAC7E,OAAO,KAAK,EAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAC,MAAM,6BAA6B,CAAC;AAO7E,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,eAAe,EACrB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAGL,KAAK,YAAY,EAClB,MAAM,yBAAyB,CAAC;AASjC;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAY1D;AAED,wBAAgB,yBAAyB,CAAC,EAAC,KAAK,EAAC,EAAE,KAAK,UAEvD;AAED,wBAAgB,qBAAqB,CAAC,EAAC,KAAK,EAAE,QAAQ,EAAC,EAAE,OAAO,UAE/D;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,UAGnD;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,UAIvD;AAMD,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,GAAG,MAAM,UAGzB;AAoCD,wBAAsB,kBAAkB,CAAC,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,iBAEpE;AAED,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,UASvD;AAED;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,UASzD;AAED,eAAO,MAAM,kBAAkB,gBAAgB,CAAC;AAEhD,wBAAgB,UAAU,CACxB,WAAW,EAAE,WAAW,EACxB,mBAAmB,EAAE,MAAM,GAC1B,MAAM,CA0DR;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAYzE;AAED,QAAA,MAAM,yBAAyB;;;;;aAQ7B,CAAC;AAEH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,yBAAyB,CAAC,CAAC;AA2B5E,QAAA,MAAM,aAAa;;;;;;;;;;;;;;IAhBjB;;;;;;OAMG
|
|
1
|
+
{"version":3,"file":"shard.d.ts","sourceRoot":"","sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/shard.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAA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AoB,CAClC,EAAE,EAAE,UAAU,EACd,SAAS,EAAE,eAAe,QAmB3B;AAED,KAAK,iBAAiB,GAAG;IACvB,KAAK,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtD,CAAC;AAEF,wBAAgB,4CAA4C,CAC1D,IAAI,EAAE,eAAe,GACpB,iBAAiB,GAAG,SAAS,CAsF/B"}
|
|
@@ -6,7 +6,7 @@ import { id } from "../../../../types/sql.js";
|
|
|
6
6
|
import { getPublicationInfo, publishedSchema } from "./published.js";
|
|
7
7
|
import { createEventFunctionStatements, createEventTriggerStatements } from "./ddl.js";
|
|
8
8
|
import { replicaStageSchema } from "./replica-stage-enum.js";
|
|
9
|
-
import { validate } from "./validation.js";
|
|
9
|
+
import { validate, validateRelationNames } from "./validation.js";
|
|
10
10
|
import postgres from "postgres";
|
|
11
11
|
import { PG_INSUFFICIENT_PRIVILEGE } from "@drdgvhbh/postgres-error-codes";
|
|
12
12
|
import { literal } from "pg-format";
|
|
@@ -460,23 +460,46 @@ function validatePublications(lc, published) {
|
|
|
460
460
|
if (!pub.pubinsert || !pub.pubupdate || !pub.pubdelete || !pub.pubtruncate) throw new Error(`PUBLICATION ${pub.pubname} must publish insert, update, delete, and truncate`);
|
|
461
461
|
});
|
|
462
462
|
published.tables.forEach((table) => validate(lc, table));
|
|
463
|
+
validateRelationNames(published);
|
|
463
464
|
}
|
|
464
465
|
function replicaIdentitiesForTablesWithoutPrimaryKeys(pubs) {
|
|
465
466
|
const replicaIdentities = [];
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
467
|
+
const withoutIndex = [];
|
|
468
|
+
for (const table of pubs.tables) {
|
|
469
|
+
if (table.primaryKey?.length) continue;
|
|
470
|
+
if (table.replicaIdentity === "f") withoutIndex.push(...table.partitions ?? []);
|
|
471
|
+
else if (table.replicaIdentity === "d") {
|
|
472
|
+
const numIdentities = replicaIdentities.length;
|
|
473
|
+
const { schema, name: tableName } = table;
|
|
474
|
+
for (const { columns, name: indexName } of pubs.indexes.filter((idx) => idx.schema === schema && idx.tableName === tableName && idx.unique && idx.isImmediate && idx.predicate === void 0)) {
|
|
475
|
+
if (Object.keys(columns).some((col) => !table.columns[col].notNull)) continue;
|
|
476
|
+
replicaIdentities.push({
|
|
477
|
+
schema,
|
|
478
|
+
tableName,
|
|
479
|
+
indexName
|
|
480
|
+
});
|
|
481
|
+
break;
|
|
482
|
+
}
|
|
483
|
+
if (replicaIdentities.length === numIdentities) withoutIndex.push(table.oid, ...table.partitions ?? []);
|
|
476
484
|
}
|
|
477
485
|
}
|
|
478
|
-
if (replicaIdentities.length === 0) return;
|
|
486
|
+
if (replicaIdentities.length === 0 && withoutIndex.length === 0) return;
|
|
479
487
|
return { apply: async (lc, sql) => {
|
|
488
|
+
const generatedKeys = withoutIndex.length ? await sql`
|
|
489
|
+
SELECT ns.nspname AS "schema", c.relname AS "tableName"
|
|
490
|
+
FROM pg_class c JOIN pg_namespace ns ON ns.oid = c.relnamespace
|
|
491
|
+
WHERE c.oid = ANY (${withoutIndex}::oid[]) AND c.relreplident = 'd'
|
|
492
|
+
AND EXISTS (
|
|
493
|
+
SELECT 1 FROM pg_index i
|
|
494
|
+
JOIN pg_attribute a
|
|
495
|
+
ON a.attrelid = i.indrelid AND a.attnum = ANY (i.indkey)
|
|
496
|
+
WHERE i.indrelid = c.oid AND i.indisprimary
|
|
497
|
+
AND a.attgenerated != '')` : [];
|
|
498
|
+
for (const { schema, tableName } of generatedKeys) {
|
|
499
|
+
lc.info?.(`setting REPLICA IDENTITY FULL for "${tableName}", which has a generated column in its primary key`);
|
|
500
|
+
await sql`
|
|
501
|
+
ALTER TABLE ${sql(schema)}.${sql(tableName)} REPLICA IDENTITY FULL`;
|
|
502
|
+
}
|
|
480
503
|
for (const { schema, tableName, indexName } of replicaIdentities) {
|
|
481
504
|
lc.info?.(`setting "${indexName}" as the REPLICA IDENTITY for "${tableName}"`);
|
|
482
505
|
await sql`
|