db.py 1.78 KB
Newer Older
1
import os
2
import logging
3
import json
4
5
from typing import Optional, Any
from typing_extensions import Self
Timothy J. Baek's avatar
Timothy J. Baek committed
6

7
8
9
10
from sqlalchemy import create_engine, types, Dialect
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.type_api import _T
11

12
from config import SRC_LOG_LEVELS, DATA_DIR, DATABASE_URL, BACKEND_DIR
13

14
15
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["DB"])
16

Timothy J. Baek's avatar
Timothy J. Baek committed
17

18
19
20
21
22
23
24
25
26
27
28
29
30
31
class JSONField(types.TypeDecorator):
    impl = types.Text
    cache_ok = True

    def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
        return json.dumps(value)

    def process_result_value(self, value: Optional[_T], dialect: Dialect) -> Any:
        if value is not None:
            return json.loads(value)

    def copy(self, **kw: Any) -> Self:
        return JSONField(self.impl.length)

32
33
34
35
36
37
38
    def db_value(self, value):
        return json.dumps(value)

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

Timothy J. Baek's avatar
Timothy J. Baek committed
39

40
41
42
43
# 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")
44
    log.info("Database migrated from Ollama-WebUI successfully.")
45
46
47
else:
    pass

48
49
50
51
52
53
54
55
56
SQLALCHEMY_DATABASE_URL = DATABASE_URL
if "sqlite" in SQLALCHEMY_DATABASE_URL:
    engine = create_engine(
        SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
    )
else:
    engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
57

58
59
60
61
62
63
64
65
66
67
68

def get_db():
    db = SessionLocal()
    try:
        yield db
        db.commit()
    except Exception as e:
        db.rollback()
        raise e
    finally:
        db.close()