From 3b45219bbdde415e9035f42c002cbbc14932a54d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=85=E5=BF=B5?= Date: Tue, 20 Oct 2026 19:36:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(db):=200002=20=E5=86=85=E5=AE=B9=E5=9F=9F?= =?UTF-8?q?=E2=80=94=E2=80=94entry/locale/revision=20+=20=E4=BF=AE?= =?UTF-8?q?=E8=AE=A2=E4=B8=8D=E5=8F=AF=E5=8F=98=20+=20=E5=9B=9E=E5=A1=AB?= =?UTF-8?q?=20content=5Fentry=20FK?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Code --- .../drizzle/0002_fancy_silver_centurion.sql | 55 + apps/api/drizzle/meta/0002_snapshot.json | 1106 +++++++++++++++++ apps/api/drizzle/meta/_journal.json | 7 + apps/api/src/db/schema.ts | 55 +- tests/integration/db.content.test.ts | 127 ++ 5 files changed, 1347 insertions(+), 3 deletions(-) create mode 100644 apps/api/drizzle/0002_fancy_silver_centurion.sql create mode 100644 apps/api/drizzle/meta/0002_snapshot.json create mode 100644 tests/integration/db.content.test.ts diff --git a/apps/api/drizzle/0002_fancy_silver_centurion.sql b/apps/api/drizzle/0002_fancy_silver_centurion.sql new file mode 100644 index 0000000..c589ea9 --- /dev/null +++ b/apps/api/drizzle/0002_fancy_silver_centurion.sql @@ -0,0 +1,55 @@ +CREATE TYPE "public"."content_lifecycle_status" AS ENUM('active', 'archived');--> statement-breakpoint +CREATE TYPE "public"."revision_source_kind" AS ENUM('import', 'manual', 'restore');--> statement-breakpoint +CREATE TABLE "content_entries" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "site_id" uuid NOT NULL, + "type_key" text NOT NULL, + "lifecycle_status" "content_lifecycle_status" NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "content_revisions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "site_id" uuid NOT NULL, + "content_entry_id" uuid NOT NULL, + "locale" text NOT NULL, + "schema_version" integer NOT NULL, + "data" jsonb NOT NULL, + "checksum" text NOT NULL, + "source_kind" "revision_source_kind" NOT NULL, + "source_record_id" uuid, + "import_job_id" uuid, + "overridden_fields" jsonb DEFAULT '[]'::jsonb NOT NULL, + "created_by" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "entry_locales" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "site_id" uuid NOT NULL, + "content_entry_id" uuid NOT NULL, + "locale" text NOT NULL, + "slug" text NOT NULL, + "current_revision_id" uuid, + "published_revision_id" uuid, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "content_entries" ADD CONSTRAINT "content_entries_site_id_sites_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "content_revisions" ADD CONSTRAINT "content_revisions_site_id_sites_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "content_revisions" ADD CONSTRAINT "content_revisions_content_entry_id_content_entries_id_fk" FOREIGN KEY ("content_entry_id") REFERENCES "public"."content_entries"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "content_revisions" ADD CONSTRAINT "content_revisions_import_job_id_import_jobs_id_fk" FOREIGN KEY ("import_job_id") REFERENCES "public"."import_jobs"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "entry_locales" ADD CONSTRAINT "entry_locales_site_id_sites_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "entry_locales" ADD CONSTRAINT "entry_locales_content_entry_id_content_entries_id_fk" FOREIGN KEY ("content_entry_id") REFERENCES "public"."content_entries"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "content_entries_site_type_idx" ON "content_entries" USING btree ("site_id","type_key");--> statement-breakpoint +CREATE UNIQUE INDEX "entry_locales_uq" ON "entry_locales" USING btree ("site_id","content_entry_id","locale");--> statement-breakpoint +-- ↓ 手写追加(drizzle-kit 不生成触发器):修订不可变,复用 0001 的 sf_forbid_update。 +-- 发布 = 只 UPDATE entry_locales 双指针(current/published),修订行本身库级禁改禁删(ADR-010)。 +CREATE TRIGGER content_revisions_immutable BEFORE UPDATE OR DELETE ON content_revisions + FOR EACH ROW EXECUTE FUNCTION sf_forbid_update();--> statement-breakpoint +-- 补 source_records.content_entry_id → content_entries FK(Task 7 预留,schema 层不声明故由手写 SQL 回填) +ALTER TABLE source_records + ADD CONSTRAINT source_records_content_entry_id_fkey + FOREIGN KEY (content_entry_id) REFERENCES content_entries(id); \ No newline at end of file diff --git a/apps/api/drizzle/meta/0002_snapshot.json b/apps/api/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..7407cec --- /dev/null +++ b/apps/api/drizzle/meta/0002_snapshot.json @@ -0,0 +1,1106 @@ +{ + "id": "76da975d-44c9-4a1f-ab30-29fae9e227ed", + "prevId": "6b9e4c4b-1851-48c7-b5c7-df804ef5477a", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.content_entries": { + "name": "content_entries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "type_key": { + "name": "type_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "lifecycle_status": { + "name": "lifecycle_status", + "type": "content_lifecycle_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "content_entries_site_type_idx": { + "name": "content_entries_site_type_idx", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "type_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "content_entries_site_id_sites_id_fk": { + "name": "content_entries_site_id_sites_id_fk", + "tableFrom": "content_entries", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.content_revisions": { + "name": "content_revisions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "content_entry_id": { + "name": "content_entry_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schema_version": { + "name": "schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "checksum": { + "name": "checksum", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_kind": { + "name": "source_kind", + "type": "revision_source_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "source_record_id": { + "name": "source_record_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "import_job_id": { + "name": "import_job_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "overridden_fields": { + "name": "overridden_fields", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "content_revisions_site_id_sites_id_fk": { + "name": "content_revisions_site_id_sites_id_fk", + "tableFrom": "content_revisions", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "content_revisions_content_entry_id_content_entries_id_fk": { + "name": "content_revisions_content_entry_id_content_entries_id_fk", + "tableFrom": "content_revisions", + "tableTo": "content_entries", + "columnsFrom": [ + "content_entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "content_revisions_import_job_id_import_jobs_id_fk": { + "name": "content_revisions_import_job_id_import_jobs_id_fk", + "tableFrom": "content_revisions", + "tableTo": "import_jobs", + "columnsFrom": [ + "import_job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.entry_locales": { + "name": "entry_locales", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "content_entry_id": { + "name": "content_entry_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "current_revision_id": { + "name": "current_revision_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "published_revision_id": { + "name": "published_revision_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "entry_locales_uq": { + "name": "entry_locales_uq", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "content_entry_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "locale", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "entry_locales_site_id_sites_id_fk": { + "name": "entry_locales_site_id_sites_id_fk", + "tableFrom": "entry_locales", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "entry_locales_content_entry_id_content_entries_id_fk": { + "name": "entry_locales_content_entry_id_content_entries_id_fk", + "tableFrom": "entry_locales", + "tableTo": "content_entries", + "columnsFrom": [ + "content_entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.import_jobs": { + "name": "import_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_snapshot_id": { + "name": "source_snapshot_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "import_job_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "mapping_version": { + "name": "mapping_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_summary": { + "name": "error_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "report_path": { + "name": "report_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "import_jobs_site_id_sites_id_fk": { + "name": "import_jobs_site_id_sites_id_fk", + "tableFrom": "import_jobs", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "import_jobs_source_snapshot_id_source_snapshots_id_fk": { + "name": "import_jobs_source_snapshot_id_source_snapshots_id_fk", + "tableFrom": "import_jobs", + "tableTo": "source_snapshots", + "columnsFrom": [ + "source_snapshot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "import_jobs_idempotency_key_unique": { + "name": "import_jobs_idempotency_key_unique", + "nullsNotDistinct": false, + "columns": [ + "idempotency_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.site_config_revisions": { + "name": "site_config_revisions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "checksum": { + "name": "checksum", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "site_config_rev_uq": { + "name": "site_config_rev_uq", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "site_config_revisions_site_id_sites_id_fk": { + "name": "site_config_revisions_site_id_sites_id_fk", + "tableFrom": "site_config_revisions", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sites": { + "name": "sites", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_locale": { + "name": "default_locale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "production_origin": { + "name": "production_origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sites_key_unique": { + "name": "sites_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.source_connections": { + "name": "source_connections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "source_connection_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "configuration": { + "name": "configuration", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "source_connections_site_id_sites_id_fk": { + "name": "source_connections_site_id_sites_id_fk", + "tableFrom": "source_connections", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.source_records": { + "name": "source_records", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_connection_id": { + "name": "source_connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_snapshot_id": { + "name": "source_snapshot_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "import_job_id": { + "name": "import_job_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "raw_location": { + "name": "raw_location", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_checksum": { + "name": "source_checksum", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "normalized_checksum": { + "name": "normalized_checksum", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parse_status": { + "name": "parse_status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_entry_id": { + "name": "content_entry_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "source_records_identity_uq": { + "name": "source_records_identity_uq", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "locale", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_snapshot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "source_records_site_id_sites_id_fk": { + "name": "source_records_site_id_sites_id_fk", + "tableFrom": "source_records", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "source_records_source_connection_id_source_connections_id_fk": { + "name": "source_records_source_connection_id_source_connections_id_fk", + "tableFrom": "source_records", + "tableTo": "source_connections", + "columnsFrom": [ + "source_connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "source_records_source_snapshot_id_source_snapshots_id_fk": { + "name": "source_records_source_snapshot_id_source_snapshots_id_fk", + "tableFrom": "source_records", + "tableTo": "source_snapshots", + "columnsFrom": [ + "source_snapshot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "source_records_import_job_id_import_jobs_id_fk": { + "name": "source_records_import_job_id_import_jobs_id_fk", + "tableFrom": "source_records", + "tableTo": "import_jobs", + "columnsFrom": [ + "import_job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.source_snapshots": { + "name": "source_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_connection_id": { + "name": "source_connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "source_snapshot_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "storage_path": { + "name": "storage_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "byte_size": { + "name": "byte_size", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "adapter_version": { + "name": "adapter_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "captured_at": { + "name": "captured_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "source_snapshots_uq": { + "name": "source_snapshots_uq", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sha256", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "source_snapshots_site_id_sites_id_fk": { + "name": "source_snapshots_site_id_sites_id_fk", + "tableFrom": "source_snapshots", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "source_snapshots_source_connection_id_source_connections_id_fk": { + "name": "source_snapshots_source_connection_id_source_connections_id_fk", + "tableFrom": "source_snapshots", + "tableTo": "source_connections", + "columnsFrom": [ + "source_connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.content_lifecycle_status": { + "name": "content_lifecycle_status", + "schema": "public", + "values": [ + "active", + "archived" + ] + }, + "public.import_job_status": { + "name": "import_job_status", + "schema": "public", + "values": [ + "queued", + "running", + "succeeded", + "succeeded_with_issues", + "failed", + "cancelled", + "stale" + ] + }, + "public.revision_source_kind": { + "name": "revision_source_kind", + "schema": "public", + "values": [ + "import", + "manual", + "restore" + ] + }, + "public.source_connection_kind": { + "name": "source_connection_kind", + "schema": "public", + "values": [ + "wxr" + ] + }, + "public.source_snapshot_kind": { + "name": "source_snapshot_kind", + "schema": "public", + "values": [ + "wxr", + "sitemap", + "media_bundle", + "manual_url_list" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.json index 202b71d..2d02e0c 100644 --- a/apps/api/drizzle/meta/_journal.json +++ b/apps/api/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1792495504658, "tag": "0001_broken_microchip", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1792496109431, + "tag": "0002_fancy_silver_centurion", + "breakpoints": true } ] } \ No newline at end of file diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index ffa308e..a39804a 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -1,5 +1,5 @@ -// 聚合导出:Task 6 起按域追加 pgTable 定义(站点域 = 迁移文件 0000_pale_sumo;来源域 = 0001_*) -import { pgTable, pgEnum, uuid, text, integer, bigint, jsonb, timestamp, uniqueIndex } from 'drizzle-orm/pg-core' +// 聚合导出:Task 6 起按域追加 pgTable 定义(站点域 = 迁移文件 0000_pale_sumo;来源域 = 0001_*;内容域 = 0002_*) +import { pgTable, pgEnum, uuid, text, integer, bigint, jsonb, timestamp, uniqueIndex, index } from 'drizzle-orm/pg-core' export const sites = pgTable('sites', { id: uuid('id').primaryKey().defaultRandom(), @@ -83,8 +83,57 @@ export const sourceRecords = pgTable('source_records', { sourceChecksum: text('source_checksum'), normalizedChecksum: text('normalized_checksum'), parseStatus: text('parse_status').notNull(), - // 暂无 FK:content_entries 于 Task 8(内容域)落地后再补引用 + // FK 由 0002 迁移手写 SQL 回填(Task 7 预留;schema 层不声明以避免与生成器 diff 漂移) contentEntryId: uuid('content_entry_id'), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), // 跨 Snapshot 稳定映射键 = site_id + source_connection_id + source_type + source_id + locale(snapshot_id 进键以允许跨快照再导入) }, (t) => [uniqueIndex('source_records_identity_uq').on(t.siteId, t.sourceConnectionId, t.sourceType, t.sourceId, t.locale, t.sourceSnapshotId)]) + +// ---- 内容域(spec §5.3;迁移文件 0002_*,末尾手写追加修订不可变触发器 + 回填 source_records.content_entry_id FK)---- + +export const contentLifecycleStatus = pgEnum('content_lifecycle_status', ['active', 'archived']) +export const revisionSourceKind = pgEnum('revision_source_kind', ['import', 'manual', 'restore']) + +// Entry = 内容聚合根(身份与 locale 无关;不用 Permalink 做身份) +export const contentEntries = pgTable('content_entries', { + id: uuid('id').primaryKey().defaultRandom(), + siteId: uuid('site_id').notNull().references(() => sites.id), + typeKey: text('type_key').notNull(), + lifecycleStatus: contentLifecycleStatus('lifecycle_status').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), +}, (t) => [index('content_entries_site_type_idx').on(t.siteId, t.typeKey)]) + +// 双指针:current=最新工作修订,published=公开修订;两者不同即"已发布但有未发布修改"(构建只读 published)。 +// 发布 = 只 UPDATE 本表指针,修订行永不 UPDATE(ADR-010)。 +export const entryLocales = pgTable('entry_locales', { + id: uuid('id').primaryKey().defaultRandom(), + siteId: uuid('site_id').notNull().references(() => sites.id), + contentEntryId: uuid('content_entry_id').notNull().references(() => contentEntries.id), + locale: text('locale').notNull(), + slug: text('slug').notNull(), + // 双指针本任务不设 FK:修订表在同一迁移创建,循环引用让 drizzle 处理麻烦; + // 指针目标合法性由应用层 + Task 13 测试保证,或后续迁移补 FK + currentRevisionId: uuid('current_revision_id'), + publishedRevisionId: uuid('published_revision_id'), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), + // slug 唯一性由 Route Registry 决定,不在此假设共享 slug 空间 +}, (t) => [uniqueIndex('entry_locales_uq').on(t.siteId, t.contentEntryId, t.locale)]) + +// 修订创建后不可变(库内触发器强制,见 0002 迁移手写 SQL;只 INSERT,无 UPDATE/DELETE 业务接口) +export const contentRevisions = pgTable('content_revisions', { + id: uuid('id').primaryKey().defaultRandom(), + siteId: uuid('site_id').notNull().references(() => sites.id), + contentEntryId: uuid('content_entry_id').notNull().references(() => contentEntries.id), + locale: text('locale').notNull(), + schemaVersion: integer('schema_version').notNull(), + data: jsonb('data').notNull(), + checksum: text('checksum').notNull(), + sourceKind: revisionSourceKind('source_kind').notNull(), + sourceRecordId: uuid('source_record_id'), + importJobId: uuid('import_job_id').references(() => importJobs.id), + overriddenFields: jsonb('overridden_fields').notNull().default([]), + createdBy: text('created_by').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), +}) diff --git a/tests/integration/db.content.test.ts b/tests/integration/db.content.test.ts new file mode 100644 index 0000000..5981139 --- /dev/null +++ b/tests/integration/db.content.test.ts @@ -0,0 +1,127 @@ +// 内容域集成测试:修订不可变触发器(UPDATE/DELETE 拒绝)+ entry_locales 三元组唯一 + +// 双指针语义(发布=只动 entry_locales 指针,不碰修订行)+ source_records.content_entry_id 回填 FK。 +// 生命周期纪律:随机后缀插入 + finally 反序清理;不可变表(content_revisions / source_snapshots) +// 清场走点名 DISABLE TRIGGER → 删本级行 → ENABLE,嵌套 finally 保证触发器必然恢复。 +import { describe, it, expect } from 'vitest' +import { getDb } from '../../apps/api/src/db/client.js' + +type Db = ReturnType +type Fixture = { + siteId: string + entryId: string + localeId: string + revisionId: string + connectionId: string + snapshotId: string + importJobId: string +} + +// 建链(FK 依赖顺序):site → content_entry → content_revision → entry_locale(current 指针指向该修订,published=NULL); +// 另建 source 链(connection → snapshot → job)供 source_records FK 探针使用。 +async function setupContentFixture(db: Db): Promise { + const rand = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}` + const site = (await db.execute(`insert into sites (id, key, name, default_locale, production_origin) + values (gen_random_uuid(), 'content-${rand}', 'ContentFixture', 'en', 'https://content.example') returning id`)) as any + const siteId = site[0].id + const entry = (await db.execute(`insert into content_entries (id, site_id, type_key, lifecycle_status) + values (gen_random_uuid(), '${siteId}', 'post', 'active') returning id`)) as any + const entryId = entry[0].id + const rev = (await db.execute(`insert into content_revisions (id, site_id, content_entry_id, locale, schema_version, data, checksum, source_kind, created_by) + values (gen_random_uuid(), '${siteId}', '${entryId}', 'en', 1, '{"title":"v1"}', 'ck-${rand}', 'manual', 'tester') returning id`)) as any + const revisionId = rev[0].id + const locale = (await db.execute(`insert into entry_locales (id, site_id, content_entry_id, locale, slug, current_revision_id, published_revision_id) + values (gen_random_uuid(), '${siteId}', '${entryId}', 'en', 'slug-${rand}', '${revisionId}', null) returning id`)) as any + const conn = (await db.execute(`insert into source_connections (id, site_id, kind, name, configuration) + values (gen_random_uuid(), '${siteId}', 'wxr', 'content-conn-${rand}', '{}') returning id`)) as any + const connectionId = conn[0].id + const snap = (await db.execute(`insert into source_snapshots (id, site_id, source_connection_id, kind, storage_path, sha256, byte_size, adapter_version, captured_at, metadata) + values (gen_random_uuid(), '${siteId}', '${connectionId}', 'wxr', 'wxr://${rand}.xml', 'sha256-${rand}', 123, 'wxr@1', now(), '{}') returning id`)) as any + const job = (await db.execute(`insert into import_jobs (id, site_id, source_snapshot_id, status, mapping_version, idempotency_key, attempt) + values (gen_random_uuid(), '${siteId}', '${snap[0].id}', 'queued', 'mapping@1', 'idem-content-${rand}', 0) returning id`)) as any + return { siteId, entryId, localeId: locale[0].id, revisionId, connectionId, snapshotId: snap[0].id, importJobId: job[0].id } +} + +// 反序清理。source_records 先于 content_entries(新 FK);两张不可变表逐一 DISABLE → 删 → ENABLE(嵌套 finally)。 +async function cleanupContentFixture(db: Db, f: Fixture) { + await db.execute(`delete from source_records where site_id = '${f.siteId}'`) + await db.execute(`delete from entry_locales where site_id = '${f.siteId}'`) + await db.execute(`alter table content_revisions disable trigger content_revisions_immutable`) + try { + await db.execute(`delete from content_revisions where site_id = '${f.siteId}'`) + } finally { + await db.execute(`alter table content_revisions enable trigger content_revisions_immutable`) + } + await db.execute(`delete from import_jobs where site_id = '${f.siteId}'`) + await db.execute(`alter table source_snapshots disable trigger source_snapshots_immutable`) + try { + await db.execute(`delete from source_snapshots where site_id = '${f.siteId}'`) + } finally { + await db.execute(`alter table source_snapshots enable trigger source_snapshots_immutable`) + } + await db.execute(`delete from source_connections where site_id = '${f.siteId}'`) + await db.execute(`delete from content_entries where site_id = '${f.siteId}'`) + await db.execute(`delete from sites where id = '${f.siteId}'`) +} + +async function withContentFixture(fn: (db: Db, f: Fixture) => Promise) { + const db = getDb() + const f = await setupContentFixture(db) + try { + await fn(db, f) + } finally { + await cleanupContentFixture(db, f) + await (db as any).$client.end() + } +} + +// drizzle 会把 PostgresError 包成 DrizzleQueryError(message 只有 "Failed query: ..."), +// 服务端原始错误文本在 cause 里——断言触发器/约束身份时必须看 cause。 +async function rejectionMessage(db: Db, query: string): Promise { + try { + await db.execute(query) + } catch (e: any) { + return String(e?.cause?.message ?? e?.message ?? e) + } + throw new Error(`expected query to be rejected: ${query}`) +} + +describe('内容域约束(修订不可变 + 双指针)', () => { + it('content_revisions 不可变:UPDATE 与 DELETE 均被触发器拒绝', async () => { + await withContentFixture(async (db, f) => { + expect(await rejectionMessage(db, `update content_revisions set checksum = 'tampered' where id = '${f.revisionId}'`)) + .toMatch(/immutable table content_revisions/) + expect(await rejectionMessage(db, `delete from content_revisions where id = '${f.revisionId}'`)) + .toMatch(/immutable table content_revisions/) + }) + }) + + it('entry_locales UNIQUE(site_id, content_entry_id, locale):同三元组重复插入拒绝,换 locale 放行', async () => { + await withContentFixture(async (db, f) => { + await expect(db.execute(`insert into entry_locales (id, site_id, content_entry_id, locale, slug) + values (gen_random_uuid(), '${f.siteId}', '${f.entryId}', 'en', 'dup-slug')`)) + .rejects.toThrow() + // 对照组:同 entry 换 locale → 允许(约束打在 site+entry+locale 三元组上,非 entry 级唯一) + await db.execute(`insert into entry_locales (id, site_id, content_entry_id, locale, slug) + values (gen_random_uuid(), '${f.siteId}', '${f.entryId}', 'zh', 'slug-zh')`) + }) + }) + + it('双指针语义:发布=只 UPDATE entry_locales.published_revision_id,不碰修订行(ADR-010)', async () => { + await withContentFixture(async (db, f) => { + // 初始:current=X、published=NULL(未发布)。发布动作 = 指针 UPDATE——库层必须放行 + // (修订行自身不可变,但指针是 entry_locales 的可变列;V2 设计的库级表达) + await db.execute(`update entry_locales set published_revision_id = '${f.revisionId}' where id = '${f.localeId}'`) + const after = (await db.execute(`select current_revision_id, published_revision_id from entry_locales where id = '${f.localeId}'`)) as any + expect(after[0].current_revision_id).toBe(f.revisionId) + expect(after[0].published_revision_id).toBe(f.revisionId) + }) + }) + + it('source_records.content_entry_id 回填 FK:指向不存在 entry 的插入被拒绝', async () => { + await withContentFixture(async (db, f) => { + expect(await rejectionMessage(db, `insert into source_records (id, site_id, source_connection_id, source_snapshot_id, import_job_id, source_type, source_id, locale, raw_location, parse_status, content_entry_id) + values (gen_random_uuid(), '${f.siteId}', '${f.connectionId}', '${f.snapshotId}', '${f.importJobId}', 'post', 'src-1', 'en', 'raw://1', 'parsed', gen_random_uuid())`)) + .toMatch(/source_records_content_entry_id_fkey/) + }) + }) +})