Added cleanup support

This commit is contained in:
Amit Salunke 2026-09-11 19:31:55 +05:30
parent 71732a5c26
commit f7958d4c1e
4 changed files with 296 additions and 166 deletions

View File

@ -11,33 +11,54 @@ from .schema import CONTENT_SCHEMA, resolve_content_schema
@dataclass(frozen=True, slots=True)
class ModuleContentCleanupResult:
module_code: str
definition_set_count: int
content_count: int
search_facet_count: int
search_document_count: int
module_content_count: int
content_attribute_count: int
content_item_count: int
definition_member_count: int
definition_count: int
presentation_contract_count: int
search_facet_mapping_count: int
class ModuleContentCleaner:
"""
Removes seeded content associated with one module without removing
module/template/attribute-definition/search-facet configuration.
"""Archive/reset all bootstrap-owned content configuration for one module.
Shared content is preserved:
* the target module's module_contents associations are removed;
* content_attributes/content_items are deleted only when the content
has no remaining module_contents association.
``--cleanup`` is a logical module reset, not a destructive schema delete.
The module's definition-set rows are retained as stable template identities
so their UUIDs remain reusable across subsequent bootstrap runs. Everything
owned beneath those sets is reset to a state that the normal idempotent
seeders can reconcile:
* content_items are archived/inactivated rather than deleted;
* module/search projections for those contents are removed;
* attribute_definitions are deactivated rather than deleted;
* attribute_definition_members are deleted because the table has no
archival flag and the definition seeder recreates the current graph;
* presentation contracts are deactivated and reused by natural key;
* search facet mappings pointing at this module/its definitions are
deactivated and reused by the facet seeder;
* attribute_definition_sets remain active and keep their UUIDs.
Archived content receives a private metadata marker. ContentSeeder uses
that marker to distinguish a bootstrap cleanup archive from a genuinely
business-archived record, and only the former may be restored automatically
during reseeding.
Callers own the transaction boundary. This class never commits.
"""
_ARCHIVE_MARKER = "_bootstrap_cleanup"
def __init__(self, session: AsyncSession, *, schema: str = CONTENT_SCHEMA) -> None:
self._session = session
self._schema = resolve_content_schema(schema)
async def cleanup(self, module_code: str) -> ModuleContentCleanupResult:
normalized_code = module_code.strip()
normalized_code = module_code.strip().upper()
if not normalized_code:
raise ValueError("module_code must be a non-empty string")
@ -46,13 +67,52 @@ class ModuleContentCleaner:
f"""
SELECT id
FROM {self._schema}.modules
WHERE code = :module_code
WHERE upper(code) = :module_code
"""
),
{"module_code": normalized_code},
)
if module_id is None:
raise ValueError(f"Module not found: {normalized_code}")
# A first-time bootstrap may legitimately have no module row yet.
# Do not fail cleanup in that case: definition-set/template identity is
# still sufficient to find and reset any orphaned state left by a
# previous partial bootstrap. If no such state exists, all cleanup
# counts naturally remain zero and normal module seeding continues.
# Stable ownership is derived from the template/definition-set code,
# not solely from module_contents. This captures historical/orphaned
# content left behind by an older or failed bootstrap implementation.
await self._session.execute(
text(
"""
CREATE TEMP TABLE IF NOT EXISTS tmp_acupedia_module_cleanup_sets (
definition_set_id uuid PRIMARY KEY
) ON COMMIT DROP
"""
)
)
await self._session.execute(
text("TRUNCATE TABLE tmp_acupedia_module_cleanup_sets")
)
await self._session.execute(
text(
f"""
INSERT INTO tmp_acupedia_module_cleanup_sets (definition_set_id)
SELECT ads.id
FROM {self._schema}.attribute_definition_sets ads
WHERE upper(ads.code) LIKE :template_pattern
OR upper(ads.attribute_prefix_code) LIKE :template_pattern
ON CONFLICT (definition_set_id) DO NOTHING
"""
),
{"template_pattern": f"{normalized_code}_CT%"},
)
definition_set_count = int(
await self._session.scalar(
text("SELECT count(*) FROM tmp_acupedia_module_cleanup_sets")
)
or 0
)
await self._session.execute(
text(
@ -73,6 +133,14 @@ class ModuleContentCleaner:
SELECT DISTINCT mc.content_id
FROM {self._schema}.module_contents mc
WHERE mc.module_id = :module_id
UNION
SELECT DISTINCT ci.id
FROM {self._schema}.content_items ci
JOIN tmp_acupedia_module_cleanup_sets s
ON s.definition_set_id = ci.attribute_definition_set_id
ON CONFLICT (content_id) DO NOTHING
"""
),
@ -86,6 +154,9 @@ class ModuleContentCleaner:
or 0
)
# Search projections are runtime/derived state; remove them so stale
# archived content is not discoverable. The normal facet/index rebuild
# recreates projections after successful reseeding.
search_facet_result = await self._session.execute(
text(
f"""
@ -95,7 +166,6 @@ class ModuleContentCleaner:
"""
)
)
search_document_result = await self._session.execute(
text(
f"""
@ -106,47 +176,143 @@ class ModuleContentCleaner:
)
)
# Remove only this module's associations. A content row may still have
# associations elsewhere, but if it is owned by this module's template
# definition set it is still archived below as part of the reset.
module_content_result = await self._session.execute(
text(f"DELETE FROM {self._schema}.module_contents WHERE module_id = :module_id"),
text(
f"DELETE FROM {self._schema}.module_contents WHERE module_id = :module_id"
),
{"module_id": module_id},
)
attribute_result = await self._session.execute(
# Archive content rather than deleting it. Keep attributes/history in
# place until the content seeder restores a row; _seed_row already
# replaces content_attributes for a successfully reseeded item.
content_result = await self._session.execute(
text(
f"""
DELETE FROM {self._schema}.content_attributes ca
USING tmp_acupedia_module_cleanup_content t
WHERE ca.content_id = t.content_id
AND NOT EXISTS (
SELECT 1
FROM {self._schema}.module_contents mc
WHERE mc.content_id = t.content_id
)
UPDATE {self._schema}.content_items ci
SET status = 'archived',
is_active = false,
published_at = null,
metadata = coalesce(ci.metadata, '{{}}'::jsonb)
|| jsonb_build_object(
'_bootstrap_cleanup',
jsonb_build_object(
'module_code', CAST(:module_code AS text),
'archived_at', to_jsonb(now())
)
),
updated_at = now()
FROM tmp_acupedia_module_cleanup_content t
WHERE ci.id = t.content_id
"""
),
{"module_code": normalized_code},
)
# Capture all current definitions owned by the module's stable sets.
await self._session.execute(
text(
"""
CREATE TEMP TABLE IF NOT EXISTS tmp_acupedia_module_cleanup_definitions (
definition_id uuid PRIMARY KEY
) ON COMMIT DROP
"""
)
)
await self._session.execute(
text("TRUNCATE TABLE tmp_acupedia_module_cleanup_definitions")
)
await self._session.execute(
text(
f"""
INSERT INTO tmp_acupedia_module_cleanup_definitions (definition_id)
SELECT ad.id
FROM {self._schema}.attribute_definitions ad
JOIN tmp_acupedia_module_cleanup_sets s
ON s.definition_set_id = ad.attribute_definition_set_id
ON CONFLICT (definition_id) DO NOTHING
"""
)
)
content_result = await self._session.execute(
# A member edge is mutable derived configuration and has no is_active
# column. Remove both intra-set and any erroneous cross-set edges that
# touch a module-owned definition. The definition seeder reconstructs
# only valid current edges from template JSON.
member_result = await self._session.execute(
text(
f"""
DELETE FROM {self._schema}.content_items ci
USING tmp_acupedia_module_cleanup_content t
WHERE ci.id = t.content_id
AND NOT EXISTS (
SELECT 1
FROM {self._schema}.module_contents mc
WHERE mc.content_id = t.content_id
)
DELETE FROM {self._schema}.attribute_definition_members adm
USING tmp_acupedia_module_cleanup_definitions d
WHERE adm.parent_attribute_definition_id = d.definition_id
OR adm.child_attribute_definition_id = d.definition_id
"""
)
)
definition_result = await self._session.execute(
text(
f"""
UPDATE {self._schema}.attribute_definitions ad
SET is_active = false,
updated_at = now()
FROM tmp_acupedia_module_cleanup_definitions d
WHERE ad.id = d.definition_id
AND ad.is_active = true
"""
)
)
# Preserve contract rows/version history but make the current module
# presentation inactive until the template seeder reactivates the
# declared version(s).
presentation_result = await self._session.execute(
text(
f"""
UPDATE {self._schema}.template_presentation_contracts tpc
SET is_active = false,
updated_at = now()
FROM tmp_acupedia_module_cleanup_sets s
WHERE tpc.attribute_definition_set_id = s.definition_set_id
AND tpc.is_active = true
"""
)
)
# Facets themselves are canonical/global. Only mappings owned by this
# module or pointing at one of its definitions are archived.
search_mapping_result = await self._session.execute(
text(
f"""
UPDATE {self._schema}.search_facet_mappings sfm
SET is_active = false,
updated_at = now()
WHERE sfm.is_active = true
AND (
sfm.module_id = :module_id
OR sfm.attribute_definition_id IN (
SELECT definition_id
FROM tmp_acupedia_module_cleanup_definitions
)
)
"""
),
{"module_id": module_id},
)
return ModuleContentCleanupResult(
module_code=normalized_code,
definition_set_count=definition_set_count,
content_count=content_count,
search_facet_count=max(search_facet_result.rowcount or 0, 0),
search_document_count=max(search_document_result.rowcount or 0, 0),
module_content_count=max(module_content_result.rowcount or 0, 0),
content_attribute_count=max(attribute_result.rowcount or 0, 0),
content_item_count=max(content_result.rowcount or 0, 0),
definition_member_count=max(member_result.rowcount or 0, 0),
definition_count=max(definition_result.rowcount or 0, 0),
presentation_contract_count=max(presentation_result.rowcount or 0, 0),
search_facet_mapping_count=max(search_mapping_result.rowcount or 0, 0),
)

View File

@ -649,7 +649,7 @@ class ContentSeeder:
existing = await self._session.execute(
text(
f"""
select id, status, attribute_definition_set_id
select id, status, is_active, attribute_definition_set_id, metadata
from {self._schema}.content_items
where source_key = :source_key
for update
@ -662,7 +662,14 @@ class ContentSeeder:
if existing_row is not None:
existing_id = existing_row["id"]
existing_status = str(existing_row["status"])
if existing_status != "draft":
existing_metadata = dict(existing_row["metadata"] or {})
cleanup_marker = existing_metadata.get("_bootstrap_cleanup")
cleanup_archived = (
existing_status == "archived"
and isinstance(cleanup_marker, dict)
and bool(cleanup_marker.get("module_code"))
)
if existing_status != "draft" and not cleanup_archived:
raise ContentValidationError(
f"Refusing to overwrite existing {existing_status!r} content for "
f"source_key={source_key!r}; return it to draft first"
@ -686,6 +693,9 @@ class ContentSeeder:
title = :title,
slug = :slug,
summary = :summary,
status = 'draft',
is_active = true,
published_at = null,
metadata = cast(:metadata as jsonb),
version_no = version_no + 1,
updated_at = now()

View File

@ -91,16 +91,21 @@ class SeedOrchestrator:
await self._session.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
logger.info(
"Cleaned module content: module=%s contents=%s "
"search_facets=%s search_documents=%s associations=%s "
"attributes=%s content_items=%s",
"Archived module bootstrap state: module=%s definition_sets=%s "
"contents=%s search_facets=%s search_documents=%s associations=%s "
"content_items=%s definitions=%s members_removed=%s "
"presentation_contracts=%s search_mappings=%s",
cleanup_result.module_code,
cleanup_result.definition_set_count,
cleanup_result.content_count,
cleanup_result.search_facet_count,
cleanup_result.search_document_count,
cleanup_result.module_content_count,
cleanup_result.content_attribute_count,
cleanup_result.content_item_count,
cleanup_result.definition_count,
cleanup_result.definition_member_count,
cleanup_result.presentation_contract_count,
cleanup_result.search_facet_mapping_count,
)
try:

View File

@ -2094,191 +2094,140 @@ create or replace trigger trg_prevent_content_attribute_cycle
-- may temporarily contain an incomplete object tree.
-- ============================================================================
create or replace function content.validate_content_required_attributes(
CREATE OR REPLACE FUNCTION content.validate_content_required_attributes(
p_content_id uuid
)
returns void
language plpgsql
set search_path = pg_catalog, public
as $$
declare
v_content_kind content.content_kind_enum;
RETURNS void
LANGUAGE plpgsql
SET search_path = pg_catalog, public
AS $$
DECLARE
v_definition_set_id uuid;
v_content_status text;
v_missing_attribute_key text;
v_missing_parent_id uuid;
begin
BEGIN
-- --------------------------------------------------------------------------
-- CONTENT
-- --------------------------------------------------------------------------
select
ci.content_kind,
SELECT
ci.attribute_definition_set_id,
ci.status
into
v_content_kind,
INTO
v_definition_set_id,
v_content_status
from content.content_items ci
where ci.id =
p_content_id;
FROM content.content_items ci
WHERE ci.id = p_content_id;
-- Content may have been cascade-deleted.
if not found then
return;
end if;
IF NOT FOUND THEN
RETURN;
END IF;
-- Required validation matters only for published content.
if v_content_status <> 'published' then
return;
end if;
IF v_content_status <> 'published' THEN
RETURN;
END IF;
-- --------------------------------------------------------------------------
-- REQUIRED ROOT ATTRIBUTES
--
-- IMPORTANT:
-- Required root definitions must come from the exact definition set used by
-- this content item. Scoping only by content_kind incorrectly mixes required
-- attributes across templates that share the same content kind.
-- --------------------------------------------------------------------------
select
SELECT
ad.attribute_key
into
INTO
v_missing_attribute_key
from content.attribute_definitions ad
where ad.is_active = true
and ad.is_root = true
and ad.is_required = true
and (
ad.content_kind is null
or ad.content_kind =
v_content_kind
FROM content.attribute_definitions ad
WHERE ad.attribute_definition_set_id = v_definition_set_id
AND ad.is_active = true
AND ad.is_root = true
AND ad.is_required = true
AND NOT EXISTS (
SELECT 1
FROM content.content_attributes ca
WHERE ca.content_id = p_content_id
AND ca.attribute_definition_id = ad.id
AND ca.parent_attribute_value_id IS NULL
)
and not exists (
select 1
from content.content_attributes ca
where ca.content_id =
p_content_id
and ca.attribute_definition_id =
ad.id
and ca.parent_attribute_value_id
is null
)
order by
ORDER BY
ad.sort_order,
ad.attribute_key
LIMIT 1;
limit 1;
if found then
raise exception
IF FOUND THEN
RAISE EXCEPTION
'Cannot publish content %. Required root attribute "%" is missing',
p_content_id,
v_missing_attribute_key;
end if;
END IF;
-- --------------------------------------------------------------------------
-- REQUIRED CHILD ATTRIBUTES
--
-- Evaluates every existing object instance regardless of depth.
-- Evaluate every existing object instance regardless of depth. Keep the
-- validation inside the same definition set as the content item as an extra
-- guard against stale/cross-template member relationships.
--
-- Requirement applies when:
--
-- member.is_required = TRUE
-- OR
-- child definition.is_required = TRUE
-- member.is_required = TRUE
-- OR child definition.is_required = TRUE
-- --------------------------------------------------------------------------
select
SELECT
child_ad.attribute_key,
parent_ca.id
into
INTO
v_missing_attribute_key,
v_missing_parent_id
FROM content.content_attributes parent_ca
from content.content_attributes parent_ca
JOIN content.attribute_definitions parent_ad
ON parent_ad.id = parent_ca.attribute_definition_id
AND parent_ad.attribute_definition_set_id = v_definition_set_id
join content.attribute_definitions parent_ad
on parent_ad.id =
parent_ca.attribute_definition_id
JOIN content.attribute_definition_members adm
ON adm.parent_attribute_definition_id = parent_ca.attribute_definition_id
join content.attribute_definition_members adm
on adm.parent_attribute_definition_id =
parent_ca.attribute_definition_id
JOIN content.attribute_definitions child_ad
ON child_ad.id = adm.child_attribute_definition_id
AND child_ad.attribute_definition_set_id = v_definition_set_id
join content.attribute_definitions child_ad
on child_ad.id =
adm.child_attribute_definition_id
where parent_ca.content_id =
p_content_id
and parent_ad.definition_kind =
'object'
and child_ad.is_active = true
and (
WHERE parent_ca.content_id = p_content_id
AND parent_ad.definition_kind = 'object'
AND child_ad.is_active = true
AND (
adm.is_required = true
or child_ad.is_required = true
OR child_ad.is_required = true
)
and not exists (
select 1
from content.content_attributes child_ca
where child_ca.content_id =
p_content_id
and child_ca.parent_attribute_value_id =
parent_ca.id
and child_ca.attribute_definition_id =
child_ad.id
AND NOT EXISTS (
SELECT 1
FROM content.content_attributes child_ca
WHERE child_ca.content_id = p_content_id
AND child_ca.parent_attribute_value_id = parent_ca.id
AND child_ca.attribute_definition_id = child_ad.id
)
order by
ORDER BY
parent_ca.id,
adm.sort_order,
child_ad.attribute_key
LIMIT 1;
limit 1;
if found then
raise exception
IF FOUND THEN
RAISE EXCEPTION
'Cannot publish content %. Required child attribute "%" is missing under attribute value %',
p_content_id,
v_missing_attribute_key,
v_missing_parent_id;
END IF;
end if;
end;
END;
$$;
-- ============================================================================
-- CONTENT PUBLISH VALIDATION TRIGGER FUNCTION
-- ============================================================================