SQLAlchemy Expression Language Problem

I am trying to convert this into a sqlalchemy expression compatible with the language, I do not know if this is possible out of the box and hope that someone more experienced can help me. The backend is PostgreSQL, and if I cannot do it as an expression, I will create a string instead of ::

SELECT
    DISTINCT date_trunc('month', x.x) as date,
    COALESCE(b.res1, 0) AS res1,
    COALESCE(b.res2, 0) AS res2
FROM 
    generate_series(
        date_trunc('year', now() - interval '1 years'), 
        date_trunc('year', now() + interval '1 years'),
        interval '1 months'
    ) AS x
LEFT OUTER JOIN(
    SELECT
        date_trunc('month', access_datetime) AS when,
        count(NULLIF(resource_id != 1, TRUE)) AS res1,
        count(NULLIF(resource_id != 2, TRUE)) AS res2
    FROM tracking_entries
    GROUP BY 
        date_trunc('month', access_datetime)
    ) AS b
ON (date_trunc('month', x.x) = b.when)

First of all, I got the TrackingEntry class mapped to tracking_entries, the select statement inside the external connection can be converted to something like (pseudo-code) ::

from sqlalchemy.sql import func, select
from datetime import datetime, timedelta

stmt = select([
    func.date_trunc('month', TrackingEntry.resource_id).label('when'),
    func.count(func.nullif(TrackingEntry.resource_id != 1, True)).label('res1'),
    func.count(func.nullif(TrackingEntry.resource_id != 2, True)).label('res2')
    ],
    group_by=[func.date_trunc('month', TrackingEntry.access_datetime), ])

Given the external selection operator, I have no idea how to build it, I think something like:

outer = select([
        func.distinct(func.date_trunc('month', ?)).label('date'),
        func.coalesce(?.res1, 0).label('res1'),
        func.coalesce(?.res2, 0).label('res2')
    ],
    from_obj=[
        func.generate_series(
                datetime.now(),
                datetime.now() + timedelta(days=365),
                timedelta(days=1)
            ).label(x)
    ])

Then I suggest that I need to bind these statements together without using foreign keys:

outer.outerjoin(stmt???).??(func.date_trunc('month', ?.?), ?.when)

Anyone have suggestions or even a better solution?

http://pastie.org/994367

+3
1

, select() , ".c". , , .

s1 = select(...)
s2 = select(...)

s3 = select([s1,s2]).select_from(s1.join(s2, s1.c.foo==s2.c.bar))

select ([func.foo(s1.c.x)]).select_from(s1.join(s2, ...))
+1

Source: https://habr.com/ru/post/1748776/


All Articles