Skip to content

Error migrating database from any lower Airflow version 2.x to 2.9.2 #43690

Closed

Description

@JayalakshmiH

Apache Airflow version

Other Airflow 2 version (please specify below)

If "Other Airflow 2 version" selected, which one?

2.9.2

What happened?

When upgrading the database from 2.8.2 or 2.9.2 via airflow db migrate, I get the following error message

INFO  [alembic.runtime.migration] Context impl MySQLImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade 1949afb29106 -> bff083ad727d, Remove idx_last_scheduling_decision index on last_scheduling_decision in dag_run table
INFO  [alembic.runtime.migration] Running upgrade bff083ad727d -> 686269002441, Fix inconsistency between ORM and migration files.
Traceback (most recent call last):
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1910, in _execute_context
    self.dialect.do_execute(
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py", line 736, in do_execute
    cursor.execute(statement, parameters)
  File "/opt/venv/lib/python3.12/site-packages/pymysql/cursors.py", line 153, in execute
    result = self._query(query)
             ^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/pymysql/cursors.py", line 322, in _query
    conn.query(q)
  File "/opt/venv/lib/python3.12/site-packages/pymysql/connections.py", line 563, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/pymysql/connections.py", line 825, in _read_query_result
    result.read()
  File "/opt/venv/lib/python3.12/site-packages/pymysql/connections.py", line 1199, in read
    first_packet = self.connection._read_packet()
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/pymysql/connections.py", line 775, in _read_packet
    packet.raise_for_error()
  File "/opt/venv/lib/python3.12/site-packages/pymysql/protocol.py", line 219, in raise_for_error
    err.raise_mysql_exception(self._data)
  File "/opt/venv/lib/python3.12/site-packages/pymysql/err.py", line 150, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'prepare stmt from @var;\n        execute stmt;\n        deallocate prepare stmt' at line 8")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/venv/bin/airflow", line 8, in <module>
    sys.exit(main())
             ^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/airflow/__main__.py", line 58, in main
    args.func(args)
  File "/opt/venv/lib/python3.12/site-packages/airflow/cli/cli_config.py", line 49, in command
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/airflow/utils/cli.py", line 114, in wrapper
    return f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/airflow/utils/providers_configuration_loader.py", line 55, in wrapped_function
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/airflow/cli/commands/db_command.py", line 130, in migratedb
    db.upgradedb(
  File "/opt/venv/lib/python3.12/site-packages/airflow/utils/session.py", line 79, in wrapper
    return func(*args, session=session, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/airflow/utils/db.py", line 1632, in upgradedb
    command.upgrade(config, revision=to_revision or "heads")
  File "/opt/venv/lib/python3.12/site-packages/alembic/command.py", line 406, in upgrade
    script.run_env()
  File "/opt/venv/lib/python3.12/site-packages/alembic/script/base.py", line 582, in run_env
    util.load_python_file(self.dir, "env.py")
  File "/opt/venv/lib/python3.12/site-packages/alembic/util/pyfiles.py", line 95, in load_python_file
    module = load_module_py(module_id, path)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/alembic/util/pyfiles.py", line 113, in load_module_py
    spec.loader.exec_module(module)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap_external>", line 995, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "/opt/venv/lib/python3.12/site-packages/airflow/migrations/env.py", line 120, in <module>
    run_migrations_online()
  File "/opt/venv/lib/python3.12/site-packages/airflow/migrations/env.py", line 114, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "/opt/venv/lib/python3.12/site-packages/alembic/runtime/environment.py", line 946, in run_migrations
    self.get_context().run_migrations(**kw)
  File "/opt/venv/lib/python3.12/site-packages/alembic/runtime/migration.py", line 628, in run_migrations
    step.migration_fn(**kw)
  File "/opt/venv/lib/python3.12/site-packages/airflow/migrations/versions/0142_2_9_2_fix_inconsistency_between_ORM_and_migration_files.py", line 46, in upgrade
    conn.execute(
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/future/engine.py", line 286, in execute
    return self._execute_20(
           ^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1710, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 334, in _execute_on_connection
    return connection._execute_clauseelement(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1577, in _execute_clauseelement
    ret = self._execute_context(
          ^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1953, in _execute_context
    self._handle_dbapi_exception(
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 2134, in _handle_dbapi_exception
    util.raise_(
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/util/compat.py", line 211, in raise_
    raise exception
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1910, in _execute_context
    self.dialect.do_execute(
  File "/opt/venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py", line 736, in do_execute
    cursor.execute(statement, parameters)
  File "/opt/venv/lib/python3.12/site-packages/pymysql/cursors.py", line 153, in execute
    result = self._query(query)
             ^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/pymysql/cursors.py", line 322, in _query
    conn.query(q)
  File "/opt/venv/lib/python3.12/site-packages/pymysql/connections.py", line 563, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/pymysql/connections.py", line 825, in _read_query_result
    result.read()
  File "/opt/venv/lib/python3.12/site-packages/pymysql/connections.py", line 1199, in read
    first_packet = self.connection._read_packet()
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/venv/lib/python3.12/site-packages/pymysql/connections.py", line 775, in _read_packet
    packet.raise_for_error()
  File "/opt/venv/lib/python3.12/site-packages/pymysql/protocol.py", line 219, in raise_for_error
    err.raise_mysql_exception(self._data)
  File "/opt/venv/lib/python3.12/site-packages/pymysql/err.py", line 150, in raise_mysql_exception
    raise errorclass(errno, errval)
sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'prepare stmt from @var;\n        execute stmt;\n        deallocate prepare stmt' at line 8")
[SQL: 
        set @var=if((SELECT true FROM information_schema.TABLE_CONSTRAINTS WHERE
            CONSTRAINT_SCHEMA = DATABASE() AND
            TABLE_NAME        = 'connection' AND
            CONSTRAINT_NAME   = 'unique_conn_id' AND
            CONSTRAINT_TYPE   = 'UNIQUE') = true,'ALTER TABLE connection
            DROP INDEX unique_conn_id','select 1');

        prepare stmt from @var;
        execute stmt;
        deallocate prepare stmt;
        ]
(Background on this error at: https://sqlalche.me/e/14/f405)

What you think should happen instead?

The db migration should successfully finish.

How to reproduce

Start with airflow 2.9.2, an empty mysql database. The initial new creation of new database objects works well.
Now run, for example

airflow db downgrade --to-version=2.8.2 --yes

Run
airflow db migrate

Operating System

Debian GNU/Linux 11 (bullseye)

Versions of Apache Airflow Providers

No response

Deployment

Other Docker-based deployment

Deployment details

Mysql version (docker) mysql:8.0.28. Issue occurs in other versions of mysql as well i.e 8.0.32, 8.0.36

Anything else?

Though this issue is marked as closed #40928, it is still occuring as reported by multiple users.

Are you willing to submit PR?

  • Yes I am willing to submit a PR!

Code of Conduct

Activity

  1. added
    kind:bug
    needs-triage
    on Nov 5, 2024
  2. boring-cyborg commented on Nov 5, 2024

    @boring-cyborg

    Thanks for opening your first issue here! Be sure to follow the issue template! If you are willing to raise PR to address this issue please do so, no need to wait for approval.

  3. added
    area:db-migrations
    on Nov 5, 2024
  4. xia-stan commented on Nov 5, 2024

    @xia-stan

    Can confirm that this error happens on Airflow 2.10.3 with MySQL 8.0.28. Confirmed too that a fresh DB poses no issues.

  5. OlafenwaMoses commented on Nov 6, 2024

    @OlafenwaMoses

    cross posting from the closed issue #40928

    I am getting same issue to. I am using MySQL 8.0.32 and any attempt to upgrade beyond 2.9.1 on an existing database leads to the error in the trace below. I have tried

    • Airflow 2.9.1 to 2.9.2 with MySQL 8.0.32
    • Airflow 2.9.1 to 2.9.3 MySQL 8.0.32
    • Airflow 2.9.1 to 2.9.3 with MySQL 8.0.36

    and apparently all failed with same error despite the fix in #40314 .

    As @JayalakshmiH mentioned, Airflow 2.9.2 and higher only works when you setup with an empty db.

    2024-11-04 22:14:41 sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'prepare stmt from @var;\n        execute stmt;\n        deallocate prepare stmt' at line 7")
    2024-11-04 22:14:41 [SQL: 
    2024-11-04 22:14:41         set @var=if((SELECT true FROM information_schema.TABLE_CONSTRAINTS WHERE
    2024-11-04 22:14:41             CONSTRAINT_SCHEMA = DATABASE() AND
    2024-11-04 22:14:41             TABLE_NAME        = 'connection' AND
    2024-11-04 22:14:41             CONSTRAINT_NAME   = 'unique_conn_id' AND
    2024-11-04 22:14:41             CONSTRAINT_TYPE   = 'UNIQUE') = true,'ALTER TABLE connection
    2024-11-04 22:14:41             DROP INDEX unique_conn_id','select 1');
    2024-11-04 22:14:41 
    2024-11-04 22:14:41         prepare stmt from @var;
    2024-11-04 22:14:41         execute stmt;
    2024-11-04 22:14:41         deallocate prepare stmt;
    2024-11-04 22:14:41         ]
    2024-11-04 22:14:41 (Background on this error at: https://sqlalche.me/e/14/f405)
    2024-11-04 22:14:41 WARNING: Environment variable '_AIRFLOW_DB_UPGRADE' is deprecated please use '_AIRFLOW_DB_MIGRATE' instead
    
  6. kaxil commented on Nov 6, 2024

    @kaxil
    Member

    I am not able to reproduce this:

    MySQL: 8.0.40

    irflow> SELECT VERSION()
    [2024-11-06 14:45:01] 1 row retrieved starting from 1 in 34 ms (execution: 13 ms, fetching: 21 ms)
    airflow> set @var=if((SELECT true FROM information_schema.TABLE_CONSTRAINTS WHERE
                 CONSTRAINT_SCHEMA = DATABASE() AND
                 TABLE_NAME        = 'connection' AND
                 CONSTRAINT_NAME   = 'unique_conn_id' AND
                 CONSTRAINT_TYPE   = 'UNIQUE') = true,'ALTER TABLE connection
                 DROP INDEX unique_conn_id','select 1')
    [2024-11-06 14:45:06] completed in 3 ms
    airflow> prepare stmt from @var
    [2024-11-06 14:45:06] completed in 2 ms
    airflow> execute stmt
    [2024-11-06 14:45:06] 1 row retrieved starting from 1 in 18 ms (execution: 4 ms, fetching: 14 ms)
  7. kaxil commented on Nov 6, 2024

    @kaxil
    Member

    @JayalakshmiH By any chance are you using a different flavour of MySQL like MariaDB?

  8. xia-stan commented on Nov 6, 2024

    @xia-stan

    @kaxil : I'm using a cloud host. I double checked my MySQL version with the command you posted. It returns 8.0.28-0ubuntu0.20.04.3. From the package repo, it seems like this is definitely MySQL and not MariaDB. I didn't bother posting my error message as it was identical to @OlafenwaMoses's.

  9. kaxil commented on Nov 6, 2024

    @kaxil
    Member

    hmm curious, maybe it was a bug in MySQL in that version

  10. kaxil commented on Nov 6, 2024

    @kaxil
    Member

    aah yes I see a related item in their changelog for MySQL 8.0.40 (link here)

    It may not be exactly be the same though

  11. kaxil commented on Nov 6, 2024

    @kaxil
    Member

    Could someone on this thread who were experiencing issue help and try to reproduce it with 8.0.40, please?

    That way we can narrow it down

  12. prabhusneha commented on Nov 7, 2024

    @prabhusneha
    Contributor

    I couldn't reproduce the issue either. Attaching some screenshots and descriptions on how I tried to reproduce it.

    image

    1. As seen in the above image, started with airflow version 2.9.2. MySQL backend version 8.0.40.
    2. Ran a sample DAG multiple times to populate some metadata.
    3. Executed airflow db downgrade --to-version=2.8.2 --yes
      Revision id applied is 88344c1d9134 and downgrade completed successfully.
    4. Upgraded successfully using airflow db migrate

    After the upgrade and downgrade, I checked a few things in the database (see image below):
    The unique key on the connection table is named connection_conn_id_uq. When I ran the query that caused the error mentioned in this issue, it executed without any errors.The query output is also shown in the image.

    image
  13. hatched-DavidMichon commented on Dec 12, 2024

    @hatched-DavidMichon

    I was able to reproduce this issue and narrow it down. I am using aurora mysql 8.0.39. While testing directly on the database with a unix mysql client I can run the prepare statement query without any issue.

    But when I am doing the same via python, using PyMySQL, it errors out. Per this open issue PyMySQL/PyMySQL#202, prepared statement are not supported on PyMySQL. Does anyone else has this migration issue using PyMySQL?

  14. 3 remaining items

  15. kaxil commented on Dec 12, 2024

    @kaxil
    Member

    Ah that makes sense -- mystery solved! We recommend mysqlclient because of those sort of issues

    We recommend using the mysqlclient driver and specifying it in your SqlAlchemy connection string.

    https://airflow.apache.org/docs/apache-airflow/stable/howto/set-up-database.html#setting-up-a-mysql-database

  16. kaxil commented on Dec 12, 2024

    @kaxil
    Member

    That said, we should solve this, does anyone fancy a PR to not use prepare statement when using PyMySQL?

  17. hatched-DavidMichon commented on Dec 12, 2024

    @hatched-DavidMichon

    Ah that makes sense -- mystery solved! We recommend mysqlclient because of those sort of issues

    We recommend using the mysqlclient driver and specifying it in your SqlAlchemy connection string.

    https://airflow.apache.org/docs/apache-airflow/stable/howto/set-up-database.html#setting-up-a-mysql-database

    @kaxil right, this is precisely what I am at right now to solve it.

  18. added
    _eol_affected_version:2.9
    and removed
    needs-triage
    on Jul 12, 2025
  19. xchwan commented on Sep 12, 2025

    @xchwan
    Contributor

    That said, we should solve this, does anyone fancy a PR to not use prepare statement when using PyMySQL?

    I have PR to remove prepare statement. Since nobody take it, I modify it.

  20. added a commit that references this issue on Aug 9, 2026
    8ed9406
  21. added 2 commits that reference this issue on Sep 7, 2026
    08e428c
    8acabc3
  22. added a commit that references this issue on Sep 27, 2026
    d1c50c5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    _eol_affected_version:2.9area:corearea:db-migrationsgood first issuekind:bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions