def query_to_json(query, name):
    """This query is useful to fetch a complex join
    with some aggregations as a single blob, and later,
    just hydrate it without having to iterate over the resultset

    .. Example:
        SELECT
            u.id::varchar,
            to_jsonb(array_agg(scopes)) as scopes,
        FROM auth.auth_user u
            LEFT join LATERAL (
                SELECT id, scope
                FROM auth.auth_user_scope
                WHERE user_id=u.id
            ) scopes on true
        WHERE user_id = ANY($1)
        GROUP BY u.user_id;

    This query will fetch a list of users, and aggregate it's
    scopes as an array of dicts
    """

    return f"""
        select
            array_to_json(array_agg(row_to_json(t))) as {name}
        from (
            {query}
        ) as t
    """