Spaces:
Sleeping
Sleeping
File size: 2,120 Bytes
c0afe44 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | """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()
|