|
| 1 | +""" |
| 2 | +Utilities for managing views via SQLAlchemy. |
| 3 | +""" |
| 4 | + |
| 5 | +from functools import partial |
| 6 | + |
| 7 | +import sqlalchemy as sa |
| 8 | +from sqlalchemy.ext import compiler |
| 9 | +from sqlalchemy.schema import DDLElement, MetaData |
| 10 | +from sqlalchemy.orm import Session |
| 11 | + |
| 12 | +from mavedb.db.base import Base |
| 13 | + |
| 14 | +# See: https://github.com/sqlalchemy/sqlalchemy/wiki/Views, https://github.com/jeffwidman/sqlalchemy-postgresql-materialized-views?tab=readme-ov-file |
| 15 | + |
| 16 | + |
| 17 | +class CreateView(DDLElement): |
| 18 | + def __init__(self, name: str, selectable: sa.Select, materialized: bool): |
| 19 | + self.name = name |
| 20 | + self.selectable = selectable |
| 21 | + self.materialized = materialized |
| 22 | + |
| 23 | + |
| 24 | +class DropView(DDLElement): |
| 25 | + def __init__(self, name: str, materialized: bool): |
| 26 | + self.name = name |
| 27 | + self.materialized = materialized |
| 28 | + |
| 29 | + |
| 30 | +class MaterializedView(Base): |
| 31 | + __abstract__ = True |
| 32 | + |
| 33 | + @classmethod |
| 34 | + def refresh(cls, connection, concurrently=True): |
| 35 | + """Refresh this materialized view.""" |
| 36 | + refresh_mat_view(connection, cls.__table__.fullname, concurrently) |
| 37 | + |
| 38 | + |
| 39 | +@compiler.compiles(CreateView) |
| 40 | +def _create_view(element: CreateView, compiler, **kw): |
| 41 | + return "CREATE %s %s AS %s" % ( |
| 42 | + "MATERIALIZED VIEW" if element.materialized else "VIEW", |
| 43 | + element.name, |
| 44 | + compiler.sql_compiler.process(element.selectable, literal_binds=True), |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +@compiler.compiles(DropView) |
| 49 | +def _drop_view(element: DropView, compiler, **kw): |
| 50 | + return "DROP %s %s" % ("MATERIALIZED VIEW" if element.materialized else "VIEW", element.name) |
| 51 | + |
| 52 | + |
| 53 | +def view_exists(ddl: CreateView, target, connection: sa.Connection, materialized: bool, **kw): |
| 54 | + inspector = sa.inspect(connection) |
| 55 | + if inspector is None: |
| 56 | + return False |
| 57 | + |
| 58 | + view_names = inspector.get_materialized_view_names() if ddl.materialized else inspector.get_view_names() |
| 59 | + return ddl.name in view_names |
| 60 | + |
| 61 | + |
| 62 | +def view_doesnt_exist(ddl: CreateView, target, connection: sa.Connection, materialized: bool, **kw): |
| 63 | + return not view_exists(ddl, target, connection, materialized, **kw) |
| 64 | + |
| 65 | + |
| 66 | +def view(name: str, selectable: sa.Select, metadata: MetaData = Base.metadata, materialized: bool = False): |
| 67 | + """ |
| 68 | + Register a view or materialized view to SQLAlchemy. Use this function to define a view on some arbitrary |
| 69 | + model class. |
| 70 | +
|
| 71 | + ``` |
| 72 | + class MyView(Base): |
| 73 | + __table__ = view( |
| 74 | + "my_view", |
| 75 | + select( |
| 76 | + MyModel.id.label("id"), |
| 77 | + MyModel.name.label("name"), |
| 78 | + ), |
| 79 | + materialized=False, |
| 80 | + ) |
| 81 | + ``` |
| 82 | +
|
| 83 | + When registered in this manner, SQLAlchemy will create and destroy the view along with other tables. You can |
| 84 | + then query this view as if it were an ORM object. |
| 85 | +
|
| 86 | + ``` |
| 87 | + results = db.query(select(MyView.col1).where(MyView.col2)).all() |
| 88 | + ``` |
| 89 | + """ |
| 90 | + t = sa.table( |
| 91 | + name, |
| 92 | + *(sa.Column(c.name, c.type, primary_key=c.primary_key) for c in selectable.selected_columns), |
| 93 | + ) |
| 94 | + t.primary_key.update(c for c in t.c if c.primary_key) # type: ignore |
| 95 | + |
| 96 | + # TODO: Figure out indices. |
| 97 | + if materialized: |
| 98 | + sa.event.listen( |
| 99 | + metadata, |
| 100 | + "after_create", |
| 101 | + CreateView(name, selectable, True).execute_if(callable_=partial(view_doesnt_exist, materialized=True)), |
| 102 | + ) |
| 103 | + sa.event.listen( |
| 104 | + metadata, |
| 105 | + "before_drop", |
| 106 | + DropView(name, True).execute_if(callable_=partial(view_exists, materialized=True)), |
| 107 | + ) |
| 108 | + |
| 109 | + else: |
| 110 | + sa.event.listen( |
| 111 | + metadata, |
| 112 | + "after_create", |
| 113 | + CreateView(name, selectable, False).execute_if(callable_=partial(view_doesnt_exist, materialized=False)), |
| 114 | + ) |
| 115 | + sa.event.listen( |
| 116 | + metadata, |
| 117 | + "before_drop", |
| 118 | + DropView(name, False).execute_if(callable_=partial(view_exists, materialized=False)), |
| 119 | + ) |
| 120 | + |
| 121 | + return t |
| 122 | + |
| 123 | + |
| 124 | +def refresh_mat_view(session: Session, name: str, concurrently=True): |
| 125 | + """ |
| 126 | + Refreshes a single materialized view, given by `name`. |
| 127 | + """ |
| 128 | + # since session.execute() bypasses autoflush, must manually flush in order |
| 129 | + # to include newly-created/modified objects in the refresh |
| 130 | + session.flush() |
| 131 | + _con = "CONCURRENTLY " if concurrently else "" |
| 132 | + session.execute(sa.text("REFRESH MATERIALIZED VIEW " + _con + name)) |
| 133 | + |
| 134 | + |
| 135 | +def refresh_all_mat_views(session: Session, concurrently=True): |
| 136 | + """ |
| 137 | + Refreshes all materialized views. Views are refreshed in non-deterministic order, |
| 138 | + so view definitions can't depend on each other. |
| 139 | + """ |
| 140 | + inspector = sa.inspect(session.connection()) |
| 141 | + |
| 142 | + if not inspector: |
| 143 | + return |
| 144 | + |
| 145 | + for mv in inspector.get_materialized_view_names(): |
| 146 | + refresh_mat_view(session, mv, concurrently) |
0 commit comments