Created
June 11, 2019 11:00
-
-
Save kezabelle/42373e81266f588c7a439d5ef9ccaead to your computer and use it in GitHub Desktop.
Hacking on Django temp tables ORMish stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TempTabler(object): | |
__slots__ = ("queryset", "model", "name", "create_template", "drop_template") | |
def __init__(self, query, model, name): | |
# type: (QuerySet, Type[Model], str) -> None | |
self.queryset = query | |
class TempTable(model): | |
class Meta(model.Meta): | |
abstract = False | |
managed = False | |
db_table = name | |
self.model = TempTable | |
self.name = name | |
self.create_template = """ | |
CREATE TEMPORARY TABLE "{named}" as ( | |
{query} | |
)""" | |
self.drop_template = """ | |
DROP TABLE IF EXISTS {named} | |
""" | |
def create(self): | |
qs = self.queryset | |
compiler = qs.query.get_compiler(qs.db) | |
query, query_params = compiler.as_sql() | |
table = self.create_template.format(named=self.name, query=query) | |
with compiler.connection.cursor() as c: | |
c.execute(table, query_params) | |
return | |
def drop(self): | |
# type: () -> bool | |
assert self.model._meta.db_table == self.name, "Oh my goodness no" | |
qs = self.queryset | |
compiler = qs.query.get_compiler(qs.db) | |
table = self.drop_template.format(named=self.name) | |
with compiler.connection.cursor() as c: | |
c.execute(table) | |
return True | |
def __enter__(self): | |
self.create() | |
return self.model | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self.drop() | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment