]> git.notmuchmail.org Git - notmuch/blob - bindings/python/notmuch/database.py
93183687a4259c8aebe391ccb342c4b577493366
[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 res is None:
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 res is None:
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         try:
547             # python3.x
548             from configparser import SafeConfigParser
549         except ImportError:
550             # python2.x
551             from ConfigParser import SafeConfigParser
552
553         config = SafeConfigParser()
554         conf_f = os.getenv('NOTMUCH_CONFIG',
555                            os.path.expanduser('~/.notmuch-config'))
556         config.read(conf_f)
557         if not config.has_option('database', 'path'):
558             raise NotmuchError(message="No DB path specified"
559                                        " and no user default found")
560         return config.get('database', 'path').decode('utf-8')
561
562     @property
563     def db_p(self):
564         """Property returning a pointer to `notmuch_database_t` or `None`
565
566         This should normally not be needed by a user (and is not yet
567         guaranteed to remain stable in future versions).
568         """
569         return self._db
570
571
572 class Query(object):
573     """Represents a search query on an opened :class:`Database`.
574
575     A query selects and filters a subset of messages from the notmuch
576     database we derive from.
577
578     :class:`Query` provides an instance attribute :attr:`sort`, which
579     contains the sort order (if specified via :meth:`set_sort`) or
580     `None`.
581
582     Any function in this class may throw an :exc:`NotInitializedError`
583     in case the underlying query object was not set up correctly.
584
585     .. note:: Do remember that as soon as we tear down this object,
586            all underlying derived objects such as threads,
587            messages, tags etc will be freed by the underlying library
588            as well. Accessing these objects will lead to segfaults and
589            other unexpected behavior. See above for more details.
590     """
591     # constants
592     SORT = Enum(['OLDEST_FIRST', 'NEWEST_FIRST', 'MESSAGE_ID', 'UNSORTED'])
593     """Constants: Sort order in which to return results"""
594
595     """notmuch_query_create"""
596     _create = nmlib.notmuch_query_create
597     _create.argtypes = [NotmuchDatabaseP, c_char_p]
598     _create.restype = NotmuchQueryP
599
600     """notmuch_query_search_threads"""
601     _search_threads = nmlib.notmuch_query_search_threads
602     _search_threads.argtypes = [NotmuchQueryP]
603     _search_threads.restype = NotmuchThreadsP
604
605     """notmuch_query_search_messages"""
606     _search_messages = nmlib.notmuch_query_search_messages
607     _search_messages.argtypes = [NotmuchQueryP]
608     _search_messages.restype = NotmuchMessagesP
609
610     """notmuch_query_count_messages"""
611     _count_messages = nmlib.notmuch_query_count_messages
612     _count_messages.argtypes = [NotmuchQueryP]
613     _count_messages.restype = c_uint
614
615     def __init__(self, db, querystr):
616         """
617         :param db: An open database which we derive the Query from.
618         :type db: :class:`Database`
619         :param querystr: The query string for the message.
620         :type querystr: utf-8 encoded str or unicode
621         """
622         self._db = None
623         self._query = None
624         self.sort = None
625         self.create(db, querystr)
626
627     def _assert_query_is_initialized(self):
628         """Raises :exc:`NotInitializedError` if self._query is `None`"""
629         if self._query is None:
630             raise NotInitializedError()
631
632     def create(self, db, querystr):
633         """Creates a new query derived from a Database
634
635         This function is utilized by __init__() and usually does not need to
636         be called directly.
637
638         :param db: Database to create the query from.
639         :type db: :class:`Database`
640         :param querystr: The query string
641         :type querystr: utf-8 encoded str or unicode
642         :returns: Nothing
643         :exception:
644             :exc:`NullPointerError` if the query creation failed
645                 (e.g. too little memory).
646             :exc:`NotInitializedError` if the underlying db was not
647                 intitialized.
648         """
649         db._assert_db_is_initialized()
650         # create reference to parent db to keep it alive
651         self._db = db
652         # create query, return None if too little mem available
653         query_p = Query._create(db.db_p, _str(querystr))
654         if query_p is None:
655             raise NullPointerError
656         self._query = query_p
657
658     _set_sort = nmlib.notmuch_query_set_sort
659     _set_sort.argtypes = [NotmuchQueryP, c_uint]
660     _set_sort.argtypes = None
661
662     def set_sort(self, sort):
663         """Set the sort order future results will be delivered in
664
665         :param sort: Sort order (see :attr:`Query.SORT`)
666         """
667         self._assert_query_is_initialized()
668         self.sort = sort
669         self._set_sort(self._query, sort)
670
671     def search_threads(self):
672         """Execute a query for threads
673
674         Execute a query for threads, returning a :class:`Threads` iterator.
675         The returned threads are owned by the query and as such, will only be
676         valid until the Query is deleted.
677
678         The method sets :attr:`Message.FLAG`\.MATCH for those messages that
679         match the query. The method :meth:`Message.get_flag` allows us
680         to get the value of this flag.
681
682         :returns: :class:`Threads`
683         :exception: :exc:`NullPointerError` if search_threads failed
684         """
685         self._assert_query_is_initialized()
686         threads_p = Query._search_threads(self._query)
687
688         if threads_p is None:
689             raise NullPointerError
690         return Threads(threads_p, self)
691
692     def search_messages(self):
693         """Filter messages according to the query and return
694         :class:`Messages` in the defined sort order
695
696         :returns: :class:`Messages`
697         :exception: :exc:`NullPointerError` if search_messages failed
698         """
699         self._assert_query_is_initialized()
700         msgs_p = Query._search_messages(self._query)
701
702         if msgs_p is None:
703             raise NullPointerError
704         return Messages(msgs_p, self)
705
706     def count_messages(self):
707         """Estimate the number of messages matching the query
708
709         This function performs a search and returns Xapian's best
710         guess as to the number of matching messages. It is much faster
711         than performing :meth:`search_messages` and counting the
712         result with `len()` (although it always returned the same
713         result in my tests). Technically, it wraps the underlying
714         *notmuch_query_count_messages* function.
715
716         :returns: :class:`Messages`
717         """
718         self._assert_query_is_initialized()
719         return Query._count_messages(self._query)
720
721     _destroy = nmlib.notmuch_query_destroy
722     _destroy.argtypes = [NotmuchQueryP]
723     _destroy.restype = None
724
725     def __del__(self):
726         """Close and free the Query"""
727         if self._query is not None:
728             self._destroy(self._query)
729
730
731 class Directory(object):
732     """Represents a directory entry in the notmuch directory
733
734     Modifying attributes of this object will modify the
735     database, not the real directory attributes.
736
737     The Directory object is usually derived from another object
738     e.g. via :meth:`Database.get_directory`, and will automatically be
739     become invalid whenever that parent is deleted. You should
740     therefore initialized this object handing it a reference to the
741     parent, preventing the parent from automatically being garbage
742     collected.
743     """
744
745     """notmuch_directory_get_mtime"""
746     _get_mtime = nmlib.notmuch_directory_get_mtime
747     _get_mtime.argtypes = [NotmuchDirectoryP]
748     _get_mtime.restype = c_long
749
750     """notmuch_directory_set_mtime"""
751     _set_mtime = nmlib.notmuch_directory_set_mtime
752     _set_mtime.argtypes = [NotmuchDirectoryP, c_long]
753     _set_mtime.restype = c_uint
754
755     """notmuch_directory_get_child_files"""
756     _get_child_files = nmlib.notmuch_directory_get_child_files
757     _get_child_files.argtypes = [NotmuchDirectoryP]
758     _get_child_files.restype = NotmuchFilenamesP
759
760     """notmuch_directory_get_child_directories"""
761     _get_child_directories = nmlib.notmuch_directory_get_child_directories
762     _get_child_directories.argtypes = [NotmuchDirectoryP]
763     _get_child_directories.restype = NotmuchFilenamesP
764
765     def _assert_dir_is_initialized(self):
766         """Raises a NotmuchError(:attr:`STATUS`.NOT_INITIALIZED)
767         if dir_p is None"""
768         if self._dir_p is None:
769             raise NotmuchError(STATUS.NOT_INITIALIZED)
770
771     def __init__(self, path, dir_p, parent):
772         """
773         :param path:   The absolute path of the directory object as unicode.
774         :param dir_p:  The pointer to an internal notmuch_directory_t object.
775         :param parent: The object this Directory is derived from
776                        (usually a :class:`Database`). We do not directly use
777                        this, but store a reference to it as long as
778                        this Directory object lives. This keeps the
779                        parent object alive.
780         """
781         assert isinstance(path, unicode), "Path needs to be an UNICODE object"
782         self._path = path
783         self._dir_p = dir_p
784         self._parent = parent
785
786     def set_mtime(self, mtime):
787         """Sets the mtime value of this directory in the database
788
789         The intention is for the caller to use the mtime to allow efficient
790         identification of new messages to be added to the database. The
791         recommended usage is as follows:
792
793         * Read the mtime of a directory from the filesystem
794
795         * Call :meth:`Database.add_message` for all mail files in
796           the directory
797
798         * Call notmuch_directory_set_mtime with the mtime read from the
799           filesystem.  Then, when wanting to check for updates to the
800           directory in the future, the client can call :meth:`get_mtime`
801           and know that it only needs to add files if the mtime of the
802           directory and files are newer than the stored timestamp.
803
804           .. note::
805
806                 :meth:`get_mtime` function does not allow the caller to
807                 distinguish a timestamp of 0 from a non-existent timestamp. So
808                 don't store a timestamp of 0 unless you are comfortable with
809                 that.
810
811           :param mtime: A (time_t) timestamp
812           :returns: Nothing on success, raising an exception on failure.
813           :exception: :exc:`NotmuchError`:
814
815                         :attr:`STATUS`.XAPIAN_EXCEPTION
816                           A Xapian exception occurred, mtime not stored.
817                         :attr:`STATUS`.READ_ONLY_DATABASE
818                           Database was opened in read-only mode so directory
819                           mtime cannot be modified.
820                         :attr:`STATUS`.NOT_INITIALIZED
821                           The directory has not been initialized
822         """
823         self._assert_dir_is_initialized()
824         #TODO: make sure, we convert the mtime parameter to a 'c_long'
825         status = Directory._set_mtime(self._dir_p, mtime)
826
827         #return on success
828         if status == STATUS.SUCCESS:
829             return
830         #fail with Exception otherwise
831         raise NotmuchError(status)
832
833     def get_mtime(self):
834         """Gets the mtime value of this directory in the database
835
836         Retrieves a previously stored mtime for this directory.
837
838         :param mtime: A (time_t) timestamp
839         :returns: Nothing on success, raising an exception on failure.
840         :exception: :exc:`NotmuchError`:
841
842                         :attr:`STATUS`.NOT_INITIALIZED
843                           The directory has not been initialized
844         """
845         self._assert_dir_is_initialized()
846         return Directory._get_mtime(self._dir_p)
847
848     # Make mtime attribute a property of Directory()
849     mtime = property(get_mtime, set_mtime, doc="""Property that allows getting
850                      and setting of the Directory *mtime* (read-write)
851
852                      See :meth:`get_mtime` and :meth:`set_mtime` for usage and
853                      possible exceptions.""")
854
855     def get_child_files(self):
856         """Gets a Filenames iterator listing all the filenames of
857         messages in the database within the given directory.
858
859         The returned filenames will be the basename-entries only (not
860         complete paths.
861         """
862         self._assert_dir_is_initialized()
863         files_p = Directory._get_child_files(self._dir_p)
864         return Filenames(files_p, self)
865
866     def get_child_directories(self):
867         """Gets a :class:`Filenames` iterator listing all the filenames of
868         sub-directories in the database within the given directory
869
870         The returned filenames will be the basename-entries only (not
871         complete paths.
872         """
873         self._assert_dir_is_initialized()
874         files_p = Directory._get_child_directories(self._dir_p)
875         return Filenames(files_p, self)
876
877     @property
878     def path(self):
879         """Returns the absolute path of this Directory (read-only)"""
880         return self._path
881
882     def __repr__(self):
883         """Object representation"""
884         return "<notmuch Directory object '%s'>" % self._path
885
886     _destroy = nmlib.notmuch_directory_destroy
887     _destroy.argtypes = [NotmuchDirectoryP]
888     _destroy.argtypes = None
889
890     def __del__(self):
891         """Close and free the Directory"""
892         if self._dir_p is not None:
893             self._destroy(self._dir_p)
894
895
896 class Filenames(object):
897     """An iterator over File- or Directory names stored in the database"""
898
899     #notmuch_filenames_get
900     _get = nmlib.notmuch_filenames_get
901     _get.argtypes = [NotmuchFilenamesP]
902     _get.restype = c_char_p
903
904     def __init__(self, files_p, parent):
905         """
906         :param files_p: The pointer to an internal notmuch_filenames_t object.
907         :param parent: The object this Directory is derived from
908                        (usually a Directory()). We do not directly use
909                        this, but store a reference to it as long as
910                        this Directory object lives. This keeps the
911                        parent object alive.
912         """
913         self._files_p = files_p
914         self._parent = parent
915
916     def __iter__(self):
917         """ Make Filenames an iterator """
918         return self
919
920     _valid = nmlib.notmuch_filenames_valid
921     _valid.argtypes = [NotmuchFilenamesP]
922     _valid.restype = bool
923
924     _move_to_next = nmlib.notmuch_filenames_move_to_next
925     _move_to_next.argtypes = [NotmuchFilenamesP]
926     _move_to_next.restype = None
927
928     def next(self):
929         if self._files_p is None:
930             raise NotmuchError(STATUS.NOT_INITIALIZED)
931
932         if not self._valid(self._files_p):
933             self._files_p = None
934             raise StopIteration
935
936         file = Filenames._get(self._files_p)
937         self._move_to_next(self._files_p)
938         return file
939
940     def __len__(self):
941         """len(:class:`Filenames`) returns the number of contained files
942
943         .. note::
944
945             As this iterates over the files, we will not be able to
946             iterate over them again! So this will fail::
947
948                  #THIS FAILS
949                  files = Database().get_directory('').get_child_files()
950                  if len(files) > 0:  # this 'exhausts' msgs
951                      # next line raises
952                      # NotmuchError(:attr:`STATUS`.NOT_INITIALIZED)
953                      for file in files: print file
954         """
955         if self._files_p is None:
956             raise NotmuchError(STATUS.NOT_INITIALIZED)
957
958         i = 0
959         while self._valid(self._files_p):
960             self._move_to_next(self._files_p)
961             i += 1
962         self._files_p = None
963         return i
964
965     _destroy = nmlib.notmuch_filenames_destroy
966     _destroy.argtypes = [NotmuchFilenamesP]
967     _destroy.restype = None
968
969     def __del__(self):
970         """Close and free Filenames"""
971         if self._files_p is not None:
972             self._destroy(self._files_p)