19
19
20
20
21
21
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 )
24
24
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
27
51
28
52
# Step 3: Migrate data from 'old_chat' to 'chat'
29
53
chat_table = table (
30
54
"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 () ),
33
57
sa .Column ("chat" , sa .JSON ()),
34
58
)
35
59
@@ -50,6 +74,7 @@ def upgrade():
50
74
)
51
75
52
76
# Step 4: Drop 'old_chat' column
77
+ print ("Dropping 'old_chat' column" )
53
78
op .drop_column ("chat" , "old_chat" )
54
79
55
80
@@ -60,7 +85,7 @@ def downgrade():
60
85
# Step 2: Convert 'chat' JSON data back to text and store in 'old_chat'
61
86
chat_table = table (
62
87
"chat" ,
63
- sa .Column ("id" , sa .String , primary_key = True ),
88
+ sa .Column ("id" , sa .String () , primary_key = True ),
64
89
sa .Column ("chat" , sa .JSON ()),
65
90
sa .Column ("old_chat" , sa .Text ()),
66
91
)
@@ -79,4 +104,4 @@ def downgrade():
79
104
op .drop_column ("chat" , "chat" )
80
105
81
106
# 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