SQLAlchemyのdistinct

2022年2月4日

目的

SQLAlchemyのdistinctがうまく動かなかったので 備忘録として記録しておく。

事象

動かそうとしたコードは下記

engine = create_engine("mysql://user:password@localhost:3306/race")
SessionClass = sessionmaker(engine)  
session = SessionClass()
races = session.query(RaceInfo).\
        distinct(RaceInfo.race_id).\
        all()

動かすと下記のようなWarningが出た。

SADeprecationWarning: DISTINCT ON is currently supported only by the PostgreSQL dialect.  Use of DISTINCT ON for other backends is currently silently ignored, however this usage is deprecated, and will raise CompileError in a future release for all backends that do not support this syntax.

現在はDISTINCT ONはPostgreSQLしかサポートされていないらしい。将来的には非推奨になるようだ。
自分はMySQLを使っていたので、distict部分のコードが無視されていた。

公式にもversion 2.0で非推奨になると書いてあった。
https://docs.sqlalchemy.org/en/14/orm/query.html?highlight=distinct#sqlalchemy.orm.Query.distinct

解決策

こちらのカラムにdistinctをかける方だとうまく動いた。
https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.distinct

from sqlalchemy import distinct
races = session.query(distinct(RaceInfo.race_id)).\
        all()
print(len(races))