db.py 1.46 KB
Newer Older
1
import os
2
import logging
3
import json
Timothy J. Baek's avatar
Timothy J. Baek committed
4

5
from peewee import *
6
7
from peewee_migrate import Router

8
from apps.webui.internal.wrappers import register_connection
9
from config import SRC_LOG_LEVELS, DATA_DIR, DATABASE_URL, BACKEND_DIR
10

11
12
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["DB"])
13

14
15
16
17
18
19
20
21
class JSONField(TextField):
    def db_value(self, value):
        return json.dumps(value)

    def python_value(self, value):
        if value is not None:
            return json.loads(value)

22
23
24
25
# Check if the file exists
if os.path.exists(f"{DATA_DIR}/ollama.db"):
    # Rename the file
    os.rename(f"{DATA_DIR}/ollama.db", f"{DATA_DIR}/webui.db")
26
    log.info("Database migrated from Ollama-WebUI successfully.")
27
28
29
else:
    pass

30
31
32
33
34
35
36
37
38
39
40
41

# The `register_connection` function encapsulates the logic for setting up 
# the database connection based on the connection string, while `connect` 
# is a Peewee-specific method to manage the connection state and avoid errors 
# when a connection is already open.
try:
    DB = register_connection(DATABASE_URL)
    log.info(f"Connected to a {DB.__class__.__name__} database.")
except Exception as e:
    log.error(f"Failed to initialize the database connection: {e}")
    raise

Tang Ziya's avatar
Tang Ziya committed
42
router = Router(
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
43
44
45
    DB,
    migrate_dir=BACKEND_DIR / "apps" / "webui" / "internal" / "migrations",
    logger=log,
Tang Ziya's avatar
Tang Ziya committed
46
)
47
router.run()
48
try:
49
    DB.connect(reuse_if_open=True)
50
51
52
except OperationalError as e:
    log.info(f"Failed to connect to database again due to: {e}")
    pass