Coverage for manila/db/sqlalchemy/utils.py: 100%
15 statements
« prev ^ index » next coverage.py v7.11.0, created at 2026-02-18 22:19 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2026-02-18 22:19 +0000
1# Licensed under the Apache License, Version 2.0 (the "License"); you may
2# not use this file except in compliance with the License. You may obtain
3# a copy of the License at
4#
5# http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10# License for the specific language governing permissions and limitations
11# under the License.
13"""Implementation of paginate query."""
15from manila import exception
16import sqlalchemy
19def paginate_query(query, model, limit, sort_key='created_at',
20 sort_dir='desc', offset=None):
21 """Returns a query with sorting / pagination criteria added.
23 :param query: the query object to which we should add paging/sorting
24 :param model: the ORM model class
25 :param limit: maximum number of items to return
26 :param sort_key: attributes by which results should be sorted, default is
27 created_at
28 :param sort_dir: direction in which results should be sorted (asc, desc)
29 :param offset: the number of items to skip from the marker or from the
30 first element.
32 :rtype: sqlalchemy.orm.query.Query
33 :return: The query with sorting/pagination added.
34 """
36 try:
37 sort_key_attr = getattr(model, sort_key)
38 except AttributeError:
39 raise exception.InvalidInput(reason='Invalid sort key %s' % sort_key)
40 if sort_dir == 'desc':
41 query = query.order_by(sqlalchemy.desc(sort_key_attr))
42 else:
43 query = query.order_by(sqlalchemy.asc(sort_key_attr))
45 if limit is not None:
46 query = query.limit(limit)
48 if offset:
49 query = query.offset(offset)
51 return query