import logging import os.path import sqlite3 from pathlib import Path def create_database(): """Creates the database.""" # Check if the database already exists if os.path.exists(Path(__file__).parent / "jarvis-commands-memory.sqlite"): logging.debug("Database already exists, skipping creation") return with open(Path(__file__).parent / "create_empty_database.sql", "r") as create_database_script: create_database_script = create_database_script.read() db = sqlite3.connect(Path(__file__).parent / "jarvis-commands-memory.sqlite") cursor = db.cursor() cursor.executescript(create_database_script) db.commit() db.close() logging.info("Database created") def do_request(request, args=None): """Execute SQL request and return result""" conn = sqlite3.connect(Path(__file__).parent / "jarvis-commands-memory.sqlite") cursor = conn.cursor() if not args: cursor.execute(request) else: cursor.execute(request, args) conn.commit() result = cursor.fetchall() conn.close() return result def add_response(response): """Add a response to the database""" # Check if the response is already in the database request = do_request("SELECT * FROM responses WHERE response=?", (response,)) if request: response_id = request[0][0] logging.debug("Response already in database (id: " + str(response_id) + ")") # If not, add it else: do_request("INSERT INTO responses (response) VALUES (?)", (response,)) response_id = do_request("SELECT * FROM responses WHERE response=?", (response,))[0][0] logging.debug("Response added to database with id " + str(response_id) + ": " + str(response)) return response_id def add_command(original_command, simplified_command, response): """Add a command to the database""" do_request("INSERT INTO commands (original_command, simplified_command, response) VALUES (?, ?, ?)", (original_command, simplified_command, add_response(response))) logging.debug("Query added to database: " + original_command + " -> " + response)