CREATE TABLE IF NOT EXISTS estudio_control (id integer PRIMARY KEY CHECK(id=1), modo text NOT NULL CHECK(modo IN ('preparacion','activo')), importado_en timestamptz); INSERT INTO estudio_control(id,modo) VALUES(1,'preparacion') ON CONFLICT DO NOTHING; ALTER TABLE estudio_control ADD COLUMN IF NOT EXISTS huella_fuente text; CREATE TABLE IF NOT EXISTS estudio_documento ( id text PRIMARY KEY, tipo text NOT NULL, estado text NOT NULL DEFAULT 'borrador' CHECK(estado IN ('borrador','publicado','retirado')), revision integer NOT NULL DEFAULT 1 CHECK(revision>0), borrador jsonb NOT NULL, publicado jsonb, actualizado timestamptz NOT NULL DEFAULT now(), autor text NOT NULL, CHECK(jsonb_typeof(borrador)='object'), CHECK(publicado IS NULL OR jsonb_typeof(publicado)='object') ); CREATE INDEX IF NOT EXISTS estudio_documento_tipo ON estudio_documento(tipo,actualizado DESC,id); CREATE UNIQUE INDEX IF NOT EXISTS estudio_documento_slug ON estudio_documento(tipo,(borrador->>'slug')) WHERE borrador->>'slug' <> ''; CREATE TABLE IF NOT EXISTS estudio_vinculo ( origen text NOT NULL REFERENCES estudio_documento(id) ON DELETE CASCADE, destino text NOT NULL REFERENCES estudio_documento(id) ON DELETE RESTRICT, edicion text NOT NULL CHECK(edicion IN ('borrador','publicado')), papel text NOT NULL, orden integer NOT NULL, detalle text NOT NULL DEFAULT '', PRIMARY KEY(origen,destino,edicion,papel) ); CREATE INDEX IF NOT EXISTS estudio_vinculo_destino ON estudio_vinculo(destino,edicion); CREATE TABLE IF NOT EXISTS estudio_historial ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, documento_id text NOT NULL REFERENCES estudio_documento(id) ON DELETE RESTRICT, revision integer NOT NULL, accion text NOT NULL, autor text NOT NULL, contenido jsonb NOT NULL, fecha timestamptz NOT NULL DEFAULT now() ); CREATE TABLE IF NOT EXISTS estudio_archivo ( id text PRIMARY KEY, clase text NOT NULL CHECK(clase IN ('imagen','audio')), nombre text NOT NULL, datos jsonb NOT NULL, creado timestamptz NOT NULL DEFAULT now() ); CREATE TABLE IF NOT EXISTS estudio_trabajo ( id text PRIMARY KEY, documento_id text NOT NULL REFERENCES estudio_documento(id) ON DELETE RESTRICT, estado text NOT NULL CHECK(estado IN ('procesando','listo','error')), mensaje text NOT NULL DEFAULT '', creado timestamptz NOT NULL DEFAULT now(), actualizado timestamptz NOT NULL DEFAULT now() ); CREATE TABLE IF NOT EXISTS estudio_pista_publicada ( lanzamiento_id text NOT NULL, grabacion_id text NOT NULL, orden integer NOT NULL, PRIMARY KEY(lanzamiento_id,grabacion_id), UNIQUE(lanzamiento_id,orden) );