"""Initialise the NutriVision AI database. * For MySQL: creates the database (if it does not exist), then all tables. * For SQLite: creates the database file and all tables. Usage ----- python scripts/init_database.py """ import _bootstrap # noqa: F401 (adds src/ to sys.path) from nutrivision.config import get_config from nutrivision.logger import get_logger logger = get_logger("nutrivision.init_db") def create_mysql_database(settings: dict) -> bool: """Create the MySQL database if missing. Returns True on success.""" try: import pymysql except ImportError: logger.error("PyMySQL not installed. Run: pip install pymysql cryptography") return False try: conn = pymysql.connect( host=settings["host"], port=settings["port"], user=settings["user"], password=settings["password"], ) with conn.cursor() as cur: cur.execute( f"CREATE DATABASE IF NOT EXISTS `{settings['name']}` " "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" ) conn.commit() conn.close() logger.info("MySQL database '%s' is ready.", settings["name"]) return True except Exception as exc: logger.error("Could not create MySQL database: %s", exc) return False def main() -> None: settings = get_config().database_settings() print(f"Database backend: {settings['type']}") if settings["type"] == "mysql": if not create_mysql_database(settings): print( "\nMySQL is unavailable. The application will still run using " "the automatic SQLite fallback. To use SQLite explicitly, set " "DB_TYPE=sqlite in your .env file." ) # Create tables (uses the graceful MySQL->SQLite fallback under the hood). from nutrivision.database.db import init_db, get_engine init_db() print(f"Tables created. Active engine: {get_engine().url}") print("Database initialisation complete.") if __name__ == "__main__": main()