SQL使用 AsyncEngine 执行任何 SQL 查询时,Alchemy v1.4 ObjectNotExecutableError

SQLAlchemy v1.4 ObjectNotExecutableError when executing any SQL query using AsyncEngine

我正在使用 async_engine。当我尝试执行任何操作时:

async with self.async_engine.connect() as con:
    query = "SELECT id, name FROM item LIMIT 50;"
    result = await con.execute(f"{query}")

我得到:

Exception has occurred: ObjectNotExecutableError
Not an executable object: 'SELECT id, name FROM item LIMIT 50;'

用户 @stilmaniac but it is now deleted from SO 之前曾问过这个问题。

我在 Google 搜索缓存中找到它,here is copy

我也有同样的问题,所以我重新提问,但原始版本如下:


我正在尝试从元数据创建表,如下所示:

Base = declarative_base()

properties = Table(
    'properties', Base.metadata,
    # ...
    Column('geolocation', Geography(geometry_type='POINT', srid=4326)),
    # ... 
)

engine = create_async_engine("postgresql+asyncpg://user:password@postgres/")
async with engine.begin() as conn:
    await conn.run_sync(Base.metadata.create_all)

给我以下错误:

sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: 'CREATE INDEX "idx_properties_geolocation" ON "properties" USING GIST ("geolocation")'

考虑到这个 doc

版本:

如异常消息所示,str 'SELECT id, name FROM item LIMIT 50;' 不是可执行对象。要使其可执行,请用 sqlalchemy.text.

包装它
from sqlalchemy import text

async with self.async_engine.connect() as con:
    query = "SELECT id, name FROM item LIMIT 50;"
    result = await con.execute(text(query))

async.connection.execute 要求其语句参数

[...] is always an object that is in both the ClauseElement and Executable hierarchies, including:

  • Select

  • Insert, Update, Delete

  • TextClause and TextualSelect

  • DDL and objects which inherit from DDLElement

同步 connection.execute 方法允许原始字符串,但这在 SQLAlchemy 2.0 中已弃用并标记为删除。