Skip to content

Instantly share code, notes, and snippets.

@Alain1405
Forked from techniq/view.py
Created April 16, 2017 13:24
Show Gist options
  • Save Alain1405/04283c729f4ace67a8b8cba132a60669 to your computer and use it in GitHub Desktop.
Save Alain1405/04283c729f4ace67a8b8cba132a60669 to your computer and use it in GitHub Desktop.
SQLAlchemy View support
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Executable, ClauseElement
from sqlalchemy.schema import DDLElement, DropTable
from sqlalchemy.sql import table
from sqlalchemy.orm import Query
from . import db
class CreateView(DDLElement):
def __init__(self, name, selectable):
self.name = name
self.selectable = selectable
class DropView(DDLElement):
def __init__(self, name):
self.name = name
@compiles(CreateView)
def compile_create_view(element, compiler, **kw):
return "CREATE VIEW %s AS %s" % (element.name, compiler.sql_compiler.process(element.selectable))
@compiles(DropView)
def compile_drop_view(element, compiler, **kw):
return "DROP VIEW IF EXISTS %s" % (element.name)
def View(name, selectable):
"""
`View` support for SQLAlchemy
See: http://www.sqlalchemy.org/trac/wiki/UsageRecipes/Views
"""
t = table(name)
if isinstance(selectable, Query):
selectable = selectable.subquery()
for c in selectable.c:
c._make_proxy(t)
CreateView(name, selectable).execute_at('after-create', db.metadata)
DropView(name).execute_at('before-drop', db.metadata)
return t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment