]> git.notmuchmail.org Git - notmuch/blob - bindings/python/notmuch/database.py
debian: changelog for 0.11.1
[notmuch] / bindings / python / notmuch / database.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 import os
21 from ctypes import c_char_p, c_void_p, c_uint, c_long, byref, POINTER
22 from notmuch.globals import (nmlib, STATUS, NotmuchError, NotInitializedError,
23      NullPointerError, Enum, _str,
24      NotmuchDatabaseP, NotmuchDirectoryP, NotmuchMessageP, NotmuchTagsP,
25      NotmuchQueryP, NotmuchMessagesP, NotmuchThreadsP, NotmuchFilenamesP)
26 from notmuch.thread import Threads
27 from notmuch.message import Messages, Message
28 from notmuch.tag import Tags
29
30
31 class Database(object):
32     """The :class:`Database` is the highest-level object that notmuch
33     provides. It references a notmuch database, and can be opened in
34     read-only or read-write mode. A :class:`Query` can be derived from
35     or be applied to a specific database to find messages. Also adding
36     and removing messages to the database happens via this
37     object. Modifications to the database are not atmic by default (see
38     :meth:`begin_atomic`) and once a database has been modified, all
39     other database objects pointing to the same data-base will throw an
40     :exc:`XapianError` as the underlying database has been
41     modified. Close and reopen the database to continue working with it.
42
43     .. note::
44
45         Any function in this class can and will throw an
46         :exc:`NotInitializedError` if the database was not intitialized
47         properly.
48
49     .. note::
50
51         Do remember that as soon as we tear down (e.g. via `del db`) this
52         object, all underlying derived objects such as queries, threads,
53         messages, tags etc will be freed by the underlying library as well.
54         Accessing these objects will lead to segfaults and other unexpected
55         behavior. See above for more details.
56     """
57     _std_db_path = None
58     """Class attribute to cache user's default database"""
59
60     MODE = Enum(['READ_ONLY', 'READ_WRITE'])
61     """Constants: Mode in which to open the database"""
62
63     """notmuch_database_get_directory"""
64     _get_directory = nmlib.notmuch_database_get_directory
65     _get_directory.argtypes = [NotmuchDatabaseP, c_char_p]
66     _get_directory.restype = NotmuchDirectoryP
67
68     """notmuch_database_get_path"""
69     _get_path = nmlib.notmuch_database_get_path
70     _get_path.argtypes = [NotmuchDatabaseP]
71     _get_path.restype = c_char_p
72
73     """notmuch_database_get_version"""
74     _get_version = nmlib.notmuch_database_get_version
75     _get_version.argtypes = [NotmuchDatabaseP]
76     _get_version.restype = c_uint
77
78     """notmuch_database_open"""
79     _open = nmlib.notmuch_database_open
80     _open.argtypes = [c_char_p, c_uint]
81     _open.restype = NotmuchDatabaseP
82
83     """notmuch_database_upgrade"""
84     _upgrade = nmlib.notmuch_database_upgrade
85     _upgrade.argtypes = [NotmuchDatabaseP, c_void_p, c_void_p]
86     _upgrade.restype = c_uint
87
88     """ notmuch_database_find_message"""
89     _find_message = nmlib.notmuch_database_find_message
90     _find_message.argtypes = [NotmuchDatabaseP, c_char_p,
91                               POINTER(NotmuchMessageP)]
92     _find_message.restype = c_uint
93
94     """notmuch_database_find_message_by_filename"""
95     _find_message_by_filename = nmlib.notmuch_database_find_message_by_filename
96     _find_message_by_filename.argtypes = [NotmuchDatabaseP, c_char_p,
97                                           POINTER(NotmuchMessageP)]
98     _find_message_by_filename.restype = c_uint
99
100     """notmuch_database_get_all_tags"""
101     _get_all_tags = nmlib.notmuch_database_get_all_tags
102     _get_all_tags.argtypes = [NotmuchDatabaseP]
103     _get_all_tags.restype = NotmuchTagsP
104
105     """notmuch_database_create"""
106     _create = nmlib.notmuch_database_create
107     _create.argtypes = [c_char_p]
108     _create.restype = NotmuchDatabaseP
109
110     def __init__(self, path=None, create=False, mode=0):
111         """If *path* is `None`, we will try to read a users notmuch
112         configuration and use his configured database. The location of the
113         configuration file can be specified through the environment variable
114         *NOTMUCH_CONFIG*, falling back to the default `~/.notmuch-config`.
115
116         If *create* is `True`, the database will always be created in
117         :attr:`MODE`.READ_WRITE mode. Default mode for opening is READ_ONLY.
118
119         :param path:   Directory to open/create the database in (see
120                        above for behavior if `None`)
121         :type path:    `str` or `None`
122         :param create: Pass `False` to open an existing, `True` to create a new
123                        database.
124         :type create:  bool
125         :param mode:   Mode to open a database in. Is always
126                        :attr:`MODE`.READ_WRITE when creating a new one.
127         :type mode:    :attr:`MODE`
128         :exception: :exc:`NotmuchError` or derived exception in case of
129             failure.
130         """
131         self._db = None
132         if path is None:
133             # no path specified. use a user's default database
134             if Database._std_db_path is None:
135                 #the following line throws a NotmuchError if it fails
136                 Database._std_db_path = self._get_user_default_db()
137             path = Database._std_db_path
138
139         if create == False:
140             self.open(path, mode)
141         else:
142             self.create(path)
143
144     def _assert_db_is_initialized(self):
145         """Raises :exc:`NotInitializedError` if self._db is `None`"""
146         if self._db is None:
147             raise NotInitializedError()
148
149     def create(self, path):
150         """Creates a new notmuch database
151
152         This function is used by __init__() and usually does not need
153         to be called directly. It wraps the underlying
154         *notmuch_database_create* function and creates a new notmuch
155         database at *path*. It will always return a database in :attr:`MODE`
156         .READ_WRITE mode as creating an empty database for
157         reading only does not make a great deal of sense.
158
159         :param path: A directory in which we should create the database.
160         :type path: str
161         :returns: Nothing
162         :exception: :exc:`NotmuchError` in case of any failure
163                     (possibly after printing an error message on stderr).
164         """
165         if self._db is not None:
166             raise NotmuchError(message="Cannot create db, this Database() "
167                                        "already has an open one.")
168
169         res = Database._create(_str(path), Database.MODE.READ_WRITE)
170
171         if not res:
172             raise NotmuchError(
173                 message="Could not create the specified database")
174         self._db = res
175
176     def open(self, path, mode=0):
177         """Opens an existing database
178
179         This function is used by __init__() and usually does not need
180         to be called directly. It wraps the underlying
181         *notmuch_database_open* function.
182
183         :param status: Open the database in read-only or read-write mode
184         :type status:  :attr:`MODE`
185         :returns: Nothing
186         :exception: Raises :exc:`NotmuchError` in case of any failure
187                     (possibly after printing an error message on stderr).
188         """
189         res = Database._open(_str(path), mode)
190
191         if not res:
192             raise NotmuchError(message="Could not open the specified database")
193         self._db = res
194
195     def get_path(self):
196         """Returns the file path of an open database"""
197         self._assert_db_is_initialized()
198         return Database._get_path(self._db).decode('utf-8')
199
200     def get_version(self):
201         """Returns the database format version
202
203         :returns: The database version as positive integer
204         """
205         self._assert_db_is_initialized()
206         return Database._get_version(self._db)
207
208     _needs_upgrade = nmlib.notmuch_database_needs_upgrade
209     _needs_upgrade.argtypes = [NotmuchDatabaseP]
210     _needs_upgrade.restype = bool
211
212     def needs_upgrade(self):
213         """Does this database need to be upgraded before writing to it?
214
215         If this function returns `True` then no functions that modify the
216         database (:meth:`add_message`,
217         :meth:`Message.add_tag`, :meth:`Directory.set_mtime`,
218         etc.) will work unless :meth:`upgrade` is called successfully first.
219
220         :returns: `True` or `False`
221         """
222         self._assert_db_is_initialized()
223         return self._needs_upgrade(self._db)
224
225     def upgrade(self):
226         """Upgrades the current database
227
228         After opening a database in read-write mode, the client should
229         check if an upgrade is needed (notmuch_database_needs_upgrade) and
230         if so, upgrade with this function before making any modifications.
231
232         NOT IMPLEMENTED: The optional progress_notify callback can be
233         used by the caller to provide progress indication to the
234         user. If non-NULL it will be called periodically with
235         'progress' as a floating-point value in the range of [0.0..1.0]
236         indicating the progress made so far in the upgrade process.
237
238         :TODO: catch exceptions, document return values and etc...
239         """
240         self._assert_db_is_initialized()
241         status = Database._upgrade(self._db, None, None)
242         #TODO: catch exceptions, document return values and etc
243         return status
244
245     _begin_atomic = nmlib.notmuch_database_begin_atomic
246     _begin_atomic.argtypes = [NotmuchDatabaseP]
247     _begin_atomic.restype = c_uint
248
249     def begin_atomic(self):
250         """Begin an atomic database operation
251
252         Any modifications performed between a successful
253         :meth:`begin_atomic` and a :meth:`end_atomic` will be applied to
254         the database atomically.  Note that, unlike a typical database
255         transaction, this only ensures atomicity, not durability;
256         neither begin nor end necessarily flush modifications to disk.
257
258         :returns: :attr:`STATUS`.SUCCESS or raises
259         :exception: :exc:`NotmuchError`: :attr:`STATUS`.XAPIAN_EXCEPTION
260                     Xapian exception occurred; atomic section not entered.
261
262         *Added in notmuch 0.9*"""
263         self._assert_db_is_initialized()
264         status = self._begin_atomic(self._db)
265         if status != STATUS.SUCCESS:
266             raise NotmuchError(status)
267         return status
268
269     _end_atomic = nmlib.notmuch_database_end_atomic
270     _end_atomic.argtypes = [NotmuchDatabaseP]
271     _end_atomic.restype = c_uint
272
273     def end_atomic(self):
274         """Indicate the end of an atomic database operation
275
276         See :meth:`begin_atomic` for details.
277
278         :returns: :attr:`STATUS`.SUCCESS or raises
279
280         :exception:
281             :exc:`NotmuchError`:
282                 :attr:`STATUS`.XAPIAN_EXCEPTION
283                     A Xapian exception occurred; atomic section not
284                     ended.
285                 :attr:`STATUS`.UNBALANCED_ATOMIC:
286                     end_atomic has been called more times than begin_atomic.
287
288         *Added in notmuch 0.9*"""
289         self._assert_db_is_initialized()
290         status = self._end_atomic(self._db)
291         if status != STATUS.SUCCESS:
292             raise NotmuchError(status)
293         return status
294
295     def get_directory(self, path):
296         """Returns a :class:`Directory` of path,
297         (creating it if it does not exist(?))
298
299         .. warning::
300
301             This call needs a writeable database in
302             :attr:`Database.MODE`.READ_WRITE mode. The underlying library will
303             exit the program if this method is used on a read-only database!
304
305         :param path: An unicode string containing the path relative to the path
306               of database (see :meth:`get_path`), or else should be an absolute
307               path with initial components that match the path of 'database'.
308         :returns: :class:`Directory` or raises an exception.
309         :exception:
310             :exc:`NotmuchError` with :attr:`STATUS`.FILE_ERROR
311                     If path is not relative database or absolute with initial
312                     components same as database.
313         """
314         self._assert_db_is_initialized()
315         # sanity checking if path is valid, and make path absolute
316         if path[0] == os.sep:
317             # we got an absolute path
318             if not path.startswith(self.get_path()):
319                 # but its initial components are not equal to the db path
320                 raise NotmuchError(STATUS.FILE_ERROR,
321                                    message="Database().get_directory() called "
322                                            "with a wrong absolute path.")
323             abs_dirpath = path
324         else:
325             #we got a relative path, make it absolute
326             abs_dirpath = os.path.abspath(os.path.join(self.get_path(), path))
327
328         dir_p = Database._get_directory(self._db, _str(path))
329
330         # return the Directory, init it with the absolute path
331         return Directory(_str(abs_dirpath), dir_p, self)
332
333     _add_message = nmlib.notmuch_database_add_message
334     _add_message.argtypes = [NotmuchDatabaseP, c_char_p,
335                              POINTER(NotmuchMessageP)]
336     _add_message.restype = c_uint
337
338     def add_message(self, filename, sync_maildir_flags=False):
339         """Adds a new message to the database
340
341         :param filename: should be a path relative to the path of the
342             open database (see :meth:`get_path`), or else should be an
343             absolute filename with initial components that match the
344             path of the database.
345
346             The file should be a single mail message (not a
347             multi-message mbox) that is expected to remain at its
348             current location, since the notmuch database will reference
349             the filename, and will not copy the entire contents of the
350             file.
351
352         :param sync_maildir_flags: If the message contains Maildir
353             flags, we will -depending on the notmuch configuration- sync
354             those tags to initial notmuch tags, if set to `True`. It is
355             `False` by default to remain consistent with the libnotmuch
356             API. You might want to look into the underlying method
357             :meth:`Message.maildir_flags_to_tags`.
358
359         :returns: On success, we return
360
361            1) a :class:`Message` object that can be used for things
362               such as adding tags to the just-added message.
363            2) one of the following :attr:`STATUS` values:
364
365               :attr:`STATUS`.SUCCESS
366                   Message successfully added to database.
367               :attr:`STATUS`.DUPLICATE_MESSAGE_ID
368                   Message has the same message ID as another message already
369                   in the database. The new filename was successfully added
370                   to the list of the filenames for the existing message.
371
372         :rtype:   2-tuple(:class:`Message`, :attr:`STATUS`)
373
374         :exception: Raises a :exc:`NotmuchError` with the following meaning.
375               If such an exception occurs, nothing was added to the database.
376
377               :attr:`STATUS`.FILE_ERROR
378                       An error occurred trying to open the file, (such as
379                       permission denied, or file not found, etc.).
380               :attr:`STATUS`.FILE_NOT_EMAIL
381                       The contents of filename don't look like an email
382                       message.
383               :attr:`STATUS`.READ_ONLY_DATABASE
384                       Database was opened in read-only mode so no message can
385                       be added.
386         """
387         self._assert_db_is_initialized()
388         msg_p = NotmuchMessageP()
389         status = self._add_message(self._db, _str(filename), byref(msg_p))
390
391         if not status in [STATUS.SUCCESS, STATUS.DUPLICATE_MESSAGE_ID]:
392             raise NotmuchError(status)
393
394         #construct Message() and return
395         msg = Message(msg_p, self)
396         #automatic sync initial tags from Maildir flags
397         if sync_maildir_flags:
398             msg.maildir_flags_to_tags()
399         return (msg, status)
400
401     _remove_message = nmlib.notmuch_database_remove_message
402     _remove_message.argtypes = [NotmuchDatabaseP, c_char_p]
403     _remove_message.restype = c_uint
404
405     def remove_message(self, filename):
406         """Removes a message (filename) from the given notmuch database
407
408         Note that only this particular filename association is removed from
409         the database. If the same message (as determined by the message ID)
410         is still available via other filenames, then the message will
411         persist in the database for those filenames. When the last filename
412         is removed for a particular message, the database content for that
413         message will be entirely removed.
414
415         :returns: A :attr:`STATUS` value with the following meaning:
416
417              :attr:`STATUS`.SUCCESS
418                The last filename was removed and the message was removed
419                from the database.
420              :attr:`STATUS`.DUPLICATE_MESSAGE_ID
421                This filename was removed but the message persists in the
422                database with at least one other filename.
423
424         :exception: Raises a :exc:`NotmuchError` with the following meaning.
425              If such an exception occurs, nothing was removed from the
426              database.
427
428              :attr:`STATUS`.READ_ONLY_DATABASE
429                Database was opened in read-only mode so no message can be
430                removed.
431         """
432         self._assert_db_is_initialized()
433         return self._remove_message(self._db, filename)
434
435     def find_message(self, msgid):
436         """Returns a :class:`Message` as identified by its message ID
437
438         Wraps the underlying *notmuch_database_find_message* function.
439
440         :param msgid: The message ID
441         :type msgid: unicode or str
442         :returns: :class:`Message` or `None` if no message is found.
443         :exception:
444             :exc:`OutOfMemoryError`
445                   If an Out-of-memory occured while constructing the message.
446             :exc:`XapianError`
447                   In case of a Xapian Exception. These exceptions
448                   include "Database modified" situations, e.g. when the
449                   notmuch database has been modified by another program
450                   in the meantime. In this case, you should close and
451                   reopen the database and retry.
452             :exc:`NotInitializedError` if
453                     the database was not intitialized.
454         """
455         self._assert_db_is_initialized()
456         msg_p = NotmuchMessageP()
457         status = Database._find_message(self._db, _str(msgid), byref(msg_p))
458         if status != STATUS.SUCCESS:
459             raise NotmuchError(status)
460         return msg_p and Message(msg_p, self) or None
461
462     def find_message_by_filename(self, filename):
463         """Find a message with the given filename
464
465         .. warning::
466
467             This call needs a writeable database in
468             :attr:`Database.MODE`.READ_WRITE mode. The underlying library will
469             exit the program if this method is used on a read-only database!
470
471         :returns: If the database contains a message with the given
472             filename, then a class:`Message:` is returned.  This
473             function returns None if no message is found with the given
474             filename.
475
476         :exception:
477             :exc:`OutOfMemoryError`
478                   If an Out-of-memory occured while constructing the message.
479             :exc:`XapianError`
480                   In case of a Xapian Exception. These exceptions
481                   include "Database modified" situations, e.g. when the
482                   notmuch database has been modified by another program
483                   in the meantime. In this case, you should close and
484                   reopen the database and retry.
485             :exc:`NotInitializedError` if
486                     the database was not intitialized.
487
488         *Added in notmuch 0.9*"""
489         self._assert_db_is_initialized()
490         msg_p = NotmuchMessageP()
491         status = Database._find_message_by_filename(self._db, _str(filename),
492                                                     byref(msg_p))
493         if status != STATUS.SUCCESS:
494             raise NotmuchError(status)
495         return msg_p and Message(msg_p, self) or None
496
497     def get_all_tags(self):
498         """Returns :class:`Tags` with a list of all tags found in the database
499
500         :returns: :class:`Tags`
501         :execption: :exc:`NotmuchError` with :attr:`STATUS`.NULL_POINTER
502                     on error
503         """
504         self._assert_db_is_initialized()
505         tags_p = Database._get_all_tags(self._db)
506         if tags_p == None:
507             raise NotmuchError(STATUS.NULL_POINTER)
508         return Tags(tags_p, self)
509
510     def create_query(self, querystring):
511         """Returns a :class:`Query` derived from this database
512
513         This is a shorthand method for doing::
514
515           # short version
516           # Automatically frees the Database() when 'q' is deleted
517
518           q  = Database(dbpath).create_query('from:"Biene Maja"')
519
520           # long version, which is functionally equivalent but will keep the
521           # Database in the 'db' variable around after we delete 'q':
522
523           db = Database(dbpath)
524           q  = Query(db,'from:"Biene Maja"')
525
526         This function is a python extension and not in the underlying C API.
527         """
528         return Query(self, querystring)
529
530     def __repr__(self):
531         return "'Notmuch DB " + self.get_path() + "'"
532
533     _close = nmlib.notmuch_database_close
534     _close.argtypes = [NotmuchDatabaseP]
535     _close.restype = None
536
537     def __del__(self):
538         """Close and free the notmuch database if needed"""
539         if self._db is not None:
540             self._close(self._db)
541
542     def _get_user_default_db(self):
543         """ Reads a user's notmuch config and returns his db location
544
545         Throws a NotmuchError if it cannot find it"""
546         from ConfigParser import SafeConfigParser
547         config = SafeConfigParser()
548         conf_f = os.getenv('NOTMUCH_CONFIG',
549                            os.path.expanduser('~/.notmuch-config'))
550         config.read(conf_f)
551         if not config.has_option('database', 'path'):
552             raise NotmuchError(message="No DB path specified"
553                                        " and no user default found")
554         return config.get('database', 'path').decode('utf-8')
555
556     @property
557     def db_p(self):
558         """Property returning a pointer to `notmuch_database_t` or `None`
559
560         This should normally not be needed by a user (and is not yet
561         guaranteed to remain stable in future versions).
562         """
563         return self._db
564
565
566 class Query(object):
567     """Represents a search query on an opened :class:`Database`.
568
569     A query selects and filters a subset of messages from the notmuch
570     database we derive from.
571
572     :class:`Query` provides an instance attribute :attr:`sort`, which
573     contains the sort order (if specified via :meth:`set_sort`) or
574     `None`.
575
576     Any function in this class may throw an :exc:`NotInitializedError`
577     in case the underlying query object was not set up correctly.
578
579     .. note:: Do remember that as soon as we tear down this object,
580            all underlying derived objects such as threads,
581            messages, tags etc will be freed by the underlying library
582            as well. Accessing these objects will lead to segfaults and
583            other unexpected behavior. See above for more details.
584     """
585     # constants
586     SORT = Enum(['OLDEST_FIRST', 'NEWEST_FIRST', 'MESSAGE_ID', 'UNSORTED'])
587     """Constants: Sort order in which to return results"""
588
589     """notmuch_query_create"""
590     _create = nmlib.notmuch_query_create
591     _create.argtypes = [NotmuchDatabaseP, c_char_p]
592     _create.restype = NotmuchQueryP
593
594     """notmuch_query_search_threads"""
595     _search_threads = nmlib.notmuch_query_search_threads
596     _search_threads.argtypes = [NotmuchQueryP]
597     _search_threads.restype = NotmuchThreadsP
598
599     """notmuch_query_search_messages"""
600     _search_messages = nmlib.notmuch_query_search_messages
601     _search_messages.argtypes = [NotmuchQueryP]
602     _search_messages.restype = NotmuchMessagesP
603
604     """notmuch_query_count_messages"""
605     _count_messages = nmlib.notmuch_query_count_messages
606     _count_messages.argtypes = [NotmuchQueryP]
607     _count_messages.restype = c_uint
608
609     def __init__(self, db, querystr):
610         """
611         :param db: An open database which we derive the Query from.
612         :type db: :class:`Database`
613         :param querystr: The query string for the message.
614         :type querystr: utf-8 encoded str or unicode
615         """
616         self._db = None
617         self._query = None
618         self.sort = None
619         self.create(db, querystr)
620
621     def _assert_query_is_initialized(self):
622         """Raises :exc:`NotInitializedError` if self._query is `None`"""
623         if self._query is None:
624             raise NotInitializedError()
625
626     def create(self, db, querystr):
627         """Creates a new query derived from a Database
628
629         This function is utilized by __init__() and usually does not need to
630         be called directly.
631
632         :param db: Database to create the query from.
633         :type db: :class:`Database`
634         :param querystr: The query string
635         :type querystr: utf-8 encoded str or unicode
636         :returns: Nothing
637         :exception:
638             :exc:`NullPointerError` if the query creation failed
639                 (e.g. too little memory).
640             :exc:`NotInitializedError` if the underlying db was not
641                 intitialized.
642         """
643         db._assert_db_is_initialized()
644         # create reference to parent db to keep it alive
645         self._db = db
646         # create query, return None if too little mem available
647         query_p = Query._create(db.db_p, _str(querystr))
648         if not query_p:
649             raise NullPointerError
650         self._query = query_p
651
652     _set_sort = nmlib.notmuch_query_set_sort
653     _set_sort.argtypes = [NotmuchQueryP, c_uint]
654     _set_sort.argtypes = None
655
656     def set_sort(self, sort):
657         """Set the sort order future results will be delivered in
658
659         :param sort: Sort order (see :attr:`Query.SORT`)
660         """
661         self._assert_query_is_initialized()
662         self.sort = sort
663         self._set_sort(self._query, sort)
664
665     def search_threads(self):
666         """Execute a query for threads
667
668         Execute a query for threads, returning a :class:`Threads` iterator.
669         The returned threads are owned by the query and as such, will only be
670         valid until the Query is deleted.
671
672         The method sets :attr:`Message.FLAG`\.MATCH for those messages that
673         match the query. The method :meth:`Message.get_flag` allows us
674         to get the value of this flag.
675
676         :returns: :class:`Threads`
677         :exception: :exc:`NullPointerError` if search_threads failed
678         """
679         self._assert_query_is_initialized()
680         threads_p = Query._search_threads(self._query)
681
682         if not threads_p:
683             raise NullPointerError
684         return Threads(threads_p, self)
685
686     def search_messages(self):
687         """Filter messages according to the query and return
688         :class:`Messages` in the defined sort order
689
690         :returns: :class:`Messages`
691         :exception: :exc:`NullPointerError` if search_messages failed
692         """
693         self._assert_query_is_initialized()
694         msgs_p = Query._search_messages(self._query)
695
696         if not msgs_p:
697             raise NullPointerError
698         return Messages(msgs_p, self)
699
700     def count_messages(self):
701         """Estimate the number of messages matching the query
702
703         This function performs a search and returns Xapian's best
704         guess as to the number of matching messages. It is much faster
705         than performing :meth:`search_messages` and counting the
706         result with `len()` (although it always returned the same
707         result in my tests). Technically, it wraps the underlying
708         *notmuch_query_count_messages* function.
709
710         :returns: :class:`Messages`
711         """
712         self._assert_query_is_initialized()
713         return Query._count_messages(self._query)
714
715     _destroy = nmlib.notmuch_query_destroy
716     _destroy.argtypes = [NotmuchQueryP]
717     _destroy.restype = None
718
719     def __del__(self):
720         """Close and free the Query"""
721         if self._query is not None:
722             self._destroy(self._query)
723
724
725 class Directory(object):
726     """Represents a directory entry in the notmuch directory
727
728     Modifying attributes of this object will modify the
729     database, not the real directory attributes.
730
731     The Directory object is usually derived from another object
732     e.g. via :meth:`Database.get_directory`, and will automatically be
733     become invalid whenever that parent is deleted. You should
734     therefore initialized this object handing it a reference to the
735     parent, preventing the parent from automatically being garbage
736     collected.
737     """
738
739     """notmuch_directory_get_mtime"""
740     _get_mtime = nmlib.notmuch_directory_get_mtime
741     _get_mtime.argtypes = [NotmuchDirectoryP]
742     _get_mtime.restype = c_long
743
744     """notmuch_directory_set_mtime"""
745     _set_mtime = nmlib.notmuch_directory_set_mtime
746     _set_mtime.argtypes = [NotmuchDirectoryP, c_long]
747     _set_mtime.restype = c_uint
748
749     """notmuch_directory_get_child_files"""
750     _get_child_files = nmlib.notmuch_directory_get_child_files
751     _get_child_files.argtypes = [NotmuchDirectoryP]
752     _get_child_files.restype = NotmuchFilenamesP
753
754     """notmuch_directory_get_child_directories"""
755     _get_child_directories = nmlib.notmuch_directory_get_child_directories
756     _get_child_directories.argtypes = [NotmuchDirectoryP]
757     _get_child_directories.restype = NotmuchFilenamesP
758
759     def _assert_dir_is_initialized(self):
760         """Raises a NotmuchError(:attr:`STATUS`.NOT_INITIALIZED)
761         if dir_p is None"""
762         if not self._dir_p:
763             raise NotmuchError(STATUS.NOT_INITIALIZED)
764
765     def __init__(self, path, dir_p, parent):
766         """
767         :param path:   The absolute path of the directory object as unicode.
768         :param dir_p:  The pointer to an internal notmuch_directory_t object.
769         :param parent: The object this Directory is derived from
770                        (usually a :class:`Database`). We do not directly use
771                        this, but store a reference to it as long as
772                        this Directory object lives. This keeps the
773                        parent object alive.
774         """
775         assert isinstance(path, unicode), "Path needs to be an UNICODE object"
776         self._path = path
777         self._dir_p = dir_p
778         self._parent = parent
779
780     def set_mtime(self, mtime):
781         """Sets the mtime value of this directory in the database
782
783         The intention is for the caller to use the mtime to allow efficient
784         identification of new messages to be added to the database. The
785         recommended usage is as follows:
786
787         * Read the mtime of a directory from the filesystem
788
789         * Call :meth:`Database.add_message` for all mail files in
790           the directory
791
792         * Call notmuch_directory_set_mtime with the mtime read from the
793           filesystem.  Then, when wanting to check for updates to the
794           directory in the future, the client can call :meth:`get_mtime`
795           and know that it only needs to add files if the mtime of the
796           directory and files are newer than the stored timestamp.
797
798           .. note::
799
800                 :meth:`get_mtime` function does not allow the caller to
801                 distinguish a timestamp of 0 from a non-existent timestamp. So
802                 don't store a timestamp of 0 unless you are comfortable with
803                 that.
804
805           :param mtime: A (time_t) timestamp
806           :returns: Nothing on success, raising an exception on failure.
807           :exception: :exc:`NotmuchError`:
808
809                         :attr:`STATUS`.XAPIAN_EXCEPTION
810                           A Xapian exception occurred, mtime not stored.
811                         :attr:`STATUS`.READ_ONLY_DATABASE
812                           Database was opened in read-only mode so directory
813                           mtime cannot be modified.
814                         :attr:`STATUS`.NOT_INITIALIZED
815                           The directory has not been initialized
816         """
817         self._assert_dir_is_initialized()
818         #TODO: make sure, we convert the mtime parameter to a 'c_long'
819         status = Directory._set_mtime(self._dir_p, mtime)
820
821         #return on success
822         if status == STATUS.SUCCESS:
823             return
824         #fail with Exception otherwise
825         raise NotmuchError(status)
826
827     def get_mtime(self):
828         """Gets the mtime value of this directory in the database
829
830         Retrieves a previously stored mtime for this directory.
831
832         :param mtime: A (time_t) timestamp
833         :returns: Nothing on success, raising an exception on failure.
834         :exception: :exc:`NotmuchError`:
835
836                         :attr:`STATUS`.NOT_INITIALIZED
837                           The directory has not been initialized
838         """
839         self._assert_dir_is_initialized()
840         return Directory._get_mtime(self._dir_p)
841
842     # Make mtime attribute a property of Directory()
843     mtime = property(get_mtime, set_mtime, doc="""Property that allows getting
844                      and setting of the Directory *mtime* (read-write)
845
846                      See :meth:`get_mtime` and :meth:`set_mtime` for usage and
847                      possible exceptions.""")
848
849     def get_child_files(self):
850         """Gets a Filenames iterator listing all the filenames of
851         messages in the database within the given directory.
852
853         The returned filenames will be the basename-entries only (not
854         complete paths.
855         """
856         self._assert_dir_is_initialized()
857         files_p = Directory._get_child_files(self._dir_p)
858         return Filenames(files_p, self)
859
860     def get_child_directories(self):
861         """Gets a :class:`Filenames` iterator listing all the filenames of
862         sub-directories in the database within the given directory
863
864         The returned filenames will be the basename-entries only (not
865         complete paths.
866         """
867         self._assert_dir_is_initialized()
868         files_p = Directory._get_child_directories(self._dir_p)
869         return Filenames(files_p, self)
870
871     @property
872     def path(self):
873         """Returns the absolute path of this Directory (read-only)"""
874         return self._path
875
876     def __repr__(self):
877         """Object representation"""
878         return "<notmuch Directory object '%s'>" % self._path
879
880     _destroy = nmlib.notmuch_directory_destroy
881     _destroy.argtypes = [NotmuchDirectoryP]
882     _destroy.argtypes = None
883
884     def __del__(self):
885         """Close and free the Directory"""
886         if self._dir_p is not None:
887             self._destroy(self._dir_p)
888
889
890 class Filenames(object):
891     """An iterator over File- or Directory names stored in the database"""
892
893     #notmuch_filenames_get
894     _get = nmlib.notmuch_filenames_get
895     _get.argtypes = [NotmuchFilenamesP]
896     _get.restype = c_char_p
897
898     def __init__(self, files_p, parent):
899         """
900         :param files_p: The pointer to an internal notmuch_filenames_t object.
901         :param parent: The object this Directory is derived from
902                        (usually a Directory()). We do not directly use
903                        this, but store a reference to it as long as
904                        this Directory object lives. This keeps the
905                        parent object alive.
906         """
907         self._files_p = files_p
908         self._parent = parent
909
910     def __iter__(self):
911         """ Make Filenames an iterator """
912         return self
913
914     _valid = nmlib.notmuch_filenames_valid
915     _valid.argtypes = [NotmuchFilenamesP]
916     _valid.restype = bool
917
918     _move_to_next = nmlib.notmuch_filenames_move_to_next
919     _move_to_next.argtypes = [NotmuchFilenamesP]
920     _move_to_next.restype = None
921
922     def next(self):
923         if not self._files_p:
924             raise NotmuchError(STATUS.NOT_INITIALIZED)
925
926         if not self._valid(self._files_p):
927             self._files_p = None
928             raise StopIteration
929
930         file = Filenames._get(self._files_p)
931         self._move_to_next(self._files_p)
932         return file
933
934     def __len__(self):
935         """len(:class:`Filenames`) returns the number of contained files
936
937         .. note::
938
939             As this iterates over the files, we will not be able to
940             iterate over them again! So this will fail::
941
942                  #THIS FAILS
943                  files = Database().get_directory('').get_child_files()
944                  if len(files) > 0:  # this 'exhausts' msgs
945                      # next line raises
946                      # NotmuchError(:attr:`STATUS`.NOT_INITIALIZED)
947                      for file in files: print file
948         """
949         if not self._files_p:
950             raise NotmuchError(STATUS.NOT_INITIALIZED)
951
952         i = 0
953         while self._valid(self._files_p):
954             self._move_to_next(self._files_p)
955             i += 1
956         self._files_p = None
957         return i
958
959     _destroy = nmlib.notmuch_filenames_destroy
960     _destroy.argtypes = [NotmuchFilenamesP]
961     _destroy.restype = None
962
963     def __del__(self):
964         """Close and free Filenames"""
965         if self._files_p is not None:
966             self._destroy(self._files_p)