Repository: mathesar-foundation/mathesar

Issue:
Support for `Peak month` aggregation function while summarizing columns
## Problem
We need to create an aggregate function for `Month` which imitates `average`, the only difference will be it will take modular mathematics into consieration.

## Proposed solution
It would be nice to support such an aggregate as a transformation step while summarizing Date and DateTime columns.

## To Discuss
- `Peak month` aggregation function should only be available for columns with **Date** and **DateTime** data type.

## Additional context
This feature request is a part of GSoC '23 project, [Add More Summarization Functions](https://summerofcode.withgoogle.com/programs/2023/projects/D9XvkQCN).



Discussion:

Resolving patch:
diff --git a/db/functions/base.py b/db/functions/base.py
--- a/db/functions/base.py
+++ b/db/functions/base.py
@@ -16,7 +16,7 @@
 import warnings
 
 from sqlalchemy import column, not_, and_, or_, func, literal, cast, distinct, INTEGER, TIME
-from sqlalchemy.dialects.postgresql import array_agg, TEXT, array
+from sqlalchemy.dialects.postgresql import array_agg, TEXT, array, DATE
 from sqlalchemy.sql import quoted_name
 from sqlalchemy.sql.functions import GenericFunction, concat, percentile_disc, mode, max, min
 
@@ -420,6 +420,19 @@ def to_sa_expression(column_expr):
         return sa_call_sql_function('msar.peak_time', column_expr, return_type=PostgresType.TIME_WITHOUT_TIME_ZONE)
 
 
+class PeakMonth(DBFunction):
+    id = 'peak_month'
+    name = 'peak_month'
+    hints = tuple([
+        hints.aggregation
+    ])
+
+    @staticmethod
+    def to_sa_expression(column_expr):
+        column_expr = cast(column_expr, DATE)
+        return sa_call_sql_function('msar.peak_month', column_expr, return_type=PostgresType.TEXT)
+
+
 class Min(DBFunction):
     id = 'min'
     name = 'min'
diff --git a/mathesar/models/query.py b/mathesar/models/query.py
--- a/mathesar/models/query.py
+++ b/mathesar/models/query.py
@@ -6,7 +6,7 @@
 from db.transforms.operations.deserialize import deserialize_transformation
 from db.transforms.operations.serialize import serialize_transformation
 from db.transforms.base import Summarize
-from db.functions.base import Count, ArrayAgg, Sum, Median, Mode, Percentage_True, Max, Min, Mean, PeakTime
+from db.functions.base import Count, ArrayAgg, Sum, Median, Mode, Percentage_True, Max, Min, Mean, PeakTime, PeakMonth
 from db.functions.packed import DistinctArrayAgg
 
 from mathesar.api.exceptions.query_exceptions.exceptions import DeletedColumnAccess
@@ -426,7 +426,8 @@ def _get_default_display_name_for_agg_output_alias(
             Percentage_True.id: " percentage true",
             Min.id: " min",
             Mean.id: " mean",
-            PeakTime.id: " peak_time"
+            PeakTime.id: " peak_time",
+            PeakMonth.id: " peak_month",
         }
         suffix_to_add = map_of_agg_function_to_suffix.get(agg_function)
         if suffix_to_add:


Test patch:
diff --git a/mathesar/tests/api/query/test_aggregation_functions.py b/mathesar/tests/api/query/test_aggregation_functions.py
--- a/mathesar/tests/api/query/test_aggregation_functions.py
+++ b/mathesar/tests/api/query/test_aggregation_functions.py
@@ -716,6 +716,179 @@ def test_min_aggregation(library_ma_tables, get_uid, client):
     assert sorted(actual_records, key=lambda x: x['Checkout Month']) == expect_records
 
 
+def test_peak_month_aggregation(library_ma_tables, get_uid, client):
+    _ = library_ma_tables
+    checkouts = {
+        t["name"]: t for t in client.get("/api/db/v0/tables/").json()["results"]
+    }["Checkouts"]
+    columns = {
+        c["name"]: c for c in checkouts["columns"]
+    }
+    request_data = {
+        "name": get_uid(),
+        "base_table": checkouts["id"],
+        "initial_columns": [
+            {"id": columns["Checkout Time"]["id"], "alias": "Checkout Time"},
+            {"id": columns["Patron"]["id"], "alias": "Patron"},
+        ],
+        "display_names": {
+            "Checkout Time": "Checkout Time",
+            "Patron": "Patron",
+        },
+        "display_options": {
+            "Checkout Time": {
+                display_option_origin: "Checkout Time",
+            },
+            "Patron": {
+                display_option_origin: "Patron",
+            },
+        },
+        "transformations": [
+            {
+                "spec": {
+                    "grouping_expressions": [
+                        {
+                            "input_alias": "Patron",
+                            "output_alias": "Patron",
+                        }
+                    ],
+                    "aggregation_expressions": [
+                        {
+                            "input_alias": "Checkout Time",
+                            "output_alias": "Checkout Time",
+                            "function": "peak_month",
+                        }
+                    ]
+                },
+                "type": "summarize",
+            }
+        ]
+    }
+    response = client.post('/api/db/v0/queries/', data=request_data)
+    assert response.status_code == 201
+    query_id = response.json()['id']
+    expect_records = [
+        {
+            "Patron": 1,
+            "Checkout Time": 5
+        },
+        {
+            "Patron": 2,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 3,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 4,
+            "Checkout Time": 5
+        },
+        {
+            "Patron": 5,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 6,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 7,
+            "Checkout Time": 5
+        },
+        {
+            "Patron": 8,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 9,
+            "Checkout Time": 5
+        },
+        {
+            "Patron": 10,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 11,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 12,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 13,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 14,
+            "Checkout Time": 5
+        },
+        {
+            "Patron": 15,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 16,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 17,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 18,
+            "Checkout Time": 5
+        },
+        {
+            "Patron": 19,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 20,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 21,
+            "Checkout Time": 5
+        },
+        {
+            "Patron": 22,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 23,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 24,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 25,
+            "Checkout Time": 5
+        },
+        {
+            "Patron": 26,
+            "Checkout Time": 7
+        },
+        {
+            "Patron": 27,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 28,
+            "Checkout Time": 6
+        },
+        {
+            "Patron": 29,
+            "Checkout Time": 7
+        }
+    ]
+    actual_records = client.get(f'/api/db/v0/queries/{query_id}/records/').json()['results']
+    assert sorted(actual_records, key=lambda x: x['Patron']) == expect_records
+
+
 def test_percentage_true_aggregation(payments_ma_table, get_uid, client):
     _ = payments_ma_table
     payments = {