open-webui/backend/open_webui/migrations/versions/6a39f3d8e55c_add_knowledge_table.py

81 lines
2.4 KiB
Python
Raw Normal View History

2024-10-02 05:45:04 +00:00
"""Add knowledge table
2024-10-02 00:35:10 +00:00
Revision ID: 6a39f3d8e55c
Revises: c0fbf31ca0db
Create Date: 2024-10-01 14:02:35.241684
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column, select
2024-10-02 00:46:56 +00:00
import json
2024-10-02 00:35:10 +00:00
revision = "6a39f3d8e55c"
down_revision = "c0fbf31ca0db"
branch_labels = None
depends_on = None
def upgrade():
2024-10-02 05:45:04 +00:00
# Creating the 'knowledge' table
print("Creating knowledge table")
knowledge_table = op.create_table(
"knowledge",
2024-10-02 00:35:10 +00:00
sa.Column("id", sa.Text(), primary_key=True),
sa.Column("user_id", sa.Text(), nullable=False),
sa.Column("name", sa.Text(), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("data", sa.JSON(), nullable=True),
sa.Column("meta", sa.JSON(), nullable=True),
sa.Column("created_at", sa.BigInteger(), nullable=False),
sa.Column("updated_at", sa.BigInteger(), nullable=True),
)
2024-10-02 05:45:04 +00:00
print("Migrating data from document table to knowledge table")
2024-10-02 00:35:10 +00:00
# Representation of the existing 'document' table
document_table = table(
"document",
column("collection_name", sa.String()),
column("user_id", sa.String()),
column("name", sa.String()),
column("title", sa.Text()),
2024-10-02 00:46:56 +00:00
column("content", sa.Text()),
2024-10-02 00:35:10 +00:00
column("timestamp", sa.BigInteger()),
)
# Select all from existing document table
documents = op.get_bind().execute(
select(
document_table.c.collection_name,
document_table.c.user_id,
document_table.c.name,
document_table.c.title,
2024-10-02 00:46:56 +00:00
document_table.c.content,
2024-10-02 00:35:10 +00:00
document_table.c.timestamp,
)
)
2024-10-02 05:45:04 +00:00
# Insert data into knowledge table from document table
2024-10-02 00:35:10 +00:00
for doc in documents:
op.get_bind().execute(
2024-10-02 05:45:04 +00:00
knowledge_table.insert().values(
2024-10-02 00:35:10 +00:00
id=doc.collection_name,
user_id=doc.user_id,
description=doc.name,
meta={
2024-10-04 07:59:19 +00:00
"legacy": True,
2024-10-02 04:48:15 +00:00
"document": True,
2024-10-02 00:46:56 +00:00
"tags": json.loads(doc.content or "{}").get("tags", []),
2024-10-02 00:35:10 +00:00
},
name=doc.title,
created_at=doc.timestamp,
updated_at=doc.timestamp, # using created_at for both created_at and updated_at in project
)
)
def downgrade():
2024-10-02 05:45:04 +00:00
op.drop_table("knowledge")