Vapor: Feature: Add `sum` to Fluent to sum the values of a column

Created on 4 Feb 2017  路  3Comments  路  Source: vapor/vapor

Feature, Enhancement, or Optimization

Add sum to Fluent

  • Author(s): kgn

Introduction

I'd like to be able to access the database function sum, but we can do with count today.

Motivation

I've run into a use case where I want to return the total number of items, and their total cost. I can use count, but am having to run raw sql in order to retrieve the sum of their cost.

Proposed solution

I propose that sum be added, similar to how count is implemented, but sum would take the name of the column to sum.

Code snippets

Assume a ShoppingCart model with Item model children.

let numberOfItems = shoppingCart.items.count()
let totalCost = shoppingCart.items.sum("price")

Impact

This change would allow me to remove the raw sql code in my controllers, running raw sql also requires me to add the Droplet to the controllers just for this one part, so I could remove that requirement too.

Alternatives considered

This seems like the right solution as it matches a paradigm already laid out by count.

enhancement

Most helpful comment

I think this is a good idea, and shouldn't stop at SUM. The AVG, MIN and MAX aggregate functions are also universally supported and behave exactly the same.

All 3 comments

I think this is a good idea, and shouldn't stop at SUM. The AVG, MIN and MAX aggregate functions are also universally supported and behave exactly the same.

On a second thought, implementing either on Mongo will require tapping into the aggregation pipeline, but possible nevertheless.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nhatlee picture nhatlee  路  3Comments

jsl303 picture jsl303  路  4Comments

betzerra picture betzerra  路  3Comments

litan1106 picture litan1106  路  4Comments

wildfiremedia picture wildfiremedia  路  4Comments