Saltar a contenido

dorm.contrib.matview

Helpers de ciclo de vida para vistas materializadas de PostgreSQL — crear, refrescar (sync + async), eliminar, listar. Allowlist de identificadores e intervalos.

API

dorm.contrib.matview.create_matview(name: str, select_sql: str, *, using: str = 'default', with_data: bool = True, if_not_exists: bool = False) -> None

Run CREATE MATERIALIZED VIEW <name> AS <select_sql>.

Parameters:

Name Type Description Default
name str

view identifier (validated against the SQL allowlist).

required
select_sql str

the SELECT body. Passed verbatim — bind any parameters into the string upstream if the SELECT depends on caller-supplied values. The helper does not parameter-bind because PG rejects %s in DDL positions.

required
using str

database alias.

'default'
with_data bool

whether to populate the view immediately. Pass False to skip the initial scan (you must run :func:refresh_matview before the view returns rows).

True
if_not_exists bool

emit IF NOT EXISTS so repeat invocations on a fresh DB are idempotent.

False

dorm.contrib.matview.refresh_matview(name: str, *, using: str = 'default', concurrently: bool = False) -> None

Run REFRESH MATERIALIZED VIEW [CONCURRENTLY] <name>.

concurrently=True lets readers keep querying the view while the refresh runs — required for hot dashboards. The view must have at least one unique index for CONCURRENTLY to work (PG raises ERROR: cannot refresh materialized view "<name>" concurrently otherwise).

dorm.contrib.matview.arefresh_matview(name: str, *, using: str = 'default', concurrently: bool = False) -> None async

Async counterpart of :func:refresh_matview.

dorm.contrib.matview.drop_matview(name: str, *, using: str = 'default', if_exists: bool = True, cascade: bool = False) -> None

Run DROP MATERIALIZED VIEW. if_exists defaults to True so a teardown helper can run unconditionally; cascade propagates to dependent views / triggers.

dorm.contrib.matview.list_matviews(*, using: str = 'default', schema: str = 'public') -> list[str]

Return the materialised view names visible to the current role under schema.

Reads :pg:catalog:pg_matviews directly rather than the information_schema view — the latter doesn't list materialised views (they're technically not in the SQL standard catalog yet) and would silently return an empty list.

dorm.contrib.matview.matview_refresh_task(name: str, *, using: str = 'default', concurrently: bool = True)

Return a zero-arg callable that refreshes name. Designed to plug into the :mod:dorm.contrib.tasks decorator::

from dorm.contrib.matview import matview_refresh_task
from dorm.contrib.tasks import task, TaskQueue

q = TaskQueue(name="cron")

@task(q, name="dashboards.refresh", cron="*/5 * * * *")
def _refresh():
    matview_refresh_task("dashboard_v")()

Keeping the helper as a thin closure (instead of a full scheduler registration) avoids re-implementing scheduling logic that lives in :mod:dorm.contrib.tasks already.