Skip to content

Commit

Permalink
Add method for asserting a table exists
Browse files Browse the repository at this point in the history
  • Loading branch information
David Besau committed Aug 27, 2021
1 parent 3d055ea commit 2f59abb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/db.py
@@ -1,11 +1,24 @@
from mysql.connector.abstracts import MySQLConnectionAbstract
from mysql.connector.cursor import MySQLCursorAbstract

import exception
from clui import log

SHOW_TABLES = "SHOW TABLES"


def test_connection(cnx: MySQLConnectionAbstract) -> None:
log("Testing database connection")
if cnx.is_connected():
log(f"Successfully connected to MySQL {cnx.get_server_info()} on {cnx.server_host}.")
else:
log("Connection not working!")


def assert_table_exists(cursor: MySQLCursorAbstract, table: str) -> None:
cursor.execute(SHOW_TABLES)
tables = cursor.fetchall()
for row in tables:
if table in row:
return
raise exception.TableNotFoundError(table)
9 changes: 9 additions & 0 deletions src/exception.py
@@ -0,0 +1,9 @@
class Error(Exception):
def __init__(self, message: str):
self.msg = message


class TableNotFoundError(Error):
def __init__(self, table: str):
message = f"Could not find table {table}"
super().__init__(message)

0 comments on commit 2f59abb

Please sign in to comment.