mirror of
https://github.com/GSA/notifications-api.git
synced 2025-12-24 01:11:38 -05:00
Got the SqlAlchemy query to work
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (desc, text)
|
||||
import sqlalchemy
|
||||
from sqlalchemy import desc
|
||||
|
||||
from app import db
|
||||
from app.models import (Template, TemplateHistory)
|
||||
@@ -61,11 +62,21 @@ def dao_get_template_versions(service_id, template_id):
|
||||
def dao_get_templates_by_for_cache(cache):
|
||||
if not cache or len(cache) == 0:
|
||||
return []
|
||||
txt = "( " + " Union all ".join(
|
||||
"select '{}'::text as template_id, {} as count".format(x.decode(),
|
||||
y.decode()) for x, y in cache) + " ) as cache"
|
||||
txt = "Select t.id as template_id, t.template_type, t.name, cache.count from templates t, " + \
|
||||
txt + " where t.id::text = cache.template_id order by t.name"
|
||||
stmt = text(txt)
|
||||
|
||||
return db.session.execute(stmt).fetchall()
|
||||
# First create a subquery that is a union select of the cache values
|
||||
# Then join templates to the subquery
|
||||
cache_queries = [
|
||||
db.session.query(sqlalchemy.sql.expression.bindparam("template_id" + str(i),
|
||||
uuid.UUID(template_id.decode())).label('template_id'),
|
||||
sqlalchemy.sql.expression.bindparam("count" + str(i), int(count.decode())).label('count'))
|
||||
for i, (template_id, count) in enumerate(cache)]
|
||||
cache_subq = cache_queries[0].union(*cache_queries[1:]).subquery()
|
||||
query = db.session.query(Template.id.label('template_id'),
|
||||
Template.template_type,
|
||||
Template.name,
|
||||
cache_subq.c.count.label('count')
|
||||
).join(cache_subq,
|
||||
Template.id == cache_subq.c.template_id
|
||||
).order_by(Template.name)
|
||||
|
||||
return query.all()
|
||||
|
||||
Reference in New Issue
Block a user