From 1cc0dcc57f819869e1bc066568a75155becf4ea8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=85=E5=BF=B5?= Date: Tue, 20 Oct 2026 20:02:57 +0800 Subject: [PATCH] =?UTF-8?q?feat(db):=200004=20=E5=AA=92=E4=BD=93=E5=9F=9F?= =?UTF-8?q?=E2=80=94=E2=80=94assets/usages=20=E5=8F=8C=E5=94=AF=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit media_assets 双唯一 UNIQUE(site_id, source_url) / UNIQUE(site_id, public_path) + status 四值 enum + source_id 可空;media_usages 复合主键 (media_asset_id, content_revision_id, field_path),无独立 id/时间戳(spec §5.5)。 vitest fileParallelism: false——不可变表清场 DISABLE/ENABLE TRIGGER 是库级 DDL, 与并行文件的不可变断言竞态(实测 media 清场窗口内 content 断言偶发放行); 串行执行消除竞态,套件仅数秒。 Co-Authored-By: Claude Code --- apps/api/drizzle/0004_last_victor_mancha.sql | 37 + apps/api/drizzle/meta/0004_snapshot.json | 1698 ++++++++++++++++++ apps/api/drizzle/meta/_journal.json | 7 + apps/api/src/db/schema.ts | 43 +- tests/integration/db.media.test.ts | 166 ++ vitest.config.ts | 5 + 6 files changed, 1955 insertions(+), 1 deletion(-) create mode 100644 apps/api/drizzle/0004_last_victor_mancha.sql create mode 100644 apps/api/drizzle/meta/0004_snapshot.json create mode 100644 tests/integration/db.media.test.ts diff --git a/apps/api/drizzle/0004_last_victor_mancha.sql b/apps/api/drizzle/0004_last_victor_mancha.sql new file mode 100644 index 0000000..ef651ec --- /dev/null +++ b/apps/api/drizzle/0004_last_victor_mancha.sql @@ -0,0 +1,37 @@ +CREATE TYPE "public"."media_asset_status" AS ENUM('ready', 'missing', 'quarantined', 'unsupported');--> statement-breakpoint +CREATE TABLE "media_assets" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "site_id" uuid NOT NULL, + "source_connection_id" uuid NOT NULL, + "source_id" text, + "source_url" text NOT NULL, + "source_path" text NOT NULL, + "storage_path" text NOT NULL, + "public_path" text NOT NULL, + "sha256" text NOT NULL, + "detected_mime" text NOT NULL, + "declared_mime" text, + "byte_size" bigint NOT NULL, + "width" integer, + "height" integer, + "alt_text" text, + "status" "media_asset_status" NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "media_usages" ( + "site_id" uuid NOT NULL, + "media_asset_id" uuid NOT NULL, + "content_revision_id" uuid NOT NULL, + "field_path" text NOT NULL, + "source_url" text NOT NULL, + CONSTRAINT "media_usages_media_asset_id_content_revision_id_field_path_pk" PRIMARY KEY("media_asset_id","content_revision_id","field_path") +); +--> statement-breakpoint +ALTER TABLE "media_assets" ADD CONSTRAINT "media_assets_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 "media_assets" ADD CONSTRAINT "media_assets_source_connection_id_source_connections_id_fk" FOREIGN KEY ("source_connection_id") REFERENCES "public"."source_connections"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "media_usages" ADD CONSTRAINT "media_usages_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 "media_usages" ADD CONSTRAINT "media_usages_media_asset_id_media_assets_id_fk" FOREIGN KEY ("media_asset_id") REFERENCES "public"."media_assets"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "media_usages" ADD CONSTRAINT "media_usages_content_revision_id_content_revisions_id_fk" FOREIGN KEY ("content_revision_id") REFERENCES "public"."content_revisions"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "media_assets_source_url_uq" ON "media_assets" USING btree ("site_id","source_url");--> statement-breakpoint +CREATE UNIQUE INDEX "media_assets_public_path_uq" ON "media_assets" USING btree ("site_id","public_path"); \ No newline at end of file diff --git a/apps/api/drizzle/meta/0004_snapshot.json b/apps/api/drizzle/meta/0004_snapshot.json new file mode 100644 index 0000000..c97bddd --- /dev/null +++ b/apps/api/drizzle/meta/0004_snapshot.json @@ -0,0 +1,1698 @@ +{ + "id": "fe7a789b-95ef-4f75-8d5c-00d1e2b1a518", + "prevId": "d41c9c0d-f4c9-4265-8482-fec7c3559852", + "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.content_terms": { + "name": "content_terms", + "schema": "", + "columns": { + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "content_entry_id": { + "name": "content_entry_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "term_id": { + "name": "term_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "is_primary": { + "name": "is_primary", + "type": "boolean", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "content_terms_site_id_sites_id_fk": { + "name": "content_terms_site_id_sites_id_fk", + "tableFrom": "content_terms", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "content_terms_content_entry_id_content_entries_id_fk": { + "name": "content_terms_content_entry_id_content_entries_id_fk", + "tableFrom": "content_terms", + "tableTo": "content_entries", + "columnsFrom": [ + "content_entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "content_terms_term_id_terms_id_fk": { + "name": "content_terms_term_id_terms_id_fk", + "tableFrom": "content_terms", + "tableTo": "terms", + "columnsFrom": [ + "term_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "content_terms_site_id_content_entry_id_term_id_pk": { + "name": "content_terms_site_id_content_entry_id_term_id_pk", + "columns": [ + "site_id", + "content_entry_id", + "term_id" + ] + } + }, + "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.media_assets": { + "name": "media_assets", + "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_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_path": { + "name": "source_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "storage_path": { + "name": "storage_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "public_path": { + "name": "public_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "detected_mime": { + "name": "detected_mime", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "declared_mime": { + "name": "declared_mime", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "byte_size": { + "name": "byte_size", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "alt_text": { + "name": "alt_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "media_asset_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "media_assets_source_url_uq": { + "name": "media_assets_source_url_uq", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "media_assets_public_path_uq": { + "name": "media_assets_public_path_uq", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "public_path", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_assets_site_id_sites_id_fk": { + "name": "media_assets_site_id_sites_id_fk", + "tableFrom": "media_assets", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "media_assets_source_connection_id_source_connections_id_fk": { + "name": "media_assets_source_connection_id_source_connections_id_fk", + "tableFrom": "media_assets", + "tableTo": "source_connections", + "columnsFrom": [ + "source_connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media_usages": { + "name": "media_usages", + "schema": "", + "columns": { + "site_id": { + "name": "site_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "media_asset_id": { + "name": "media_asset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "content_revision_id": { + "name": "content_revision_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "field_path": { + "name": "field_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "media_usages_site_id_sites_id_fk": { + "name": "media_usages_site_id_sites_id_fk", + "tableFrom": "media_usages", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "media_usages_media_asset_id_media_assets_id_fk": { + "name": "media_usages_media_asset_id_media_assets_id_fk", + "tableFrom": "media_usages", + "tableTo": "media_assets", + "columnsFrom": [ + "media_asset_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "media_usages_content_revision_id_content_revisions_id_fk": { + "name": "media_usages_content_revision_id_content_revisions_id_fk", + "tableFrom": "media_usages", + "tableTo": "content_revisions", + "columnsFrom": [ + "content_revision_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "media_usages_media_asset_id_content_revision_id_field_path_pk": { + "name": "media_usages_media_asset_id_content_revision_id_field_path_pk", + "columns": [ + "media_asset_id", + "content_revision_id", + "field_path" + ] + } + }, + "uniqueConstraints": {}, + "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 + }, + "public.taxonomies": { + "name": "taxonomies", + "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 + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "object_type": { + "name": "object_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "public_base_path": { + "name": "public_base_path", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "taxonomies_uq": { + "name": "taxonomies_uq", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "object_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "taxonomies_site_id_sites_id_fk": { + "name": "taxonomies_site_id_sites_id_fk", + "tableFrom": "taxonomies", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.terms": { + "name": "terms", + "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 + }, + "taxonomy_id": { + "name": "taxonomy_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_term_id": { + "name": "parent_term_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "terms_identity_uq": { + "name": "terms_identity_uq", + "columns": [ + { + "expression": "site_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "taxonomy_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "terms_site_id_sites_id_fk": { + "name": "terms_site_id_sites_id_fk", + "tableFrom": "terms", + "tableTo": "sites", + "columnsFrom": [ + "site_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "terms_taxonomy_id_taxonomies_id_fk": { + "name": "terms_taxonomy_id_taxonomies_id_fk", + "tableFrom": "terms", + "tableTo": "taxonomies", + "columnsFrom": [ + "taxonomy_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "terms_parent_term_id_terms_id_fk": { + "name": "terms_parent_term_id_terms_id_fk", + "tableFrom": "terms", + "tableTo": "terms", + "columnsFrom": [ + "parent_term_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.media_asset_status": { + "name": "media_asset_status", + "schema": "public", + "values": [ + "ready", + "missing", + "quarantined", + "unsupported" + ] + }, + "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 7faa7eb..40bb2a9 100644 --- a/apps/api/drizzle/meta/_journal.json +++ b/apps/api/drizzle/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1792496827818, "tag": "0003_groovy_phil_sheldon", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1792497336007, + "tag": "0004_last_victor_mancha", + "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 743fdc4..9b28164 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -1,4 +1,4 @@ -// 聚合导出:Task 6 起按域追加 pgTable 定义(站点域 = 迁移文件 0000_pale_sumo;来源域 = 0001_*;内容域 = 0002_*;分类域 = 0003_*) +// 聚合导出:Task 6 起按域追加 pgTable 定义(站点域 = 迁移文件 0000_pale_sumo;来源域 = 0001_*;内容域 = 0002_*;分类域 = 0003_*;媒体域 = 0004_*) import { pgTable, pgEnum, uuid, text, integer, bigint, jsonb, timestamp, uniqueIndex, index, boolean, primaryKey, type AnyPgColumn } from 'drizzle-orm/pg-core' export const sites = pgTable('sites', { @@ -172,3 +172,44 @@ export const contentTerms = pgTable('content_terms', { termId: uuid('term_id').notNull().references(() => terms.id), isPrimary: boolean('is_primary').notNull(), }, (t) => [primaryKey({ columns: [t.siteId, t.contentEntryId, t.termId] })]) + +// ---- 媒体域(spec §5.5;迁移文件 0004_*,无手写 SQL)---- +// 媒体资产与使用关系:匹配按 source_url 找(spec 匹配顺序 1-3),发布按 public_path 寻址, +// 故库层打双唯一——同站同一来源 URL 只入一次库,同站公开路径不冲突(换路径放行 = 新资产)。 + +export const mediaAssetStatus = pgEnum('media_asset_status', ['ready', 'missing', 'quarantined', 'unsupported']) + +export const mediaAssets = pgTable('media_assets', { + id: uuid('id').primaryKey().defaultRandom(), + siteId: uuid('site_id').notNull().references(() => sites.id), + sourceConnectionId: uuid('source_connection_id').notNull().references(() => sourceConnections.id), + // WP 站外媒体(热链/外部图床)在来源系统内没有附件 ID,source_id 必须可空 + sourceId: text('source_id'), + sourceUrl: text('source_url').notNull(), + sourcePath: text('source_path').notNull(), + storagePath: text('storage_path').notNull(), + publicPath: text('public_path').notNull(), + sha256: text('sha256').notNull(), + detectedMimeType: text('detected_mime').notNull(), + declaredMimeType: text('declared_mime'), + byteSize: bigint('byte_size', { mode: 'number' }).notNull(), + width: integer('width'), + height: integer('height'), + altText: text('alt_text'), + status: mediaAssetStatus('status').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), +}, (t) => [ + uniqueIndex('media_assets_source_url_uq').on(t.siteId, t.sourceUrl), + uniqueIndex('media_assets_public_path_uq').on(t.siteId, t.publicPath), +]) + +// 使用关系:一资产在一修订的一字段位被引用一次。复合主键 (media_asset_id, content_revision_id, +// field_path) 天然防重;无独立 id/时间戳(照 spec §5.5——usage 是修订不可变快照的一部分, +// 修订不可变则 usage 无需自身生命周期)。content_revision_id 指向不可变的 content_revisions。 +export const mediaUsages = pgTable('media_usages', { + siteId: uuid('site_id').notNull().references(() => sites.id), + mediaAssetId: uuid('media_asset_id').notNull().references(() => mediaAssets.id), + contentRevisionId: uuid('content_revision_id').notNull().references(() => contentRevisions.id), + fieldPath: text('field_path').notNull(), + sourceUrl: text('source_url').notNull(), +}, (t) => [primaryKey({ columns: [t.mediaAssetId, t.contentRevisionId, t.fieldPath] })]) diff --git a/tests/integration/db.media.test.ts b/tests/integration/db.media.test.ts new file mode 100644 index 0000000..83de60c --- /dev/null +++ b/tests/integration/db.media.test.ts @@ -0,0 +1,166 @@ +// 媒体域集成测试:media_assets 双唯一 UNIQUE(site_id, source_url) 与 UNIQUE(site_id, public_path) +// (各带"换列值放行"对照组——同站不同源 URL / 不同公开路径都是合法的第二次入库)+ +// media_usages 复合主键 (media_asset_id, content_revision_id, field_path)(换 field_path 放行—— +// 同媒体同修订不同字段位引用合法)+ status enum 四值可写往返 + source_id 可空(WP 站外媒体无源 ID)。 +// 生命周期纪律:随机后缀插入 + finally 反序清理;content_revisions 不可变,清场走 +// DISABLE TRIGGER → 删本级行 → ENABLE,嵌套 finally 保证触发器必然恢复。 +// 清场顺序:usages → assets → connections →(DISABLE 删 revisions)→ entries → site。 +import { describe, it, expect } from 'vitest' +import { getDb } from '../../apps/api/src/db/client.js' + +type Db = ReturnType +type Fixture = { + siteId: string + connectionId: string + entryId: string + revisionId: string + assetId: string + rand: string + sourceUrl: string + publicPath: string +} + +// 建链(FK 依赖顺序):site → source_connection(asset 的来源)+ content_entry → content_revision +// (usage 的引用目标)→ media_asset(ready 态,供双唯一探测与 enum 往返)。 +async function setupMediaFixture(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(), 'media-${rand}', 'MediaFixture', 'en', 'https://media.example') returning id`)) as any + const siteId = site[0].id + const conn = (await db.execute(`insert into source_connections (id, site_id, kind, name, configuration) + values (gen_random_uuid(), '${siteId}', 'wxr', 'media-conn-${rand}', '{}') returning id`)) as any + 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 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}', '${entry[0].id}', 'en', 1, '{"body":""}', 'ck-media-${rand}', 'manual', 'tester') returning id`)) as any + const sourceUrl = `https://wp.example/uploads/${rand}/pic.jpg` + const publicPath = `/uploads/${rand}/pic.jpg` + const asset = (await db.execute(`insert into media_assets (id, site_id, source_connection_id, source_id, source_url, source_path, storage_path, public_path, sha256, detected_mime, declared_mime, byte_size, width, height, alt_text, status) + values (gen_random_uuid(), '${siteId}', '${conn[0].id}', 'wp-att-${rand}', '${sourceUrl}', 'wp-content/uploads/${rand}/pic.jpg', 'media/${rand}/pic.jpg', '${publicPath}', 'sha256-${rand}', 'image/jpeg', 'image/jpg', 2048, 640, 480, 'Pic ${rand}', 'ready') returning id`)) as any + return { + siteId, + connectionId: conn[0].id, + entryId: entry[0].id, + revisionId: rev[0].id, + assetId: asset[0].id, + rand, + sourceUrl, + publicPath, + } +} + +// 反序清理:media_usages → media_assets → source_connections → +// content_revisions(不可变:DISABLE → 删 → ENABLE 嵌套 finally)→ content_entries → site。 +async function cleanupMediaFixture(db: Db, f: Fixture) { + await db.execute(`delete from media_usages where site_id = '${f.siteId}'`) + await db.execute(`delete from media_assets where site_id = '${f.siteId}'`) + await db.execute(`delete from source_connections 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 content_entries where site_id = '${f.siteId}'`) + await db.execute(`delete from sites where id = '${f.siteId}'`) +} + +async function withMediaFixture(fn: (db: Db, f: Fixture) => Promise) { + const db = getDb() + const f = await setupMediaFixture(db) + try { + await fn(db, f) + } finally { + await cleanupMediaFixture(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}`) +} + +// 探测插入的第二份资产:除显式指定的列外全部换新值,保证被测唯一键是唯一可能的冲突源。 +function assetProbe(f: Fixture, overrides: { sourceUrl: string; publicPath: string; sourceId?: string | null }) { + const suffix = Math.random().toString(36).slice(2, 8) + return `insert into media_assets (id, site_id, source_connection_id, source_id, source_url, source_path, storage_path, public_path, sha256, detected_mime, byte_size, status) + values (gen_random_uuid(), '${f.siteId}', '${f.connectionId}', ${overrides.sourceId === undefined ? `'probe-${suffix}'` : overrides.sourceId === null ? 'null' : `'${overrides.sourceId}'`}, '${overrides.sourceUrl}', 'wp-content/uploads/probe-${suffix}', 'media/probe-${suffix}', '${overrides.publicPath}', 'sha256-probe-${suffix}', 'image/jpeg', 1024, 'ready')` +} + +describe('媒体域约束', () => { + it('media_assets UNIQUE(site_id, source_url):同站同源 URL 重复插入拒绝,换 source_url 放行', async () => { + await withMediaFixture(async (db, f) => { + // public_path 换新,确保拒绝只可能来自 source_url 唯一键 + expect(await rejectionMessage(db, assetProbe(f, { + sourceUrl: f.sourceUrl, + publicPath: `/uploads/probe-${f.rand}-a.jpg`, + }))).toMatch(/media_assets_source_url_uq/) + // 对照组:同站换源 URL(公开路径同步换新)→ 允许(同站不同来源的同一张图是两份资产) + await db.execute(assetProbe(f, { + sourceUrl: `https://wp.example/${f.rand}/other.jpg`, + publicPath: `/uploads/probe-${f.rand}-b.jpg`, + })) + }) + }) + + it('media_assets UNIQUE(site_id, public_path):同站同公开路径重复插入拒绝,换 public_path 放行', async () => { + await withMediaFixture(async (db, f) => { + // source_url 换新,确保拒绝只可能来自 public_path 唯一键 + expect(await rejectionMessage(db, assetProbe(f, { + sourceUrl: `https://cdn.example/${f.rand}/pic.jpg`, + publicPath: f.publicPath, + }))).toMatch(/media_assets_public_path_uq/) + // 对照组:同站换公开路径(源 URL 同步换新)→ 允许(公开路径是站内命名空间,不重不解) + await db.execute(assetProbe(f, { + sourceUrl: `https://wp.example/${f.rand}/another.jpg`, + publicPath: `/uploads/probe-${f.rand}-c.jpg`, + })) + }) + }) + + it('media_usages 复合主键 (media_asset_id, content_revision_id, field_path):同三元组重复拒绝,换 field_path 放行', async () => { + await withMediaFixture(async (db, f) => { + await db.execute(`insert into media_usages (site_id, media_asset_id, content_revision_id, field_path, source_url) + values ('${f.siteId}', '${f.assetId}', '${f.revisionId}', 'data.body.img[0]', '${f.sourceUrl}')`) + expect(await rejectionMessage(db, `insert into media_usages (site_id, media_asset_id, content_revision_id, field_path, source_url) + values ('${f.siteId}', '${f.assetId}', '${f.revisionId}', 'data.body.img[0]', '${f.sourceUrl}')`)) + .toMatch(/media_usages_media_asset_id_content_revision_id_field_path_pk/) + // 对照组:同媒体同修订换字段位 → 允许(一图在正文中被引用多次是合法的多行 usage) + await db.execute(`insert into media_usages (site_id, media_asset_id, content_revision_id, field_path, source_url) + values ('${f.siteId}', '${f.assetId}', '${f.revisionId}', 'data.body.img[1]', '${f.sourceUrl}')`) + }) + }) + + it('media_assets.status enum 四值(ready/missing/quarantined/unsupported)可写往返,第五值拒绝', async () => { + await withMediaFixture(async (db, f) => { + for (const status of ['missing', 'quarantined', 'unsupported', 'ready']) { + await db.execute(`update media_assets set status = '${status}' where id = '${f.assetId}'`) + const row = (await db.execute(`select status from media_assets where id = '${f.assetId}'`)) as any + expect(row[0].status).toBe(status) + } + // enum 在库:类型化列拒绝四值之外的任意字符串 + expect(await rejectionMessage(db, `update media_assets set status = 'bogus' where id = '${f.assetId}'`)) + .toMatch(/media_asset_status/) + }) + }) + + it('media_assets.source_id 可空:插 NULL 成功(WP 站外媒体无源 ID)', async () => { + await withMediaFixture(async (db, f) => { + await db.execute(assetProbe(f, { + sourceId: null, + sourceUrl: `https://external.example/${f.rand}/hotlink.jpg`, + publicPath: `/uploads/probe-${f.rand}-d.jpg`, + })) + const row = (await db.execute(`select source_id from media_assets + where site_id = '${f.siteId}' and source_url = 'https://external.example/${f.rand}/hotlink.jpg'`)) as any + expect(row[0].source_id).toBeNull() + }) + }) +}) diff --git a/vitest.config.ts b/vitest.config.ts index 5ffbb5c..f0ca422 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,5 +3,10 @@ export default defineConfig({ test: { include: ['tests/**/*.test.ts', 'packages/*/test/**/*.test.ts', 'apps/*/test/**/*.test.ts'], testTimeout: 30000, + // 集成测试共库且清场会做全局态变更(不可变表 DISABLE/ENABLE TRIGGER 是库级 DDL, + // 对所有会话可见):文件级并行时 A 文件清场窗口会与 B 文件的不可变断言竞态(实测 + // db.media 清场 disable content_revisions_immutable 期间,db.content 恰好断言该触发器 + // → UPDATE 意外放行)。串行执行文件消除该竞态;套件仅数秒,并行无收益。 + fileParallelism: false, }, })