Source code for codegen_database.ext.chart._contract

"""Leaf module: chart-extension contract shared with ledger.

Holds the ``metadata.info`` key and the registration check that
:mod:`codegen_database.ext.ledger.chart_functions` consumes.  Lives in its own
module — with no imports from ledger, sibling chart submodules, or
the chart package's ``__init__`` — so ledger code can pull it in
without round-tripping through ``codegen_database.ext.chart``'s package
initialization (which would loop back through
``codegen_database.ext.chart.date_bin`` →
``codegen_database.ext.ledger.functions`` →
``codegen_database.ext.ledger.__init__`` → ``chart_functions``).

The user-facing names (``CHART_SCHEMA_KEY``,
``CHART_EXTENSION_NAME``, ``assert_chart_extension_declared``) are
re-exported from :mod:`codegen_database.ext.chart` for backwards
compatibility.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from codegen_database.errors import CodegenDatabaseValidationError

if TYPE_CHECKING:
    from sqlalchemy import MetaData

CHART_EXTENSION_NAME = "codegen_database-chart"
"""Canonical name for :class:`~codegen_database.ext.chart.ChartExtension`."""

CHART_SCHEMA_KEY = "codegen_database_chart_schema"
"""``metadata.info`` key holding the chart extension's schema."""


[docs] def assert_chart_extension_declared(metadata: MetaData) -> None: """Raise if ``ChartExtension`` is not registered on *metadata*. Called by the ledger chart function builders to give a clear error when the user forgot to register the extension on their :class:`~codegen_database.config.CodegenDatabaseConfig`. Mirrors :func:`~codegen_database.pg_extension.assert_pg_extension_declared`: if the marker is absent but a :class:`~codegen_database.config.CodegenDatabaseConfig` is present on ``metadata.info``, the config's extension hooks are run eagerly so the check can succeed. Args: metadata: The :class:`~sqlalchemy.MetaData` to check. Raises: CodegenDatabaseValidationError: If the extension is not declared and cannot be resolved from the registered config. """ if metadata.info.get(CHART_SCHEMA_KEY): return cfg = metadata.info.get("codegen_database_config") if cfg is not None: for ext in cfg._resolved_extensions(): ext.configure_metadata(metadata) if metadata.info.get(CHART_SCHEMA_KEY): return msg = ( "Ledger chart functions require ChartExtension to be registered. " "Add `config.use(ChartExtension())` to your CodegenDatabaseConfig " "(from codegen_database.ext.chart import ChartExtension)." ) raise CodegenDatabaseValidationError(msg)