Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache table & database #77

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 40 additions & 7 deletions hq_superset/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
)
from cryptography.fernet import MultiFernet
from superset import db
from superset.extensions import cache_manager

from hq_superset.const import OAUTH2_DATABASE_NAME
from hq_superset.exceptions import TableMissing
Expand All @@ -16,6 +17,7 @@
get_hq_database,
)

cache = cache_manager.cache

@dataclass
class DataSetChange:
Expand All @@ -31,16 +33,14 @@ def update_dataset(self):
for a form or a case, which is identified by ``self.doc_id``. If
the form or case has been deleted, then the list will be empty.
"""
database = get_hq_database()
try:
sqla_table = next((
table for table in database.tables
if table.table_name == self.data_source_id
))
except StopIteration:
sqla_table = _get_data_source_table(self.data_source_id)
if not sqla_table:
# do not cache missing table results
_get_data_source_table.delete_memoized(self.data_source_id)
raise TableMissing(f'{self.data_source_id} table not found.')
table = sqla_table.get_sqla_table_object()

database = _get_cached_hq_database()
with (
database.get_sqla_engine_with_context() as engine,
engine.connect() as connection,
Expand All @@ -54,6 +54,39 @@ def update_dataset(self):
connection.execute(insert_stmt)


@cache.memoize(timeout=24*3600) # 1 day
def _get_data_source_table(data_source_id):
"""
Fetch table for datasource.
Try again after expiring database cache if not found first
"""

def _get_table():
database = _get_cached_hq_database()
return _get_sqla_table(database, data_source_id)

sqla_table = _get_table()
if not sqla_table:
_get_cached_hq_database.delete_memoized()
sqla_table = _get_table()
return sqla_table


def _get_sqla_table(database, data_source_id):
try:
return next((
table for table in database.tables
if table.table_name == data_source_id
))
except StopIteration:
return None


@cache.memoize(timeout=24*3600) # 1 day
def _get_cached_hq_database():
return get_hq_database()


class OAuth2Client(db.Model, OAuth2ClientMixin):
__bind_key__ = OAUTH2_DATABASE_NAME
__tablename__ = 'hq_oauth_client'
Expand Down