61 lines
1.4 KiB
Python
61 lines
1.4 KiB
Python
import sqlite3
|
|
import os
|
|
|
|
|
|
def create_connection(path: str, filename: str):
|
|
""" create a database connection to a SQLite database """
|
|
conn = None
|
|
try:
|
|
# Make the directory for the file to go into
|
|
create_directory(path)
|
|
|
|
print("Opening Database file and ensuring table integrity")
|
|
conn = sqlite3.connect(path + filename)
|
|
|
|
print("Database file open")
|
|
# Execute creation scripts
|
|
sql = open("scripts/create_tables.sql", "r")
|
|
conn.executescript(sql.read())
|
|
|
|
print("Table creation complete")
|
|
|
|
# Populate with test data if we are in Test Mode
|
|
if os.environ.get("ENVIRON") == "test":
|
|
sql = open("scripts/test_data.sql", "r")
|
|
conn.executescript(sql.read())
|
|
|
|
except sqlite3.Error as e:
|
|
print(e)
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
|
|
# Ensure a directory is created given a path to it
|
|
|
|
|
|
def create_directory(dir: str):
|
|
try:
|
|
os.makedirs(dir)
|
|
except FileExistsError:
|
|
pass
|
|
|
|
|
|
def remove_file(dir: str):
|
|
try:
|
|
os.remove(dir)
|
|
except FileNotFoundError:
|
|
pass
|
|
|
|
|
|
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)
|