在SQLAlchemy中加入set-returns函数(SRF)和访问列

时间:2015-11-23 06:40:39

标签: postgresql join sqlalchemy

假设我有一个activity表和一个subscription表。每个活动都有一个对其他对象的泛型引用数组,每个订阅对同一组中的某个其他对象都有一个通用引用。

CREATE TABLE activity (
    id serial primary key,
    ob_refs UUID[] not null
);

CREATE TABLE subscription (
    id UUID primary key,
    ob_ref UUID,
    subscribed boolean not null
);

我想加入set-returning函数unnest,这样我就可以找到"最深的"匹配订阅,如下所示:

SELECT id
FROM (
    SELECT DISTINCT ON (activity.id)
        activity.id,
        x.ob_ref, x.ob_depth,
        subscription.subscribed IS NULL OR subscription.subscribed = TRUE
            AS subscribed,
    FROM activity

    LEFT JOIN subscription
        ON activity.ob_refs @> array[subscription.ob_ref]

    LEFT JOIN unnest(activity.ob_refs)
        WITH ORDINALITY AS x(ob_ref, ob_depth)
        ON subscription.ob_ref = x.ob_ref

    ORDER BY x.ob_depth DESC
) sub
WHERE subscribed = TRUE;

但我无法弄清楚如何进行第二次加入并获得对列的访问权限。我尝试过创建FromClause like this

act_ref_t = (sa.select(
        [sa.column('unnest', UUID).label('ob_ref'),
         sa.column('ordinality', sa.Integer).label('ob_depth')],
        from_obj=sa.func.unnest(Activity.ob_refs))
    .suffix_with('WITH ORDINALITY')
    .alias('act_ref_t'))

...

query = (query
    .outerjoin(
        act_ref_t,
        Subscription.ob_ref == act_ref_t.c.ob_ref))
    .order_by(activity.id, act_ref_t.ob_depth)

但是这导致这个SQL带有另一个子查询:

LEFT OUTER JOIN (
        SELECT unnest AS ob_ref, ordinality AS ref_i
        FROM unnest(activity.ob_refs) WITH ORDINALITY
    ) AS act_ref_t
    ON subscription.ob_refs @> ARRAY[act_ref_t.ob_ref]

...由于缺少unsupported LATERAL关键字而导致失败:

  

表"活动"有一个条目,但无法从查询的这一部分引用它。

那么,如何在不使用子查询的情况下为此SRF创建JOIN子句?或者还有其他我想念的东西?

修改1 sa.text使用TextClause.columns代替sa.select让我更加接近:

act_ref_t = (sa.sql.text(
        "unnest(activity.ob_refs) WITH ORDINALITY")
    .columns(sa.column('unnest', UUID),
             sa.column('ordinality', sa.Integer))
    .alias('act_ref'))

但是生成的SQL失败了,因为它将子句包装在括号中:

LEFT OUTER JOIN (unnest(activity.ob_refs) WITH ORDINALITY)
    AS act_ref ON subscription.ob_ref = act_ref.unnest

错误为syntax error at or near ")"。我可以将TextAsFrom括在括号中吗?

1 个答案:

答案 0 :(得分:2)

事实证明,SA不直接支持这一点,但使用ColumnClauseFunctionElement可以实现正确的行为。首先导入this recipe中的zzzeek所述的this SA issue。然后创建一个包含unnest修饰符的特殊WITH ORDINALITY函数:

class unnest_func(ColumnFunction):
    name = 'unnest'
    column_names = ['unnest', 'ordinality']

@compiles(unnest_func)
def _compile_unnest_func(element, compiler, **kw):
    return compiler.visit_function(element, **kw) + " WITH ORDINALITY"

然后您可以在连接,排序等中使用它,如下所示:

act_ref = unnest_func(Activity.ob_refs)
query = (query
    .add_columns(act_ref.c.unnest, act_ref.c.ordinality)
    .outerjoin(act_ref, sa.true())
    .outerjoin(Subscription, Subscription.ob_ref == act_ref.c.unnest)
    .order_by(act_ref.c.ordinality.desc()))