kaxil commented on code in PR #55975:
URL: https://github.com/apache/airflow/pull/55975#discussion_r2370869137


##########
airflow-core/src/airflow/migrations/versions/0085_3_1_0_downgrade_serialized_dag_version_to_v2.py:
##########
@@ -0,0 +1,176 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Add backward compatibility for serialized DAG format v3 to v2.
+
+Revision ID: cc92b33c6709
+Revises: eaf332f43c7c
+Create Date: 2025-09-22 22:50:48.035121
+
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "cc92b33c6709"
+down_revision = "eaf332f43c7c"
+branch_labels = None
+depends_on = None
+airflow_version = "3.1.0"
+
+
+def upgrade():
+    """Apply Downgrade Serialized Dag version to v2."""
+    # No-op: Server handles v1/v2/v3 DAGs at runtime via conversion functions
+    pass
+
+
+def downgrade():
+    """Convert v3 serialized DAGs back to v2 format for compatibility with 
older Airflow versions."""
+    import gzip
+    import json
+
+    connection = op.get_bind()
+    dialect = connection.dialect.name
+
+    if dialect == "postgresql":
+        connection.execute(
+            sa.text("""
+                UPDATE serialized_dag
+                SET data = jsonb_set(
+                    CASE
+                        WHEN data ? 'client_defaults' THEN data - 
'client_defaults'
+                        ELSE data
+                    END,
+                    '{__version}',
+                    '2'::jsonb
+                )
+                WHERE data->>'__version' = '3'
+                AND data_compressed IS NULL
+            """)
+        )
+    elif dialect == "mysql":
+        connection.execute(
+            sa.text("""
+                UPDATE serialized_dag
+                SET data = JSON_SET(
+                    JSON_REMOVE(data, '$.client_defaults'),
+                    '$.__version',
+                    2
+                )
+                WHERE JSON_EXTRACT(data, '$.__version') = '3'
+                AND data_compressed IS NULL
+            """)
+        )
+    else:
+        json_functions_available = False
+        try:
+            connection.execute(sa.text("SELECT JSON_SET('{}', '$.test', 
'value')")).fetchone()
+            json_functions_available = True
+            print("SQLite JSON functions detected, using optimized SQL 
approach")
+        except Exception:
+            print("SQLite JSON functions not available, using Python fallback 
for JSON processing")
+
+        if json_functions_available:
+            connection.execute(
+                sa.text("""
+                    UPDATE serialized_dag
+                    SET data = JSON_SET(
+                        JSON_REMOVE(data, '$.client_defaults'),
+                        '$.__version',
+                        2
+                    )
+                    WHERE JSON_EXTRACT(data, '$.__version') = '3'
+                    AND data_compressed IS NULL
+                """)
+            )
+        else:
+            result = connection.execute(
+                sa.text("""
+                    SELECT id, data
+                    FROM serialized_dag
+                    WHERE data_compressed IS NULL
+                """)
+            )
+
+            for row in result:
+                dag_id, data_json = row
+                try:
+                    if data_json is None:
+                        continue
+
+                    dag_data = json.loads(data_json)
+
+                    if dag_data.get("__version") != 3:
+                        continue
+
+                    if "client_defaults" in dag_data:
+                        del dag_data["client_defaults"]
+                    dag_data["__version"] = 2
+
+                    new_json = json.dumps(dag_data)
+                    connection.execute(
+                        sa.text("UPDATE serialized_dag SET data = :data WHERE 
id = :id"),
+                        {"data": new_json, "id": dag_id},
+                    )
+
+                except Exception as e:
+                    print(f"Failed to downgrade uncompressed DAG {dag_id}: 
{e}")
+                    continue
+    try:
+        result = connection.execute(

Review Comment:
   Handled  now



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to