以下の内容はhttps://yuutookun.hatenablog.com/entry/2024/06/12/152809より取得しました。


sqlalchemyで sqlがprintできない

表題の通り

sqlalchemyでsqlがちゃんと想定のSQLが吐き出されているか確認したかったが、以下のようなコンパイルエラーが発生してしまった。

sqlalchemy.exc.UnsupportedCompilationError: Compiler <sqlalchemy.sql.compiler.StrSQLCompiler object at 0x107a3cb90> can't render element of type <class 'models.utils.utcnow'>: <class 'models.utils.utcnow'> construct has no default compilation handler. (Background on this error at: https://sqlalche.me/e/20/l7de)

utcnowは以下のように設定していました。

class utcnow(expression.FunctionElement):
    type = DateTime()
    inherit_cache = True


@compiles(utcnow, "postgresql")
def pg_utcnow(element, compiler, **kw) -> str:
    return "TIMEZONE('utc', CURRENT_TIMESTAMP)"

実際のprintしている部分のコードはこれ

from sqlalchemy import select, update


## session は async_sessionmaker経由で作成

stmt = update(User).where(id = 1).values(name="name")
print(stmt)
await session.execute(stmt)
await session.commit()

この場合、compilesのアノテーションがついているので以下のようにcompileを使ったprintをさせる必要がありました。

from sqlalchemy.dialects import postgresql

print(stmt.compile(dialect=postgresql.dialect()))

参考リンク

Custom SQL Constructs and Compilation Extension — SQLAlchemy 2.0 Documentation

SQL Expressions — SQLAlchemy 2.0 Documentation




以上の内容はhttps://yuutookun.hatenablog.com/entry/2024/06/12/152809より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14