acupedia-api/app/bootstrap/seed_content/cleanup.py

319 lines
12 KiB
Python

from __future__ import annotations
from dataclasses import dataclass
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
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_item_count: int
definition_member_count: int
definition_count: int
presentation_contract_count: int
search_facet_mapping_count: int
class ModuleContentCleaner:
"""Archive/reset all bootstrap-owned content configuration for one module.
``--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().upper()
if not normalized_code:
raise ValueError("module_code must be a non-empty string")
module_id = await self._session.scalar(
text(
f"""
SELECT id
FROM {self._schema}.modules
WHERE upper(code) = :module_code
"""
),
{"module_code": 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(
"""
CREATE TEMP TABLE IF NOT EXISTS tmp_acupedia_module_cleanup_content (
content_id uuid PRIMARY KEY
) ON COMMIT DROP
"""
)
)
await self._session.execute(
text("TRUNCATE TABLE tmp_acupedia_module_cleanup_content")
)
await self._session.execute(
text(
f"""
INSERT INTO tmp_acupedia_module_cleanup_content (content_id)
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
"""
),
{"module_id": module_id},
)
content_count = int(
await self._session.scalar(
text("SELECT count(*) FROM tmp_acupedia_module_cleanup_content")
)
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"""
DELETE FROM {self._schema}.content_search_facets csf
USING tmp_acupedia_module_cleanup_content t
WHERE csf.content_id = t.content_id
"""
)
)
search_document_result = await self._session.execute(
text(
f"""
DELETE FROM {self._schema}.content_search_documents csd
USING tmp_acupedia_module_cleanup_content t
WHERE csd.content_id = t.content_id
"""
)
)
# 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"
),
{"module_id": module_id},
)
# 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"""
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
"""
)
)
# 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}.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_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),
)