def _aggregate(query, func, by=None):
  """
  Wrap a query in an aggregation clause.

  Use this convenience function if the aggregation parameters are coming from
  user input so that they can be validated.

  Args:
    query (str): Query string to wrap.
    func (str): Aggregation function of choice. Valid choices are 'avg'/'mean',
      'min', 'max', 'sum'.
    by (list of str): Optional list of variables by which to perform the
      aggregation.

  Returns:
    str: New query string.
  """
  if func == "mean":
    func = "avg"
  if func not in ["avg", "min", "max", "sum"]:
    raise ValueError("Unsupported aggregation function %r" % func)
  query = "{func}({query})".format(func=func, query=query)
  if by:
    query += " by({by_variables})".format(by_variables=", ".join(by))
  return query