from sqlalchemy import func, select, column


def _subquery(label, subquery, func_name):
    subquery = subquery.alias('item')
    _func = getattr(func, func_name)
    return (
        select([_func(column('item'))])
        .select_from(subquery)
        .as_scalar()
        .label(label)
    )


def json_column(label, subquery):
    return _subquery(label, subquery, 'to_json')


def json_agg_column(label, subquery):
    return _subquery(label, subquery, 'json_agg')
