Coverage for /opt/conda/envs/apienv/lib/python3.10/site-packages/daiquiri/core/metadata/ispyalchemy/utils.py: 85%
20 statements
« prev ^ index » next coverage.py v7.6.5, created at 2024-11-15 02:12 +0000
« prev ^ index » next coverage.py v7.6.5, created at 2024-11-15 02:12 +0000
1import logging
2from daiquiri.core.utils import get_start_end
4logger = logging.getLogger(__name__)
7def order(query, sort_map, default=None, **kwargs):
8 """Sort a result set by a field
10 Args:
11 query (sqlalchemy.query): The current query
12 sort_map (dict): A mapping of field(str) -> sqlalchemy.column
14 Kwargs:
15 order_by (str): Field to sort by
16 order (str): Asc or desc
18 Returns
19 query (sqlalchemy.query): The ordered query
20 """
21 sort_field = kwargs.get("order_by")
22 sort_order = kwargs.get("order")
24 if not (sort_field and sort_order) and not default:
25 return query
27 if default:
28 if not sort_field:
29 sort_field = default[0]
30 if not sort_order:
31 sort_order = default[1]
33 if sort_field not in sort_map:
34 logger.warning(f"Unknown sort_field {sort_field}")
35 return query
37 return query.order_by(getattr(sort_map[sort_field], sort_order)())
40def page(query, **kwargs):
41 """Paginate a result set
43 Kwargs:
44 per_page (str): Number of rows per page
45 page (str): Page number to display
46 last (bool): Reverse order, last page first
48 Returns
49 query (sqlalchemy.query): The paginated query
50 """
51 lims = get_start_end(kwargs)
52 return query.limit(lims["per_page"]).offset(lims["st"])