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

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. 

12 

13"""Implementation of paginate query.""" 

14 

15from manila import exception 

16import sqlalchemy 

17 

18 

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. 

22 

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. 

31 

32 :rtype: sqlalchemy.orm.query.Query 

33 :return: The query with sorting/pagination added. 

34 """ 

35 

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)) 

44 

45 if limit is not None: 

46 query = query.limit(limit) 

47 

48 if offset: 

49 query = query.offset(offset) 

50 

51 return query