-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathviews.py
More file actions
68 lines (50 loc) · 1.79 KB
/
views.py
File metadata and controls
68 lines (50 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Logic to implement and set up views in SQLAlchemy
Adapted from https://github.com/sqlalchemy/sqlalchemy/wiki/Views
"""
import sqlalchemy as sa
from sqlalchemy.ext import compiler
from sqlalchemy.schema import DDLElement
from sqlalchemy.sql import table
# pylint: disable=abstract-method, missing-function-docstring, unused-argument, redefined-outer-name, protected-access, missing-class-docstring
class CreateView(DDLElement):
def __init__(self, name, selectable):
self.name = name
self.selectable = selectable
class DropView(DDLElement):
def __init__(self, name):
self.name = name
@compiler.compiles(CreateView)
def _create_view(element, compiler, **kw):
# pylint: disable=consider-using-f-string
return "CREATE VIEW %s AS %s" % (
element.name,
compiler.sql_compiler.process(element.selectable, literal_binds=True),
)
@compiler.compiles(DropView)
def _drop_view(element, compiler, **kw):
# pylint: disable=consider-using-f-string
return "DROP VIEW %s" % (element.name)
def view_exists(ddl, target, connection, **kw):
return ddl.name in sa.inspect(connection).get_view_names()
def view_doesnt_exist(ddl, target, connection, **kw):
return not view_exists(ddl, target, connection, **kw)
def view(name, metadata, selectable):
t = sa.table(
name,
*(
sa.Column(c.name, c.type, primary_key=c.primary_key)
for c in selectable.selected_columns
),
)
t.primary_key.update(c for c in t.c if c.primary_key)
sa.event.listen(
metadata,
"after_create",
CreateView(name, selectable).execute_if(callable_=view_doesnt_exist),
)
sa.event.listen(
metadata,
"before_drop",
DropView(name).execute_if(callable_=view_exists),
)
return t