From f535b61341da0f89aa39e970dac41cc6e4ec3ed2 Mon Sep 17 00:00:00 2001 From: rluzuriaga Date: Wed, 17 Jun 2020 16:07:13 -0700 Subject: [PATCH] Handle CLI load into existing tables gracefully (PR #300) - Add exception handling for SQLite, PostgreSQL, and MySQL. Sqlalchemy gives different exceptions for each database engine so I have seperated each exception for each engine. The error message passed by each engine is also different so that is checked as well. - Once the function gets one of those exceptions the following message is outputed and the program ends: `ERROR: Table 'TABLENAME' already exists in the database. Did you mean to use 'pokedex load -D'` - If the error is not that a table already exists, then the output will just be the full error from sqlalchemy. That way if someone runs into that error it can be reported as an issue and whoever can help would see the full error. --- Resolves part of issue #16 --- pokedex/db/load.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/pokedex/db/load.py b/pokedex/db/load.py index f34ee46..b787672 100644 --- a/pokedex/db/load.py +++ b/pokedex/db/load.py @@ -193,7 +193,29 @@ def load(session, tables=[], directory=None, drop_tables=False, verbose=False, s print_start('Creating tables') for n, table in enumerate(table_objs): - table.create(bind=engine) + try: + table.create(bind=engine) + + # Exceptions for handling the error thrown when trying to load + # the database with a table that already exists. + except ( + sqlalchemy.exc.OperationalError, # Exception used for SQLite + sqlalchemy.exc.ProgrammingError, # Exception used for PostgreSQL + sqlalchemy.exc.InternalError # Exception used for MySQL + ) as error: + + if "already exists" in str(error.orig): + print("\n\nERROR: The table '{}' already exists in the database. " + "Did you mean to use 'pokedex load -D'".format(table)) + sys.exit(1) + + # If it happens to be some other error but raised by the same + # exception, then an unexpected error message is sent with + # the error included + else: + print("\n\n UNEXPECTED ERROR: ", error) + sys.exit(1) + print_status('%s/%s' % (n, len(table_objs))) print_done()