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