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