Skip to content

Commit

Permalink
Add SUM Aggregation function and fix ignore comma after aggregation f…
Browse files Browse the repository at this point in the history
…unction
  • Loading branch information
AmrDeveloper committed Jul 7, 2023
1 parent 1123839 commit 442168a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions docs/function/aggregations.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ Accept field name with `NUMBER` to calculate the minimum value of it for all ele
SELECT name, commit_count, min(commit_count) FROM branches
```

### Aggregation `sum`
The function sum() is an aggregate function that returns the sum of items in a group

```sql
SELECT name, sum(insertions) FROM diffs GROUP BY name
```

### Aggregation `count`
The function COUNT() is an aggregate function that returns the number of items in a group

Expand Down
17 changes: 17 additions & 0 deletions src/aggregation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ lazy_static! {
let mut map: HashMap<&'static str, Aggregation> = HashMap::new();
map.insert("max", aggregation_max);
map.insert("min", aggregation_min);
map.insert("sum", aggregation_sum);
map.insert("count", aggregation_count);
map
};
Expand All @@ -38,6 +39,13 @@ lazy_static! {
result: DataType::Number,
},
);
map.insert(
"sum",
AggregationPrototype {
parameter: DataType::Any,
result: DataType::Number,
},
);
map.insert(
"count",
AggregationPrototype {
Expand Down Expand Up @@ -73,6 +81,15 @@ fn aggregation_min(field_name: &String, objects: &Vec<GQLObject>) -> String {
return max_length.to_string();
}

fn aggregation_sum(field_name: &String, objects: &Vec<GQLObject>) -> String {
let mut sum: i64 = 0;
for object in objects {
let field_value = &object.attributes.get(field_name).unwrap();
sum += field_value.parse::<i64>().unwrap();
}
return sum.to_string();
}

fn aggregation_count(_field_name: &String, objects: &Vec<GQLObject>) -> String {
return objects.len().to_string();
}
5 changes: 5 additions & 0 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,10 @@ fn parse_select_statement(
},
);

if tokens[*position].kind == TokenKind::Comma {
*position += 1;
}

continue;
}

Expand Down Expand Up @@ -381,6 +385,7 @@ fn parse_select_statement(
}

if tokens[*position].kind != TokenKind::From {
println!("{}", tokens[*position].literal);
return Err(GQLError {
message: "Expect `from` keyword after attributes".to_owned(),
location: tokens[*position].location,
Expand Down

0 comments on commit 442168a

Please sign in to comment.