2024-03-02 16:19:24 +08:00
|
|
|
import os
|
2024-03-21 07:11:36 +08:00
|
|
|
import logging
|
2024-05-30 21:44:13 +08:00
|
|
|
import json
|
2024-06-21 20:58:57 +08:00
|
|
|
from contextlib import contextmanager
|
2024-06-18 21:03:31 +08:00
|
|
|
from typing import Optional, Any
|
|
|
|
from typing_extensions import Self
|
2023-12-26 13:44:28 +08:00
|
|
|
|
2024-06-18 21:03:31 +08:00
|
|
|
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
|
2024-05-30 19:55:58 +08:00
|
|
|
|
2024-05-30 21:44:13 +08:00
|
|
|
from config import SRC_LOG_LEVELS, DATA_DIR, DATABASE_URL, BACKEND_DIR
|
2024-05-30 19:55:58 +08:00
|
|
|
|
2024-03-21 07:11:36 +08:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
log.setLevel(SRC_LOG_LEVELS["DB"])
|
2024-01-20 04:13:09 +08:00
|
|
|
|
2024-06-20 19:53:23 +08:00
|
|
|
|
2024-06-18 21:03:31 +08:00
|
|
|
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)
|
|
|
|
|
2024-05-22 05:05:16 +08:00
|
|
|
def db_value(self, value):
|
|
|
|
return json.dumps(value)
|
|
|
|
|
|
|
|
def python_value(self, value):
|
|
|
|
if value is not None:
|
|
|
|
return json.loads(value)
|
|
|
|
|
2024-06-20 19:53:23 +08:00
|
|
|
|
2024-03-02 16:19:24 +08:00
|
|
|
# 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")
|
2024-04-25 01:10:18 +08:00
|
|
|
log.info("Database migrated from Ollama-WebUI successfully.")
|
2024-03-02 16:19:24 +08:00
|
|
|
else:
|
|
|
|
pass
|
|
|
|
|
2024-06-18 21:03:31 +08:00
|
|
|
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)
|
2024-06-21 20:58:57 +08:00
|
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, expire_on_commit=False)
|
2024-06-18 21:03:31 +08:00
|
|
|
Base = declarative_base()
|
2024-06-17 06:25:48 +08:00
|
|
|
|
2024-06-18 21:03:31 +08:00
|
|
|
|
2024-06-21 20:58:57 +08:00
|
|
|
@contextmanager
|
|
|
|
def get_session():
|
2024-06-18 21:03:31 +08:00
|
|
|
db = SessionLocal()
|
|
|
|
try:
|
|
|
|
yield db
|
|
|
|
db.commit()
|
|
|
|
except Exception as e:
|
|
|
|
db.rollback()
|
|
|
|
raise e
|
2024-06-21 20:58:57 +08:00
|
|
|
|