# Fix "Textual SQL expression should be explicitly declared as text()" in SQLAlchemy 2

Yes. An agent finds every raw SQL string passed to execute(), wraps each in text(), and proves the app still starts and its tests pass on SQLAlchemy 2.

[Run this on Rush](https://cloud.getrush.ai/run/fix-textual-sql-expression-argument-error/sqlalchemy/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

SQLAlchemy 2.0 stopped accepting a plain string where a statement is expected. `session.execute('SELECT 1')` now raises `sqlalchemy.exc.ArgumentError: Textual SQL expression 'SELECT 1' should be explicitly declared as text('SELECT 1')`, and the same string handed to `connection.execute()` raises `ObjectNotExecutableError: Not an executable object: 'SELECT 1'`. The most common place for such a string is a database health check, and that makes the failure look worse than it is: the one query that decides whether the app is allowed to start is the one that breaks.

CT83/The-Overly-Complicated-Random-Number-Generator, a Flask API with a Redis queue and Postgres, has that check. In `api/shared/utils.py`, `db_connection_successful` calls `db.session.execute('SELECT 1')` inside a `try` that catches `SQLAlchemyError`, logs the message and returns `False`. `create_app` in `api/app/__init__.py` then runs `assert db_connection_successful(db)`. `ArgumentError` is a subclass of `SQLAlchemyError`, so on SQLAlchemy 2 the exception is caught, and what the developer sees is a bare `AssertionError` from the app factory, in every test and at every start. The message in the title appears only as one log line above it. The agent reads the log, not just the traceback, and connects the two.

The repository pins `SQLAlchemy==1.3.16` in `api/requirements/base.txt`, next to `Flask-SQLAlchemy==2.4.1` and `Flask==1.1.2`, so the error shows up when an upgrade is attempted, and the agent checks what that upgrade really involves. Raising SQLAlchemy alone does not reach the health check: Flask-SQLAlchemy 2.4.1 fails at `SQLAlchemy()` with `module 'sqlalchemy' has no attribute '__all__'`. The pins have to move together, to a Flask-SQLAlchemy 3 release and the Flask it requires. The agent says so and proposes the order: first wrap the string, which is valid on 1.3 as well and can merge today, then raise the pins in a second commit.

The fix is `from sqlalchemy import text` and `db.session.execute(text('SELECT 1'))`. The agent searches the `api` directory, which the worker image also copies and runs, for every `execute(` call and checks each argument, since a string built with `%` or an f-string needs bound parameters, not just a wrapper. It runs `python3 -m pytest` in `api`, the command the `api/Dockerfile` runs during the image build, with the dummy environment variables `conftest.py` sets and the SQLite file the testing config points at. On SQLAlchemy 1.4 it also sets `SQLALCHEMY_WARN_20=1`, which makes the library print a `RemovedIn20Warning` for each remaining pattern that 2.0 rejects.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "After raising SQLAlchemy to 2.x this app fails with \"Textual SQL expression 'SELECT 1' should be explicitly declared as text('SELECT 1')\", or with an AssertionError or ObjectNotExecutableError at startup. Read the requirements files and report the pinned versions of SQLAlchemy, Flask-SQLAlchemy, Flask and Alembic, and which of them must move together for SQLAlchemy 2 to install and import. Search the whole repository for calls to execute() on a session, connection or engine, and for each one say whether the argument is a plain string, a string built by formatting, or already a text() or Core construct. Wrap plain strings in sqlalchemy.text(). Where a string is built with %, .format or an f-string, rewrite it to use bound parameters and pass the values separately. Check any code that catches SQLAlchemyError around such a call and then asserts or returns False, because that hides this error behind another one; make the real message visible. Make the text() changes in a first commit that still passes on the currently pinned versions. In a second commit raise the pins to a compatible set, fix whatever else breaks (engine.execute, removed attributes, extension APIs) and list each fix. Run the test suite before and after each commit and include the output. If the tests need a database, use the SQLite configuration the tests already define; do not connect to any real database. Open a pull request with both commits and say which one is safe to merge alone.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request with two commits. The first is small: an import of `text` and a wrapped string at each call site, with the test output on the existing pins to show nothing changed. The second raises the SQLAlchemy, Flask-SQLAlchemy and Flask pins together and carries the other changes that version jump needs. The description has a table of every `execute` call the agent found, with its file, line, what the argument was and what it is now.

A reviewer can merge the first commit alone, since `text()` has been the documented form for years and works on old and new versions alike. For the second, look at how the health check reports failure. If it still swallows the exception and returns `False`, the next incompatible query will again surface as an assertion with no message. Where a query was rewritten to use bound parameters, check that the parameter names match the placeholders. If part of the suite needs services the sandbox does not have, such as Redis for the queue, the agent names the tests it could not run.

## Run it on every pull request labelled sqlalchemy-2

Dependency bots open the version bump, but nobody finishes it: the checks go red and the pull request waits. Add an automation to the Project with a `github` trigger on `pull_request.labeled` and the label you choose, and a prompt that checks out the labelled pull request, runs the tests, fixes the incompatibilities it finds and pushes to that branch. A member adds the label when they want the upgrade finished. The trigger fires only for a pull request that an owner, member or collaborator opened, so the bot's own pull request never fires it, whoever adds the label: open your own pull request from the bot's branch and label that one.

For several services on the same old pins, send the request above once per repository from a script, each with its own `request_id`, a fresh UUID, so a retried call returns the run it already started. Give the key a `webhook_url` and each run posts `run.completed` when it finishes, with the session URL to read the pull request from.

## Why run it on Rush?

An upgrade like this needs two environments at once, the pinned one and the target, and a test run in each. On a laptop that means juggling virtual environments and remembering which terminal is which. The agent builds both in its sandbox, runs the suite in each and keeps the output, so the pull request can state that the first commit passes on the old versions and the second on the new. Those are claims a reviewer would otherwise have to take on trust or redo.

The search is also wider than one error message. The string that raised the exception is only the first one the app reached, and others sit in code paths that run rarely: a migration helper, an admin script, a worker task. The agent reads every `execute` call instead of waiting for each to fail in production, and the transcript shows the search commands and what they returned.

## Frequently asked questions

### Why do I get an AssertionError or a failed health check, and not this message?

Because the call is wrapped in `except SQLAlchemyError`. `ArgumentError` inherits from it, so the handler catches the new error the same way it would catch a dead database, and the code after it reports a generic failure. Look for the message in the log line the handler writes.

### Does text() work on SQLAlchemy 1.3 and 1.4?

Yes. `text()` exists in all of them, so the wrapped call can ship before the upgrade. That is why the agent puts it in its own commit.

### What about engine.execute()?

That is a separate removal. In 2.0 an `Engine` has no `execute` method at all, so those calls need a connection: `with engine.connect() as conn: conn.execute(text(...))`. The agent converts them in the second commit and lists each one.

### Can I see every affected line before upgrading?

On SQLAlchemy 1.4, yes. Set the environment variable `SQLALCHEMY_WARN_20=1` and run the tests with warnings shown. Each pattern that 2.0 rejects prints a `RemovedIn20Warning` with the file and line. A project on 1.3 has to step to 1.4 first to get those warnings.

## More SQLAlchemy jobs

- [Migrate a SQLAlchemy App From MySQL to PostgreSQL](https://getrush.ai/run/migrate-mysql-to-postgres/sqlalchemy/)
- [Review Pull Requests in a SQLAlchemy App](https://getrush.ai/run/review-pull-requests/sqlalchemy/)
- [Upgrade a FastAPI App from SQLAlchemy 1.4 to 2.0](https://getrush.ai/run/upgrade-sqlalchemy/sqlalchemy/)

## More jobs like this: Upgrade dependencies weekly

- [Fix "TypeError: this.getOptions is not a function" From sass-loader on webpack 4](https://getrush.ai/run/fix-this-getoptions-is-not-a-function/sass-loader/)
- [Fix THREE.Geometry Is Not a Constructor After a three.js Upgrade](https://getrush.ai/run/fix-three-geometry-is-not-a-constructor/three/)
- [Fix TypeScript Errors After an Upgrade](https://getrush.ai/run/fix-type-errors/nestjs/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
