SQLAlchemy 不直接支持集合返回函数,但它FunctionElement
的 s 被认为是FromClause
s,这意味着你已经可以将它们视为表;我们只需要添加从函数中选择特定列的功能。幸运的是,这很简单(虽然不明显):
from sqlalchemy.sql.base import ColumnCollection
from sqlalchemy.sql.expression import column
from sqlalchemy.sql.functions import FunctionElement
NormAddy = CompositeType(
"norm_addy",
[
Column("address", Integer),
Column("predirAbbrev", String),
Column("streetName", String),
Column("streetTypeAbbrev", String),
Column("postdirAbbrev", String),
Column("internal", String),
Column("location", String),
Column("stateAbbrev", String),
Column("zip", String),
Column("parsed", Boolean),
],
)
class geocode(GenericFunction):
columns = ColumnCollection(
Column("rating", Integer),
column("geomout"), # lowercase column because we don't have the `geometry` type
Column("addy", NormAddy),
)
子类化 fromGenericFunction
具有全局注册函数的额外好处,geocode
以便func.geocode
按预期工作。
g = func.geocode(func.pagc_normalize_address("1 Capitol Square Columbus OH 43215")).alias("g")
query = session.query(
g.c.rating,
func.ST_X(g.c.geomout).label("lon"),
func.ST_Y(g.c.geomout).label("lat"),
g.c.addy.address.label("stno"),
g.c.addy.streetName.label("street"),
g.c.addy.streetTypeAbbrev.label("styp"),
g.c.addy.location.label("city"),
g.c.addy.stateAbbrev.label("st"),
g.c.addy.zip,
).select_from(g)
不幸的是,这并不完全奏效。似乎有一个错误使g.c.addy.address
语法在最新版本的 SQLAlchemy 上不起作用。我们可以快速修复它(尽管这应该在 sqlalchemy_utils 中修复):
from sqlalchemy_utils.types.pg_composite import CompositeElement
import sqlalchemy_utils
class CompositeType(sqlalchemy_utils.CompositeType):
class comparator_factory(_CompositeType.comparator_factory):
def __getattr__(self, key):
try:
type_ = self.type.typemap[key]
except KeyError:
raise AttributeError(key)
return CompositeElement(self.expr, key, type_)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.typemap = {c.name: c.type for c in self.columns}
现在它起作用了:
print(query.statement.compile(engine))
# SELECT g.rating, ST_X(g.geomout) AS lon, ST_Y(g.geomout) AS lat, (g.addy).address AS stno, (g.addy).streetName AS street, (g.addy).streetTypeAbbrev AS styp, (g.addy).location AS city, (g.addy).stateAbbrev AS st, (g.addy).zip AS zip_1
# FROM geocode(pagc_normalize_address(%(pagc_normalize_address_1)s)) AS g