Skip to content

Commit 21b8ca3

Browse files
authored
Merge pull request open-webui#6465 from open-webui/dev
refac: migration
2 parents f1f068f + 5537b2d commit 21b8ca3

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

backend/open_webui/migrations/versions/242a2047eae0_update_chat_table.py

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,41 @@
1919

2020

2121
def upgrade():
22-
# Step 1: Rename current 'chat' column to 'old_chat'
23-
op.alter_column("chat", "chat", new_column_name="old_chat", existing_type=sa.Text)
22+
conn = op.get_bind()
23+
inspector = sa.inspect(conn)
2424

25-
# Step 2: Add new 'chat' column of type JSON
26-
op.add_column("chat", sa.Column("chat", sa.JSON(), nullable=True))
25+
columns = inspector.get_columns("chat")
26+
column_dict = {col["name"]: col for col in columns}
27+
28+
chat_column = column_dict.get("chat")
29+
old_chat_exists = "old_chat" in column_dict
30+
31+
if chat_column:
32+
if isinstance(chat_column["type"], sa.Text):
33+
print("Converting 'chat' column to JSON")
34+
35+
if old_chat_exists:
36+
print("Dropping old 'old_chat' column")
37+
op.drop_column("chat", "old_chat")
38+
39+
# Step 1: Rename current 'chat' column to 'old_chat'
40+
print("Renaming 'chat' column to 'old_chat'")
41+
op.alter_column(
42+
"chat", "chat", new_column_name="old_chat", existing_type=sa.Text()
43+
)
44+
45+
# Step 2: Add new 'chat' column of type JSON
46+
print("Adding new 'chat' column of type JSON")
47+
op.add_column("chat", sa.Column("chat", sa.JSON(), nullable=True))
48+
else:
49+
# If the column is already JSON, no need to do anything
50+
pass
2751

2852
# Step 3: Migrate data from 'old_chat' to 'chat'
2953
chat_table = table(
3054
"chat",
31-
sa.Column("id", sa.String, primary_key=True),
32-
sa.Column("old_chat", sa.Text),
55+
sa.Column("id", sa.String(), primary_key=True),
56+
sa.Column("old_chat", sa.Text()),
3357
sa.Column("chat", sa.JSON()),
3458
)
3559

@@ -50,6 +74,7 @@ def upgrade():
5074
)
5175

5276
# Step 4: Drop 'old_chat' column
77+
print("Dropping 'old_chat' column")
5378
op.drop_column("chat", "old_chat")
5479

5580

@@ -60,7 +85,7 @@ def downgrade():
6085
# Step 2: Convert 'chat' JSON data back to text and store in 'old_chat'
6186
chat_table = table(
6287
"chat",
63-
sa.Column("id", sa.String, primary_key=True),
88+
sa.Column("id", sa.String(), primary_key=True),
6489
sa.Column("chat", sa.JSON()),
6590
sa.Column("old_chat", sa.Text()),
6691
)
@@ -79,4 +104,4 @@ def downgrade():
79104
op.drop_column("chat", "chat")
80105

81106
# Step 4: Rename 'old_chat' back to 'chat'
82-
op.alter_column("chat", "old_chat", new_column_name="chat", existing_type=sa.Text)
107+
op.alter_column("chat", "old_chat", new_column_name="chat", existing_type=sa.Text())

0 commit comments

Comments
 (0)