Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use custom JSON type for database for more generic support #389

Merged
merged 3 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ragna/deploy/_api/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def _orm_to_schema_chat(chat: orm.Chat) -> schemas.Chat:
documents=documents,
source_storage=chat.source_storage,
assistant=chat.assistant,
params=chat.params, # type: ignore[arg-type]
params=chat.params,
),
messages=messages,
prepared=chat.prepared,
Expand Down
30 changes: 28 additions & 2 deletions ragna/deploy/_api/orm.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
import json
from typing import Any

from sqlalchemy import Column, ForeignKey, Table, types
from sqlalchemy.engine import Dialect
from sqlalchemy.orm import DeclarativeBase, relationship # type: ignore[attr-defined]

from ragna.core import MessageRole


class Json(types.TypeDecorator):
"""Universal JSON type which stores values as strings.

This is needed because sqlalchemy.types.JSON only works for a limited subset of
databases.
"""

impl = types.String

cache_ok = True

def process_bind_param(self, value: Any, dialect: Dialect) -> str:
return json.dumps(value)

def process_result_value(
self,
value: str, # type: ignore[override]
dialect: Dialect,
) -> Any:
return json.loads(value)


class Base(DeclarativeBase):
pass

Expand Down Expand Up @@ -34,7 +60,7 @@ class Document(Base):
name = Column(types.String)
# Mind the trailing underscore here. Unfortunately, this is necessary, because
# metadata without the underscore is reserved by SQLAlchemy
metadata_ = Column(types.JSON)
metadata_ = Column(Json)
chats = relationship(
"Chat",
secondary=document_chat_association_table,
Expand All @@ -59,7 +85,7 @@ class Chat(Base):
)
source_storage = Column(types.String)
assistant = Column(types.String)
params = Column(types.JSON)
params = Column(Json)
messages = relationship("Message", cascade="all, delete")
prepared = Column(types.Boolean)

Expand Down
Loading