"""Sync Entity-Archetypen und Felddefinitionen in PostgreSQL — AP1.10b / AP2.0b.""" from __future__ import annotations import json from db import get_connection from entity_archetypes.registry import ENTITY_ARCHETYPES from entity_fields.definitions import FIELD_DEFINITIONS def sync_entity_field_registry_to_db() -> int: conn = get_connection() try: with conn.cursor() as cur: for archetype in ENTITY_ARCHETYPES: cur.execute( """ INSERT INTO entity_archetypes ( archetype_key, entity_type, label, description, is_system ) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (archetype_key) DO UPDATE SET entity_type = EXCLUDED.entity_type, label = EXCLUDED.label, description = EXCLUDED.description, is_system = EXCLUDED.is_system, updated_at = NOW() """, ( archetype["key"], archetype["entity_type"], archetype["label"], archetype["description"], archetype["is_system"], ), ) for field_def in FIELD_DEFINITIONS: validation_json = field_def.get("validation_json") or {} cur.execute( """ INSERT INTO field_definitions ( archetype_key, field_key, field_type, label, required, searchable, sort_order, validation_json ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s::jsonb) ON CONFLICT (archetype_key, field_key) DO UPDATE SET field_type = EXCLUDED.field_type, label = EXCLUDED.label, required = EXCLUDED.required, searchable = EXCLUDED.searchable, sort_order = EXCLUDED.sort_order, validation_json = EXCLUDED.validation_json, updated_at = NOW() """, ( field_def["archetype_key"], field_def["field_key"], field_def["field_type"], field_def["label"], field_def["required"], field_def["searchable"], field_def["sort_order"], json.dumps(validation_json), ), ) conn.commit() print( "[entity_fields] Sync OK — " f"{len(ENTITY_ARCHETYPES)} Archetyp(en), " f"{len(FIELD_DEFINITIONS)} Felddefinition(en)" ) return 0 except Exception as exc: conn.rollback() print(f"[entity_fields] Sync FAIL: {exc}") return 1