From 87fd5367a13cbae75f60967c5558093c5e910eb1 Mon Sep 17 00:00:00 2001 From: Lance Edgar Date: Tue, 31 Mar 2020 14:09:51 -0500 Subject: [PATCH] Add `table_exists()` util function --- corepos/db/util.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/corepos/db/util.py b/corepos/db/util.py index 324a057..f16da72 100644 --- a/corepos/db/util.py +++ b/corepos/db/util.py @@ -36,3 +36,25 @@ def get_last_card_number(session): """ return session.query(sa.func.max(corepos.Customer.card_number))\ .scalar() or 0 + + +def table_exists(session, model_class): + """ + Determine if a table exists in the database. + + :param session: SQLAlchemy session object, opened against the database in + question. + + :param model_class: The model class associated with the table in question. + + :returns: Boolean indicating if the table exists. + """ + try: + session.query(model_class).count() + except sa.exc.ProgrammingError as error: + if "doesn't exist" in str(error): + return False + else: + raise + else: + return True