about summary refs log tree commit diff
path: root/uploader/species
diff options
context:
space:
mode:
Diffstat (limited to 'uploader/species')
-rw-r--r--uploader/species/models.py20
1 files changed, 19 insertions, 1 deletions
diff --git a/uploader/species/models.py b/uploader/species/models.py
index 481f8be..53e7de0 100644
--- a/uploader/species/models.py
+++ b/uploader/species/models.py
@@ -1,5 +1,7 @@
 """Database functions for species."""
+import math
 from typing import Optional
+from functools import reduce
 
 import MySQLdb as mdb
 from MySQLdb.cursors import DictCursor
@@ -9,11 +11,27 @@ def all_species(conn: mdb.Connection) -> tuple:
     with conn.cursor(cursorclass=DictCursor) as cursor:
         cursor.execute(
             "SELECT Id AS SpeciesId, SpeciesName, LOWER(Name) AS Name, "
-            "MenuName, FullName, TaxonomyId FROM Species")
+            "MenuName, FullName, TaxonomyId, Family, FamilyOrderId, OrderId "
+            "FROM Species ORDER BY FamilyOrderId ASC, OrderID ASC")
         return tuple(cursor.fetchall())
 
     return tuple()
 
+def order_species_by_family(species: tuple[dict, ...]) -> list:
+    """Order the species by their family"""
+    def __family_order_id__(item):
+        orderid = item["FamilyOrderId"]
+        return math.inf if orderid is None else orderid
+    def __order__(ordered, current):
+        _key = (__family_order_id__(current), current["Family"])
+        return {
+            **ordered,
+            _key: ordered.get(_key, tuple()) + (current,)
+        }
+    ordered = reduce(__order__, species, {})
+    return sorted(tuple(ordered.items()), key=lambda item: item[0][0])
+
+
 def species_by_id(conn: mdb.Connection, speciesid) -> dict:
     "Retrieve the species from the database by id."
     with conn.cursor(cursorclass=DictCursor) as cursor: