2024-01-01 16:20:44 +00:00
|
|
|
import sqlite3
|
2024-01-04 18:59:51 +00:00
|
|
|
import os
|
2024-01-01 16:20:44 +00:00
|
|
|
|
|
|
|
|
2024-01-04 18:59:51 +00:00
|
|
|
def create_connection(path: str, filename: str):
|
2024-01-01 16:20:44 +00:00
|
|
|
""" create a database connection to a SQLite database """
|
|
|
|
conn = None
|
|
|
|
try:
|
2024-01-04 18:59:51 +00:00
|
|
|
# Make the directory for the file to go into
|
|
|
|
create_directory(path)
|
|
|
|
|
2024-01-01 17:52:44 +00:00
|
|
|
print("Opening Database file and ensuring table integrity")
|
2024-01-04 18:59:51 +00:00
|
|
|
conn = sqlite3.connect(path + filename)
|
2024-01-01 16:20:44 +00:00
|
|
|
|
2024-01-04 18:59:51 +00:00
|
|
|
print("Database file open")
|
2024-01-01 16:20:44 +00:00
|
|
|
# Execute creation scripts
|
2024-01-01 16:25:58 +00:00
|
|
|
sql = open("scripts/create_tables.sql", "r");
|
2024-01-01 16:20:44 +00:00
|
|
|
conn.executescript(sql.read())
|
2024-01-09 20:53:55 +00:00
|
|
|
|
2024-01-01 17:52:44 +00:00
|
|
|
print("Table creation complete")
|
2024-01-09 20:53:55 +00:00
|
|
|
|
|
|
|
# Populate with test data if we are in Test Mode
|
2024-01-09 22:20:32 +00:00
|
|
|
if os.environ.get("ENVIRON") == "test":
|
|
|
|
sql = open("scripts/test_data.sql", "r");
|
|
|
|
conn.executescript(sql.read())
|
|
|
|
|
2024-01-01 20:19:57 +00:00
|
|
|
except sqlite3.Error as e:
|
2024-01-01 16:20:44 +00:00
|
|
|
print(e)
|
|
|
|
finally:
|
|
|
|
if conn:
|
|
|
|
conn.close()
|
|
|
|
|
2024-01-04 18:59:51 +00:00
|
|
|
# Ensure a directory is created given a path to it
|
|
|
|
def create_directory(dir: str):
|
|
|
|
try:
|
|
|
|
os.makedirs(dir)
|
|
|
|
except FileExistsError:
|
|
|
|
pass
|
2024-01-01 16:20:44 +00:00
|
|
|
|
2024-01-09 20:53:55 +00:00
|
|
|
def remove_file(dir: str):
|
|
|
|
try:
|
|
|
|
os.remove(dir)
|
|
|
|
except FileNotFoundError:
|
|
|
|
pass
|
2024-01-09 22:20:32 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dir = r"./data/"
|
|
|
|
db_name = r"wmgzon.db"
|
|
|
|
|
|
|
|
# Check for test environ
|
|
|
|
if os.environ.get("ENVIRON") == "test":
|
|
|
|
# Remove the original test database
|
|
|
|
print("TEST ENVIRONMENT ACTIVE")
|
|
|
|
db_name = "test_" + db_name
|
|
|
|
remove_file(dir + db_name)
|
|
|
|
|
|
|
|
create_connection(dir, db_name)
|