659 lines
22 KiB
Python
659 lines
22 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any, Mapping, Sequence
|
|
from uuid import UUID
|
|
|
|
from sqlalchemy import text
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from .schema import CONTENT_SCHEMA, resolve_content_schema
|
|
|
|
from .models import DefinitionSet
|
|
from .validators import (
|
|
DefinitionConflictError,
|
|
DefinitionValidationError,
|
|
validate_definition_document,
|
|
)
|
|
|
|
|
|
class AttributeDefinitionSeeder:
|
|
"""
|
|
Idempotently seeds a definition set, recursive definitions, and
|
|
attribute_definition_members relationships.
|
|
|
|
Canonical identity:
|
|
(attribute_definition_set_id, attribute_key)
|
|
|
|
Canonical keys are hierarchy-path based, for example:
|
|
M0001_CT0001.name
|
|
M0002_CT0001.regional_anatomy
|
|
M0002_CT0001.regional_anatomy.structures
|
|
"""
|
|
|
|
def __init__(self, session: AsyncSession, *, schema: str = CONTENT_SCHEMA) -> None:
|
|
self._session = session
|
|
self._schema = resolve_content_schema(schema)
|
|
|
|
async def seed(self, document: Mapping[str, Any]) -> DefinitionSet:
|
|
validate_definition_document(document)
|
|
definition_set = await self._upsert_definition_set(document)
|
|
|
|
active_attribute_keys: set[str] = set()
|
|
active_member_pairs: set[tuple[UUID, UUID]] = set()
|
|
|
|
await self._seed_definition_level(
|
|
definition_set=definition_set,
|
|
raw_definitions=document["attribute_defs"],
|
|
parent_definition_id=None,
|
|
parent_attribute_key=None,
|
|
active_attribute_keys=active_attribute_keys,
|
|
active_member_pairs=active_member_pairs,
|
|
)
|
|
|
|
await self._deactivate_removed_definitions(
|
|
definition_set_id=definition_set.id,
|
|
active_attribute_keys=active_attribute_keys,
|
|
)
|
|
await self._remove_stale_members(
|
|
definition_set_id=definition_set.id,
|
|
active_member_pairs=active_member_pairs,
|
|
)
|
|
return definition_set
|
|
|
|
async def _seed_definition_level(
|
|
self,
|
|
*,
|
|
definition_set: DefinitionSet,
|
|
raw_definitions: Sequence[Mapping[str, Any]],
|
|
parent_definition_id: UUID | None,
|
|
parent_attribute_key: str | None,
|
|
active_attribute_keys: set[str],
|
|
active_member_pairs: set[tuple[UUID, UUID]],
|
|
) -> None:
|
|
for sort_order, raw in enumerate(raw_definitions):
|
|
code = str(raw["code"]).strip()
|
|
attribute_key = self._build_attribute_key(
|
|
definition_set=definition_set,
|
|
parent_attribute_key=parent_attribute_key,
|
|
code=code,
|
|
)
|
|
active_attribute_keys.add(attribute_key)
|
|
|
|
child_definition_id = await self._upsert_definition(
|
|
definition_set=definition_set,
|
|
raw=raw,
|
|
attribute_key=attribute_key,
|
|
is_root=parent_definition_id is None,
|
|
sort_order=sort_order,
|
|
)
|
|
|
|
if parent_definition_id is not None:
|
|
await self._upsert_member(
|
|
parent_definition_id=parent_definition_id,
|
|
child_definition_id=child_definition_id,
|
|
sort_order=sort_order,
|
|
is_required=bool(
|
|
raw.get("member_required", raw.get("is_required", raw.get("required", False)))
|
|
),
|
|
metadata=dict(raw.get("member_metadata") or {}),
|
|
)
|
|
active_member_pairs.add((parent_definition_id, child_definition_id))
|
|
|
|
if str(raw.get("definition_kind", "scalar")).strip() == "object":
|
|
await self._seed_definition_level(
|
|
definition_set=definition_set,
|
|
raw_definitions=raw["children"],
|
|
parent_definition_id=child_definition_id,
|
|
parent_attribute_key=attribute_key,
|
|
active_attribute_keys=active_attribute_keys,
|
|
active_member_pairs=active_member_pairs,
|
|
)
|
|
|
|
@staticmethod
|
|
def _build_attribute_key(
|
|
*,
|
|
definition_set: DefinitionSet,
|
|
parent_attribute_key: str | None,
|
|
code: str,
|
|
) -> str:
|
|
if parent_attribute_key is None:
|
|
return f"{definition_set.attribute_prefix_code}.{code}"
|
|
return f"{parent_attribute_key}.{code}"
|
|
|
|
async def _upsert_definition_set(
|
|
self,
|
|
document: Mapping[str, Any],
|
|
) -> DefinitionSet:
|
|
code = str(
|
|
document["code"]
|
|
).strip()
|
|
|
|
name = str(
|
|
document["name"]
|
|
).strip()
|
|
|
|
attribute_prefix_code = str(
|
|
document[
|
|
"attribute_prefix_code"
|
|
]
|
|
).strip()
|
|
|
|
attribute_prefix_name = str(
|
|
document[
|
|
"attribute_prefix_name"
|
|
]
|
|
).strip()
|
|
|
|
content_kind = document.get(
|
|
"content_kind"
|
|
)
|
|
|
|
description = document.get(
|
|
"description"
|
|
)
|
|
|
|
metadata = json.dumps(
|
|
document.get("metadata")
|
|
or {}
|
|
)
|
|
|
|
# ================================================================
|
|
# Resolve existing logical definition set.
|
|
#
|
|
# attribute_prefix_code is the canonical identity.
|
|
#
|
|
# code is also checked to detect inconsistent historical rows.
|
|
# ================================================================
|
|
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
id,
|
|
code,
|
|
attribute_prefix_code
|
|
from {self._schema}.attribute_definition_sets
|
|
where code = :code
|
|
or attribute_prefix_code =
|
|
:attribute_prefix_code
|
|
for update
|
|
"""
|
|
),
|
|
{
|
|
"code": code,
|
|
"attribute_prefix_code": (
|
|
attribute_prefix_code
|
|
),
|
|
},
|
|
)
|
|
|
|
existing_rows = (
|
|
result.mappings().all()
|
|
)
|
|
|
|
# ================================================================
|
|
# More than one physical row matches the logical identity.
|
|
#
|
|
# Example:
|
|
#
|
|
# row A:
|
|
# code = OLD_CODE
|
|
# prefix = M0001_CT0002
|
|
#
|
|
# row B:
|
|
# code = M0001_CT0002
|
|
# prefix = OTHER_PREFIX
|
|
#
|
|
# That is ambiguous and must not be silently merged.
|
|
# ================================================================
|
|
|
|
if len(existing_rows) > 1:
|
|
matches = [
|
|
{
|
|
"id": str(row["id"]),
|
|
"code": row["code"],
|
|
"attribute_prefix_code": (
|
|
row[
|
|
"attribute_prefix_code"
|
|
]
|
|
),
|
|
}
|
|
for row in existing_rows
|
|
]
|
|
|
|
raise DefinitionConflictError(
|
|
"Multiple attribute definition sets "
|
|
"match the requested identity. "
|
|
f"requested_code={code!r}, "
|
|
f"requested_prefix="
|
|
f"{attribute_prefix_code!r}, "
|
|
f"matches={matches!r}"
|
|
)
|
|
|
|
# ================================================================
|
|
# Existing logical definition set.
|
|
#
|
|
# UPDATE same UUID.
|
|
# ================================================================
|
|
|
|
if existing_rows:
|
|
existing = existing_rows[0]
|
|
|
|
definition_set_id = (
|
|
existing["id"]
|
|
)
|
|
|
|
await self._session.execute(
|
|
text(
|
|
f"""
|
|
update {self._schema}.attribute_definition_sets
|
|
|
|
set
|
|
code =
|
|
:code,
|
|
|
|
name =
|
|
:name,
|
|
|
|
attribute_prefix_code =
|
|
:attribute_prefix_code,
|
|
|
|
attribute_prefix_name =
|
|
:attribute_prefix_name,
|
|
|
|
content_kind =
|
|
cast(
|
|
:content_kind
|
|
as {self._schema}.content_kind_enum
|
|
),
|
|
|
|
description =
|
|
:description,
|
|
|
|
is_active =
|
|
true,
|
|
|
|
metadata =
|
|
cast(
|
|
:metadata
|
|
as jsonb
|
|
),
|
|
|
|
updated_at =
|
|
now()
|
|
|
|
where id =
|
|
:definition_set_id
|
|
|
|
returning
|
|
id,
|
|
code,
|
|
name,
|
|
attribute_prefix_code,
|
|
attribute_prefix_name,
|
|
content_kind::text
|
|
as content_kind,
|
|
description
|
|
"""
|
|
),
|
|
{
|
|
"definition_set_id": (
|
|
definition_set_id
|
|
),
|
|
"code": code,
|
|
"name": name,
|
|
"attribute_prefix_code": (
|
|
attribute_prefix_code
|
|
),
|
|
"attribute_prefix_name": (
|
|
attribute_prefix_name
|
|
),
|
|
"content_kind": (
|
|
content_kind
|
|
),
|
|
"description": (
|
|
description
|
|
),
|
|
"metadata": metadata,
|
|
},
|
|
)
|
|
|
|
row = (
|
|
(
|
|
await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
id,
|
|
code,
|
|
name,
|
|
attribute_prefix_code,
|
|
attribute_prefix_name,
|
|
content_kind::text
|
|
as content_kind,
|
|
description
|
|
from {self._schema}.attribute_definition_sets
|
|
where id =
|
|
:definition_set_id
|
|
"""
|
|
),
|
|
{
|
|
"definition_set_id": (
|
|
definition_set_id
|
|
)
|
|
},
|
|
)
|
|
)
|
|
.mappings()
|
|
.one()
|
|
)
|
|
|
|
return DefinitionSet(
|
|
id=row["id"],
|
|
code=row["code"],
|
|
name=row["name"],
|
|
attribute_prefix_code=row[
|
|
"attribute_prefix_code"
|
|
],
|
|
attribute_prefix_name=row[
|
|
"attribute_prefix_name"
|
|
],
|
|
content_kind=row[
|
|
"content_kind"
|
|
],
|
|
description=row[
|
|
"description"
|
|
],
|
|
)
|
|
|
|
# ================================================================
|
|
# First occurrence.
|
|
# ================================================================
|
|
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
insert into {self._schema}.attribute_definition_sets (
|
|
code,
|
|
name,
|
|
attribute_prefix_code,
|
|
attribute_prefix_name,
|
|
content_kind,
|
|
description,
|
|
is_active,
|
|
metadata
|
|
)
|
|
values (
|
|
:code,
|
|
:name,
|
|
:attribute_prefix_code,
|
|
:attribute_prefix_name,
|
|
|
|
cast(
|
|
:content_kind
|
|
as {self._schema}.content_kind_enum
|
|
),
|
|
|
|
:description,
|
|
true,
|
|
|
|
cast(
|
|
:metadata
|
|
as jsonb
|
|
)
|
|
)
|
|
|
|
returning
|
|
id,
|
|
code,
|
|
name,
|
|
attribute_prefix_code,
|
|
attribute_prefix_name,
|
|
content_kind::text
|
|
as content_kind,
|
|
description
|
|
"""
|
|
),
|
|
{
|
|
"code": code,
|
|
"name": name,
|
|
"attribute_prefix_code": (
|
|
attribute_prefix_code
|
|
),
|
|
"attribute_prefix_name": (
|
|
attribute_prefix_name
|
|
),
|
|
"content_kind": content_kind,
|
|
"description": description,
|
|
"metadata": metadata,
|
|
},
|
|
)
|
|
|
|
row = result.mappings().one()
|
|
|
|
return DefinitionSet(
|
|
id=row["id"],
|
|
code=row["code"],
|
|
name=row["name"],
|
|
attribute_prefix_code=row[
|
|
"attribute_prefix_code"
|
|
],
|
|
attribute_prefix_name=row[
|
|
"attribute_prefix_name"
|
|
],
|
|
content_kind=row[
|
|
"content_kind"
|
|
],
|
|
description=row[
|
|
"description"
|
|
],
|
|
)
|
|
|
|
async def _upsert_definition(
|
|
self,
|
|
*,
|
|
definition_set: DefinitionSet,
|
|
raw: Mapping[str, Any],
|
|
attribute_key: str,
|
|
is_root: bool,
|
|
sort_order: int,
|
|
) -> UUID:
|
|
definition_kind = str(raw.get("definition_kind", "scalar")).strip()
|
|
data_type = str(raw["data_type"]).strip() if definition_kind == "scalar" else None
|
|
|
|
metadata = dict(raw.get("metadata") or {})
|
|
if definition_kind == "scalar" and "default" in raw:
|
|
metadata["default"] = raw.get("default")
|
|
else:
|
|
metadata.pop("default", None)
|
|
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
insert into {self._schema}.attribute_definitions (
|
|
attribute_definition_set_id, content_kind, attribute_key,
|
|
attribute_label, data_type, definition_kind, is_root,
|
|
description, is_required, is_searchable, is_filterable,
|
|
is_multivalue, allowed_values, sort_order, is_active, metadata
|
|
)
|
|
values (
|
|
:definition_set_id,
|
|
cast(:content_kind as {self._schema}.content_kind_enum),
|
|
:attribute_key, :attribute_label, :data_type, :definition_kind,
|
|
:is_root, :description, :is_required, :is_searchable,
|
|
:is_filterable, :is_multivalue,
|
|
cast(:allowed_values as jsonb), :sort_order, true,
|
|
cast(:metadata as jsonb)
|
|
)
|
|
on conflict (attribute_definition_set_id, attribute_key)
|
|
where attribute_definition_set_id is not null
|
|
do update set
|
|
content_kind = excluded.content_kind,
|
|
attribute_label = excluded.attribute_label,
|
|
data_type = excluded.data_type,
|
|
definition_kind = excluded.definition_kind,
|
|
is_root = excluded.is_root,
|
|
description = excluded.description,
|
|
is_required = excluded.is_required,
|
|
is_searchable = excluded.is_searchable,
|
|
is_filterable = excluded.is_filterable,
|
|
is_multivalue = excluded.is_multivalue,
|
|
allowed_values = excluded.allowed_values,
|
|
sort_order = excluded.sort_order,
|
|
is_active = true,
|
|
metadata = excluded.metadata,
|
|
updated_at = now()
|
|
returning id
|
|
"""
|
|
),
|
|
{
|
|
"definition_set_id": definition_set.id,
|
|
"content_kind": definition_set.content_kind,
|
|
"attribute_key": attribute_key,
|
|
"attribute_label": str(raw["name"]).strip(),
|
|
"data_type": data_type,
|
|
"definition_kind": definition_kind,
|
|
"is_root": is_root,
|
|
"description": raw.get("description"),
|
|
"is_required": bool(raw.get("is_required", raw.get("required", False))),
|
|
"is_searchable": bool(raw.get("is_searchable", raw.get("searchable", True))),
|
|
"is_filterable": bool(raw.get("is_filterable", raw.get("filterable", False))),
|
|
"is_multivalue": bool(raw.get("is_multivalue", raw.get("multivalue", False))),
|
|
"allowed_values": (
|
|
json.dumps(raw.get("allowed_values"))
|
|
if raw.get("allowed_values") is not None
|
|
else None
|
|
),
|
|
"sort_order": sort_order,
|
|
"metadata": json.dumps(metadata),
|
|
},
|
|
)
|
|
definition_id = result.scalar_one_or_none()
|
|
if definition_id is None:
|
|
raise DefinitionConflictError(
|
|
f"Unable to upsert attribute definition {attribute_key!r}"
|
|
)
|
|
return definition_id
|
|
|
|
async def _upsert_member(
|
|
self,
|
|
*,
|
|
parent_definition_id: UUID,
|
|
child_definition_id: UUID,
|
|
sort_order: int,
|
|
is_required: bool,
|
|
metadata: Mapping[str, Any],
|
|
) -> None:
|
|
await self._session.execute(
|
|
text(
|
|
f"""
|
|
insert into {self._schema}.attribute_definition_members (
|
|
parent_attribute_definition_id, child_attribute_definition_id,
|
|
sort_order, is_required, metadata
|
|
)
|
|
values (
|
|
:parent_definition_id, :child_definition_id,
|
|
:sort_order, :is_required, cast(:metadata as jsonb)
|
|
)
|
|
on conflict (
|
|
parent_attribute_definition_id,
|
|
child_attribute_definition_id
|
|
)
|
|
do update set
|
|
sort_order = excluded.sort_order,
|
|
is_required = excluded.is_required,
|
|
metadata = excluded.metadata
|
|
"""
|
|
),
|
|
{
|
|
"parent_definition_id": parent_definition_id,
|
|
"child_definition_id": child_definition_id,
|
|
"sort_order": sort_order,
|
|
"is_required": is_required,
|
|
"metadata": json.dumps(dict(metadata)),
|
|
},
|
|
)
|
|
|
|
async def _deactivate_removed_definitions(
|
|
self,
|
|
*,
|
|
definition_set_id: UUID,
|
|
active_attribute_keys: set[str],
|
|
) -> None:
|
|
if not active_attribute_keys:
|
|
raise DefinitionValidationError(
|
|
"Cannot reconcile definition set because active_attribute_keys is empty"
|
|
)
|
|
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select id, attribute_key, is_active
|
|
from {self._schema}.attribute_definitions
|
|
where attribute_definition_set_id = :definition_set_id
|
|
"""
|
|
),
|
|
{"definition_set_id": definition_set_id},
|
|
)
|
|
|
|
stale_ids = [
|
|
row["id"]
|
|
for row in result.mappings()
|
|
if row["is_active"] and row["attribute_key"] not in active_attribute_keys
|
|
]
|
|
|
|
if stale_ids:
|
|
await self._session.execute(
|
|
text(
|
|
f"""
|
|
update {self._schema}.attribute_definitions
|
|
set is_active = false, updated_at = now()
|
|
where id = any(:ids)
|
|
"""
|
|
),
|
|
{"ids": stale_ids},
|
|
)
|
|
|
|
async def _remove_stale_members(
|
|
self,
|
|
*,
|
|
definition_set_id: UUID,
|
|
active_member_pairs: set[tuple[UUID, UUID]],
|
|
) -> None:
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
adm.id,
|
|
adm.parent_attribute_definition_id,
|
|
adm.child_attribute_definition_id
|
|
from {self._schema}.attribute_definition_members adm
|
|
join {self._schema}.attribute_definitions parent_ad
|
|
on parent_ad.id = adm.parent_attribute_definition_id
|
|
where parent_ad.attribute_definition_set_id = :definition_set_id
|
|
"""
|
|
),
|
|
{"definition_set_id": definition_set_id},
|
|
)
|
|
|
|
stale_member_ids = []
|
|
for row in result.mappings():
|
|
pair = (
|
|
row["parent_attribute_definition_id"],
|
|
row["child_attribute_definition_id"],
|
|
)
|
|
if pair not in active_member_pairs:
|
|
stale_member_ids.append(row["id"])
|
|
|
|
if stale_member_ids:
|
|
await self._session.execute(
|
|
text(
|
|
f"""
|
|
delete from {self._schema}.attribute_definition_members
|
|
where id = any(:ids)
|
|
"""
|
|
),
|
|
{"ids": stale_member_ids},
|
|
)
|