aboutsummaryrefslogtreecommitdiff
path: root/app/handlers/count.py
blob: 526af8ab63d2b19f2ce91555db1fa6cd0628ded4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Handle the /count URLs used to count objects in the database."""

from tornado.web import asynchronous

from handlers.base import BaseHandler
from handlers.common import (
    COLLECTIONS,
    COUNT_VALID_KEYS,
    update_id_fields,
    get_and_add_date_range,
    get_query_spec,
)
from handlers.response import HandlerResponse
from models import ID_KEY
from utils.db import (
    count,
    find_and_count,
)

# Internally used only. It is used to retrieve just one field for
# the query results since we only need to count the results, we are
# not interested in the values.
COUNT_FIELDS = {ID_KEY: True}


class CountHandler(BaseHandler):
    """Handle the /count URLs."""

    def __init__(self, application, request, **kwargs):
        super(CountHandler, self).__init__(application, request, **kwargs)

    @staticmethod
    def _valid_keys(method):
        return COUNT_VALID_KEYS.get(method, None)

    def _get_one(self, collection):
        response = HandlerResponse()

        if collection in COLLECTIONS.keys():
            response.result = count_one_collection(
                self.db[COLLECTIONS[collection]],
                collection,
                self.get_query_arguments,
                self._valid_keys("GET")
            )
        else:
            response.status_code = 404
            response.reason = "Collection %s not found" % collection
            response.result = None

        return response

    def _get(self, **kwargs):
        response = HandlerResponse()
        response.result = count_all_collections(
            self.db,
            self.get_query_arguments,
            self._valid_keys("GET")
        )

        return response

    @asynchronous
    def post(self, *args, **kwargs):
        """Not implemented."""
        self.write_error(status_code=501)

    @asynchronous
    def delete(self, *args, **kwargs):
        """Not implemented."""
        self.write_error(status_code=501)


def count_one_collection(
        collection, collection_name, query_args_func, valid_keys):
    """Count all the available documents in the provide collection.

    :param collection: The collection whose elements should be counted.
    :param collection_name: The name of the collection to count.
    :type collection_name: str
    :param query_args_func: A function used to return a list of the query
    arguments.
    :type query_args_func: function
    :param valid_keys: A list containing the valid keys that should be
    retrieved.
    :type valid_keys: list
    :return A list containing a dictionary with the `collection`, `count` and
    optionally the `fields` fields.
    """
    result = []
    spec = get_query_spec(query_args_func, valid_keys)
    get_and_add_date_range(spec, query_args_func)
    update_id_fields(spec)

    if spec:
        _, number = find_and_count(
            collection, 0, 0, spec, COUNT_FIELDS
        )
        if not number:
            number = 0

        result.append(
            dict(collection=collection_name, count=number)
        )
    else:
        result.append(
            dict(
                collection=collection_name,
                count=count(collection)
            )
        )

    return result


def count_all_collections(database, query_args_func, valid_keys):
    """Count all the available documents in the database collections.

    :param database: The datase connection to use.
    :param query_args_func: A function used to return a list of the query
    arguments.
    :type query_args_func: function
    :param valid_keys: A list containing the valid keys that should be
    retrieved.
    :type valid_keys: list
    :return A list containing a dictionary with the `collection` and `count`
    fields.
    """
    result = []

    spec = get_query_spec(query_args_func, valid_keys)
    get_and_add_date_range(spec, query_args_func)
    update_id_fields(spec)

    if spec:
        for key, val in COLLECTIONS.iteritems():
            _, number = find_and_count(
                database[val], 0, 0, spec, COUNT_FIELDS
            )
            if not number:
                number = 0
            result.append(dict(collection=key, count=number))
    else:
        for key, val in COLLECTIONS.iteritems():
            result.append(dict(collection=key, count=count(database[val])))

    return result