# File lib/dm-aggregates/aggregate_functions.rb, line 150
    def aggregate(*args)
      query = args.last.kind_of?(Hash) ? args.pop : {}

      query[:fields] ||= []
      query[:fields]  |= args
      query[:fields].map! { |f| normalize_field(f) }
      query[:order]  ||= query[:fields].select { |p| p.kind_of?(Property) }

      raise ArgumentError, 'query[:fields] must not be empty' if query[:fields].empty?

      query = scoped_query(query)

      if query.fields.any? { |p| p.kind_of?(Property) }
        # explicitly specify the fields to circumvent a bug in Query#update
        query.repository.aggregate(query.update(:fields => query.fields, :unique => true))
      else
        query.repository.aggregate(query).first  # only return one row
      end
    end