]> git.notmuchmail.org Git - notmuch/blob - bindings/python/notmuch/query.py
python: move Threads class into its own file
[notmuch] / bindings / python / notmuch / query.py
1 """
2 This file is part of notmuch.
3
4 Notmuch is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License as published by the
6 Free Software Foundation, either version 3 of the License, or (at your
7 option) any later version.
8
9 Notmuch is distributed in the hope that it will be useful, but WITHOUT
10 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with notmuch.  If not, see <http://www.gnu.org/licenses/>.
16
17 Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>'
18 """
19
20 from ctypes import c_char_p, c_uint
21 from notmuch.globals import (
22     nmlib,
23     Enum,
24     _str,
25     NotmuchQueryP,
26     NotmuchThreadsP,
27     NotmuchDatabaseP,
28     NotmuchMessagesP,
29     NullPointerError,
30     NotInitializedError,
31 )
32 from .threads import Threads
33 from .messages import Messages
34
35
36 class Query(object):
37     """Represents a search query on an opened :class:`Database`.
38
39     A query selects and filters a subset of messages from the notmuch
40     database we derive from.
41
42     :class:`Query` provides an instance attribute :attr:`sort`, which
43     contains the sort order (if specified via :meth:`set_sort`) or
44     `None`.
45
46     Any function in this class may throw an :exc:`NotInitializedError`
47     in case the underlying query object was not set up correctly.
48
49     .. note:: Do remember that as soon as we tear down this object,
50            all underlying derived objects such as threads,
51            messages, tags etc will be freed by the underlying library
52            as well. Accessing these objects will lead to segfaults and
53            other unexpected behavior. See above for more details.
54     """
55     # constants
56     SORT = Enum(['OLDEST_FIRST', 'NEWEST_FIRST', 'MESSAGE_ID', 'UNSORTED'])
57     """Constants: Sort order in which to return results"""
58
59     def __init__(self, db, querystr):
60         """
61         :param db: An open database which we derive the Query from.
62         :type db: :class:`Database`
63         :param querystr: The query string for the message.
64         :type querystr: utf-8 encoded str or unicode
65         """
66         self._db = None
67         self._query = None
68         self.sort = None
69         self.create(db, querystr)
70
71     def _assert_query_is_initialized(self):
72         """Raises :exc:`NotInitializedError` if self._query is `None`"""
73         if not self._query:
74             raise NotInitializedError()
75
76     """notmuch_query_create"""
77     _create = nmlib.notmuch_query_create
78     _create.argtypes = [NotmuchDatabaseP, c_char_p]
79     _create.restype = NotmuchQueryP
80
81     def create(self, db, querystr):
82         """Creates a new query derived from a Database
83
84         This function is utilized by __init__() and usually does not need to
85         be called directly.
86
87         :param db: Database to create the query from.
88         :type db: :class:`Database`
89         :param querystr: The query string
90         :type querystr: utf-8 encoded str or unicode
91         :raises:
92             :exc:`NullPointerError` if the query creation failed
93                 (e.g. too little memory).
94             :exc:`NotInitializedError` if the underlying db was not
95                 intitialized.
96         """
97         db._assert_db_is_initialized()
98         # create reference to parent db to keep it alive
99         self._db = db
100         # create query, return None if too little mem available
101         query_p = Query._create(db.db_p, _str(querystr))
102         if not query_p:
103             raise NullPointerError
104         self._query = query_p
105
106     _set_sort = nmlib.notmuch_query_set_sort
107     _set_sort.argtypes = [NotmuchQueryP, c_uint]
108     _set_sort.argtypes = None
109
110     def set_sort(self, sort):
111         """Set the sort order future results will be delivered in
112
113         :param sort: Sort order (see :attr:`Query.SORT`)
114         """
115         self._assert_query_is_initialized()
116         self.sort = sort
117         self._set_sort(self._query, sort)
118
119     """notmuch_query_search_threads"""
120     _search_threads = nmlib.notmuch_query_search_threads
121     _search_threads.argtypes = [NotmuchQueryP]
122     _search_threads.restype = NotmuchThreadsP
123
124     def search_threads(self):
125         """Execute a query for threads
126
127         Execute a query for threads, returning a :class:`Threads` iterator.
128         The returned threads are owned by the query and as such, will only be
129         valid until the Query is deleted.
130
131         The method sets :attr:`Message.FLAG`\.MATCH for those messages that
132         match the query. The method :meth:`Message.get_flag` allows us
133         to get the value of this flag.
134
135         :returns: :class:`Threads`
136         :raises: :exc:`NullPointerError` if search_threads failed
137         """
138         self._assert_query_is_initialized()
139         threads_p = Query._search_threads(self._query)
140
141         if not threads_p:
142             raise NullPointerError
143         return Threads(threads_p, self)
144
145     """notmuch_query_search_messages"""
146     _search_messages = nmlib.notmuch_query_search_messages
147     _search_messages.argtypes = [NotmuchQueryP]
148     _search_messages.restype = NotmuchMessagesP
149
150     def search_messages(self):
151         """Filter messages according to the query and return
152         :class:`Messages` in the defined sort order
153
154         :returns: :class:`Messages`
155         :raises: :exc:`NullPointerError` if search_messages failed
156         """
157         self._assert_query_is_initialized()
158         msgs_p = Query._search_messages(self._query)
159
160         if not msgs_p:
161             raise NullPointerError
162         return Messages(msgs_p, self)
163
164     _count_messages = nmlib.notmuch_query_count_messages
165     _count_messages.argtypes = [NotmuchQueryP]
166     _count_messages.restype = c_uint
167
168     def count_messages(self):
169         '''
170         This function performs a search and returns Xapian's best
171         guess as to the number of matching messages.
172
173         :returns: the estimated number of messages matching this query
174         :rtype:   int
175         '''
176         self._assert_query_is_initialized()
177         return Query._count_messages(self._query)
178
179     _count_threads = nmlib.notmuch_query_count_threads
180     _count_threads.argtypes = [NotmuchQueryP]
181     _count_threads.restype = c_uint
182
183     def count_threads(self):
184         '''
185         This function performs a search and returns the number of
186         unique thread IDs in the matching messages. This is the same
187         as number of threads matching a search.
188
189         Note that this is a significantly heavier operation than
190         meth:`Query.count_messages`.
191
192         :returns: the number of threads returned by this query
193         :rtype:   int
194         '''
195         self._assert_query_is_initialized()
196         return Query._count_threads(self._query)
197
198     _destroy = nmlib.notmuch_query_destroy
199     _destroy.argtypes = [NotmuchQueryP]
200     _destroy.restype = None
201
202     def __del__(self):
203         """Close and free the Query"""
204         if self._query is not None:
205             self._destroy(self._query)