def build_query()

in aws/lambda/rds-proxy/lambda_function.py [0:0]


def build_query(body):
    # If the request is a simple query we can just build it manually rather
    # than having to hard code it in the list above
    params = []
    table_name = validate_schema_name(body["table_name"])

    query = f"SELECT {safe_join(body['fields'])} FROM {safe_join(table_name)}"

    where = body.get("where", None)
    if where is not None:
        if not isinstance(where, list):
            where = [where]
        for item in where:
            item["field"] = validate_schema_name(item["field"])
        query += " WHERE"
        items = [f"{n['field']} {'like' if n['like'] else '='} %s" for n in where]
        query += f" {' and '.join(items)}"
        params += [n["value"] for n in where]

    group_by = body.get("group_by", None)
    if group_by is not None:
        query += f" GROUP BY {safe_join(group_by)}"

    order_by = body.get("order_by", None)
    if order_by is not None:
        query += f" ORDER BY {safe_join(order_by)}"

    limit = body.get("limit", None)
    if limit is not None:
        query += f" LIMIT %s"
        params.append(int(limit))

    return query, params