]> git.notmuchmail.org Git - notmuch/blob - bindings/python/notmuch/database.py
python: move the exception classes into error.py
[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, byref, POINTER
23 from notmuch.globals import (
24     nmlib,
25     Enum,
26     _str,
27     NotmuchDatabaseP,
28     NotmuchDirectoryP,
29     NotmuchMessageP,
30     NotmuchTagsP,
31 )
32 from .errors import (
33     STATUS,
34     FileError,
35     NotmuchError,
36     NullPointerError,
37     NotInitializedError,
38     ReadOnlyDatabaseError,
39 )
40 from notmuch.message import Message
41 from notmuch.tag import Tags
42 from .query import Query
43 from .directory import Directory
44
45 class Database(object):
46     """The :class:`Database` is the highest-level object that notmuch
47     provides. It references a notmuch database, and can be opened in
48     read-only or read-write mode. A :class:`Query` can be derived from
49     or be applied to a specific database to find messages. Also adding
50     and removing messages to the database happens via this
51     object. Modifications to the database are not atmic by default (see
52     :meth:`begin_atomic`) and once a database has been modified, all
53     other database objects pointing to the same data-base will throw an
54     :exc:`XapianError` as the underlying database has been
55     modified. Close and reopen the database to continue working with it.
56
57     :class:`Database` objects implement the context manager protocol
58     so you can use the :keyword:`with` statement to ensure that the
59     database is properly closed.
60
61     .. note::
62
63         Any function in this class can and will throw an
64         :exc:`NotInitializedError` if the database was not intitialized
65         properly.
66
67     .. note::
68
69         Do remember that as soon as we tear down (e.g. via `del db`) this
70         object, all underlying derived objects such as queries, threads,
71         messages, tags etc will be freed by the underlying library as well.
72         Accessing these objects will lead to segfaults and other unexpected
73         behavior. See above for more details.
74     """
75     _std_db_path = None
76     """Class attribute to cache user's default database"""
77
78     MODE = Enum(['READ_ONLY', 'READ_WRITE'])
79     """Constants: Mode in which to open the database"""
80
81     """notmuch_database_get_directory"""
82     _get_directory = nmlib.notmuch_database_get_directory
83     _get_directory.argtypes = [NotmuchDatabaseP, c_char_p]
84     _get_directory.restype = NotmuchDirectoryP
85
86     """notmuch_database_get_path"""
87     _get_path = nmlib.notmuch_database_get_path
88     _get_path.argtypes = [NotmuchDatabaseP]
89     _get_path.restype = c_char_p
90
91     """notmuch_database_get_version"""
92     _get_version = nmlib.notmuch_database_get_version
93     _get_version.argtypes = [NotmuchDatabaseP]
94     _get_version.restype = c_uint
95
96     """notmuch_database_open"""
97     _open = nmlib.notmuch_database_open
98     _open.argtypes = [c_char_p, c_uint]
99     _open.restype = NotmuchDatabaseP
100
101     """notmuch_database_upgrade"""
102     _upgrade = nmlib.notmuch_database_upgrade
103     _upgrade.argtypes = [NotmuchDatabaseP, c_void_p, c_void_p]
104     _upgrade.restype = c_uint
105
106     """ notmuch_database_find_message"""
107     _find_message = nmlib.notmuch_database_find_message
108     _find_message.argtypes = [NotmuchDatabaseP, c_char_p,
109                               POINTER(NotmuchMessageP)]
110     _find_message.restype = c_uint
111
112     """notmuch_database_find_message_by_filename"""
113     _find_message_by_filename = nmlib.notmuch_database_find_message_by_filename
114     _find_message_by_filename.argtypes = [NotmuchDatabaseP, c_char_p,
115                                           POINTER(NotmuchMessageP)]
116     _find_message_by_filename.restype = c_uint
117
118     """notmuch_database_get_all_tags"""
119     _get_all_tags = nmlib.notmuch_database_get_all_tags
120     _get_all_tags.argtypes = [NotmuchDatabaseP]
121     _get_all_tags.restype = NotmuchTagsP
122
123     """notmuch_database_create"""
124     _create = nmlib.notmuch_database_create
125     _create.argtypes = [c_char_p]
126     _create.restype = NotmuchDatabaseP
127
128     def __init__(self, path = None, create = False,
129                  mode = MODE.READ_ONLY):
130         """If *path* is `None`, we will try to read a users notmuch
131         configuration and use his configured database. The location of the
132         configuration file can be specified through the environment variable
133         *NOTMUCH_CONFIG*, falling back to the default `~/.notmuch-config`.
134
135         If *create* is `True`, the database will always be created in
136         :attr:`MODE`.READ_WRITE mode. Default mode for opening is READ_ONLY.
137
138         :param path:   Directory to open/create the database in (see
139                        above for behavior if `None`)
140         :type path:    `str` or `None`
141         :param create: Pass `False` to open an existing, `True` to create a new
142                        database.
143         :type create:  bool
144         :param mode:   Mode to open a database in. Is always
145                        :attr:`MODE`.READ_WRITE when creating a new one.
146         :type mode:    :attr:`MODE`
147         :raises: :exc:`NotmuchError` or derived exception in case of
148             failure.
149         """
150         self._db = None
151         self.mode = mode
152         if path is None:
153             # no path specified. use a user's default database
154             if Database._std_db_path is None:
155                 #the following line throws a NotmuchError if it fails
156                 Database._std_db_path = self._get_user_default_db()
157             path = Database._std_db_path
158
159         if create == False:
160             self.open(path, mode)
161         else:
162             self.create(path)
163
164     def __del__(self):
165         self.close()
166
167     def _assert_db_is_initialized(self):
168         """Raises :exc:`NotInitializedError` if self._db is `None`"""
169         if not self._db:
170             raise NotInitializedError()
171
172     def create(self, path):
173         """Creates a new notmuch database
174
175         This function is used by __init__() and usually does not need
176         to be called directly. It wraps the underlying
177         *notmuch_database_create* function and creates a new notmuch
178         database at *path*. It will always return a database in :attr:`MODE`
179         .READ_WRITE mode as creating an empty database for
180         reading only does not make a great deal of sense.
181
182         :param path: A directory in which we should create the database.
183         :type path: str
184         :raises: :exc:`NotmuchError` in case of any failure
185                     (possibly after printing an error message on stderr).
186         """
187         if self._db is not None:
188             raise NotmuchError(message="Cannot create db, this Database() "
189                                        "already has an open one.")
190
191         res = Database._create(_str(path), Database.MODE.READ_WRITE)
192
193         if not res:
194             raise NotmuchError(
195                 message="Could not create the specified database")
196         self._db = res
197
198     def open(self, path, mode=0):
199         """Opens an existing database
200
201         This function is used by __init__() and usually does not need
202         to be called directly. It wraps the underlying
203         *notmuch_database_open* function.
204
205         :param status: Open the database in read-only or read-write mode
206         :type status:  :attr:`MODE`
207         :raises: Raises :exc:`NotmuchError` in case of any failure
208                     (possibly after printing an error message on stderr).
209         """
210         res = Database._open(_str(path), mode)
211
212         if not res:
213             raise NotmuchError(message="Could not open the specified database")
214         self._db = res
215
216     _close = nmlib.notmuch_database_close
217     _close.argtypes = [NotmuchDatabaseP]
218     _close.restype = None
219
220     def close(self):
221         """Close and free the notmuch database if needed"""
222         if self._db is not None:
223             self._close(self._db)
224             self._db = None
225
226     def __enter__(self):
227         '''
228         Implements the context manager protocol.
229         '''
230         return self
231
232     def __exit__(self, exc_type, exc_value, traceback):
233         '''
234         Implements the context manager protocol.
235         '''
236         self.close()
237
238     def get_path(self):
239         """Returns the file path of an open database"""
240         self._assert_db_is_initialized()
241         return Database._get_path(self._db).decode('utf-8')
242
243     def get_version(self):
244         """Returns the database format version
245
246         :returns: The database version as positive integer
247         """
248         self._assert_db_is_initialized()
249         return Database._get_version(self._db)
250
251     _needs_upgrade = nmlib.notmuch_database_needs_upgrade
252     _needs_upgrade.argtypes = [NotmuchDatabaseP]
253     _needs_upgrade.restype = bool
254
255     def needs_upgrade(self):
256         """Does this database need to be upgraded before writing to it?
257
258         If this function returns `True` then no functions that modify the
259         database (:meth:`add_message`,
260         :meth:`Message.add_tag`, :meth:`Directory.set_mtime`,
261         etc.) will work unless :meth:`upgrade` is called successfully first.
262
263         :returns: `True` or `False`
264         """
265         self._assert_db_is_initialized()
266         return self._needs_upgrade(self._db)
267
268     def upgrade(self):
269         """Upgrades the current database
270
271         After opening a database in read-write mode, the client should
272         check if an upgrade is needed (notmuch_database_needs_upgrade) and
273         if so, upgrade with this function before making any modifications.
274
275         NOT IMPLEMENTED: The optional progress_notify callback can be
276         used by the caller to provide progress indication to the
277         user. If non-NULL it will be called periodically with
278         'progress' as a floating-point value in the range of [0.0..1.0]
279         indicating the progress made so far in the upgrade process.
280
281         :TODO: catch exceptions, document return values and etc...
282         """
283         self._assert_db_is_initialized()
284         status = Database._upgrade(self._db, None, None)
285         #TODO: catch exceptions, document return values and etc
286         return status
287
288     _begin_atomic = nmlib.notmuch_database_begin_atomic
289     _begin_atomic.argtypes = [NotmuchDatabaseP]
290     _begin_atomic.restype = c_uint
291
292     def begin_atomic(self):
293         """Begin an atomic database operation
294
295         Any modifications performed between a successful
296         :meth:`begin_atomic` and a :meth:`end_atomic` will be applied to
297         the database atomically.  Note that, unlike a typical database
298         transaction, this only ensures atomicity, not durability;
299         neither begin nor end necessarily flush modifications to disk.
300
301         :returns: :attr:`STATUS`.SUCCESS or raises
302         :raises: :exc:`NotmuchError`: :attr:`STATUS`.XAPIAN_EXCEPTION
303                     Xapian exception occurred; atomic section not entered.
304
305         *Added in notmuch 0.9*"""
306         self._assert_db_is_initialized()
307         status = self._begin_atomic(self._db)
308         if status != STATUS.SUCCESS:
309             raise NotmuchError(status)
310         return status
311
312     _end_atomic = nmlib.notmuch_database_end_atomic
313     _end_atomic.argtypes = [NotmuchDatabaseP]
314     _end_atomic.restype = c_uint
315
316     def end_atomic(self):
317         """Indicate the end of an atomic database operation
318
319         See :meth:`begin_atomic` for details.
320
321         :returns: :attr:`STATUS`.SUCCESS or raises
322
323         :raises:
324             :exc:`NotmuchError`:
325                 :attr:`STATUS`.XAPIAN_EXCEPTION
326                     A Xapian exception occurred; atomic section not
327                     ended.
328                 :attr:`STATUS`.UNBALANCED_ATOMIC:
329                     end_atomic has been called more times than begin_atomic.
330
331         *Added in notmuch 0.9*"""
332         self._assert_db_is_initialized()
333         status = self._end_atomic(self._db)
334         if status != STATUS.SUCCESS:
335             raise NotmuchError(status)
336         return status
337
338     def get_directory(self, path):
339         """Returns a :class:`Directory` of path,
340         (creating it if it does not exist(?))
341
342         :param path: An unicode string containing the path relative to the path
343               of database (see :meth:`get_path`), or else should be an absolute
344               path with initial components that match the path of 'database'.
345         :returns: :class:`Directory` or raises an exception.
346         :raises: :exc:`FileError` if path is not relative database or absolute
347                  with initial components same as database.
348         :raises: :exc:`ReadOnlyDatabaseError` if the database has not been
349                  opened in read-write mode
350         """
351         self._assert_db_is_initialized()
352
353         # work around libnotmuch calling exit(3), see
354         # id:20120221002921.8534.57091@thinkbox.jade-hamburg.de
355         # TODO: remove once this issue is resolved
356         if self.mode != Database.MODE.READ_WRITE:
357             raise ReadOnlyDatabaseError('The database has to be opened in '
358                                         'read-write mode for get_directory')
359
360         # sanity checking if path is valid, and make path absolute
361         if path and path[0] == os.sep:
362             # we got an absolute path
363             if not path.startswith(self.get_path()):
364                 # but its initial components are not equal to the db path
365                 raise FileError('Database().get_directory() called '
366                                 'with a wrong absolute path')
367             abs_dirpath = path
368         else:
369             #we got a relative path, make it absolute
370             abs_dirpath = os.path.abspath(os.path.join(self.get_path(), path))
371
372         dir_p = Database._get_directory(self._db, _str(path))
373
374         # return the Directory, init it with the absolute path
375         return Directory(abs_dirpath, dir_p, self)
376
377     _add_message = nmlib.notmuch_database_add_message
378     _add_message.argtypes = [NotmuchDatabaseP, c_char_p,
379                              POINTER(NotmuchMessageP)]
380     _add_message.restype = c_uint
381
382     def add_message(self, filename, sync_maildir_flags=False):
383         """Adds a new message to the database
384
385         :param filename: should be a path relative to the path of the
386             open database (see :meth:`get_path`), or else should be an
387             absolute filename with initial components that match the
388             path of the database.
389
390             The file should be a single mail message (not a
391             multi-message mbox) that is expected to remain at its
392             current location, since the notmuch database will reference
393             the filename, and will not copy the entire contents of the
394             file.
395
396         :param sync_maildir_flags: If the message contains Maildir
397             flags, we will -depending on the notmuch configuration- sync
398             those tags to initial notmuch tags, if set to `True`. It is
399             `False` by default to remain consistent with the libnotmuch
400             API. You might want to look into the underlying method
401             :meth:`Message.maildir_flags_to_tags`.
402
403         :returns: On success, we return
404
405            1) a :class:`Message` object that can be used for things
406               such as adding tags to the just-added message.
407            2) one of the following :attr:`STATUS` values:
408
409               :attr:`STATUS`.SUCCESS
410                   Message successfully added to database.
411               :attr:`STATUS`.DUPLICATE_MESSAGE_ID
412                   Message has the same message ID as another message already
413                   in the database. The new filename was successfully added
414                   to the list of the filenames for the existing message.
415
416         :rtype:   2-tuple(:class:`Message`, :attr:`STATUS`)
417
418         :raises: Raises a :exc:`NotmuchError` with the following meaning.
419               If such an exception occurs, nothing was added to the database.
420
421               :attr:`STATUS`.FILE_ERROR
422                       An error occurred trying to open the file, (such as
423                       permission denied, or file not found, etc.).
424               :attr:`STATUS`.FILE_NOT_EMAIL
425                       The contents of filename don't look like an email
426                       message.
427               :attr:`STATUS`.READ_ONLY_DATABASE
428                       Database was opened in read-only mode so no message can
429                       be added.
430         """
431         self._assert_db_is_initialized()
432         msg_p = NotmuchMessageP()
433         status = self._add_message(self._db, _str(filename), byref(msg_p))
434
435         if not status in [STATUS.SUCCESS, STATUS.DUPLICATE_MESSAGE_ID]:
436             raise NotmuchError(status)
437
438         #construct Message() and return
439         msg = Message(msg_p, self)
440         #automatic sync initial tags from Maildir flags
441         if sync_maildir_flags:
442             msg.maildir_flags_to_tags()
443         return (msg, status)
444
445     _remove_message = nmlib.notmuch_database_remove_message
446     _remove_message.argtypes = [NotmuchDatabaseP, c_char_p]
447     _remove_message.restype = c_uint
448
449     def remove_message(self, filename):
450         """Removes a message (filename) from the given notmuch database
451
452         Note that only this particular filename association is removed from
453         the database. If the same message (as determined by the message ID)
454         is still available via other filenames, then the message will
455         persist in the database for those filenames. When the last filename
456         is removed for a particular message, the database content for that
457         message will be entirely removed.
458
459         :returns: A :attr:`STATUS` value with the following meaning:
460
461              :attr:`STATUS`.SUCCESS
462                The last filename was removed and the message was removed
463                from the database.
464              :attr:`STATUS`.DUPLICATE_MESSAGE_ID
465                This filename was removed but the message persists in the
466                database with at least one other filename.
467
468         :raises: Raises a :exc:`NotmuchError` with the following meaning.
469              If such an exception occurs, nothing was removed from the
470              database.
471
472              :attr:`STATUS`.READ_ONLY_DATABASE
473                Database was opened in read-only mode so no message can be
474                removed.
475         """
476         self._assert_db_is_initialized()
477         return self._remove_message(self._db, _str(filename))
478
479     def find_message(self, msgid):
480         """Returns a :class:`Message` as identified by its message ID
481
482         Wraps the underlying *notmuch_database_find_message* function.
483
484         :param msgid: The message ID
485         :type msgid: unicode or str
486         :returns: :class:`Message` or `None` if no message is found.
487         :raises:
488             :exc:`OutOfMemoryError`
489                   If an Out-of-memory occured while constructing the message.
490             :exc:`XapianError`
491                   In case of a Xapian Exception. These exceptions
492                   include "Database modified" situations, e.g. when the
493                   notmuch database has been modified by another program
494                   in the meantime. In this case, you should close and
495                   reopen the database and retry.
496             :exc:`NotInitializedError` if
497                     the database was not intitialized.
498         """
499         self._assert_db_is_initialized()
500         msg_p = NotmuchMessageP()
501         status = Database._find_message(self._db, _str(msgid), byref(msg_p))
502         if status != STATUS.SUCCESS:
503             raise NotmuchError(status)
504         return msg_p and Message(msg_p, self) or None
505
506     def find_message_by_filename(self, filename):
507         """Find a message with the given filename
508
509         :returns: If the database contains a message with the given
510             filename, then a class:`Message:` is returned.  This
511             function returns None if no message is found with the given
512             filename.
513
514         :raises: :exc:`OutOfMemoryError` if an Out-of-memory occured while
515                  constructing the message.
516         :raises: :exc:`XapianError` in case of a Xapian Exception.
517                  These exceptions include "Database modified"
518                  situations, e.g. when the notmuch database has been
519                  modified by another program in the meantime. In this
520                  case, you should close and reopen the database and
521                  retry.
522         :raises: :exc:`NotInitializedError` if the database was not
523                  intitialized.
524         :raises: :exc:`ReadOnlyDatabaseError` if the database has not been
525                  opened in read-write mode
526
527         *Added in notmuch 0.9*"""
528         self._assert_db_is_initialized()
529
530         # work around libnotmuch calling exit(3), see
531         # id:20120221002921.8534.57091@thinkbox.jade-hamburg.de
532         # TODO: remove once this issue is resolved
533         if self.mode != Database.MODE.READ_WRITE:
534             raise ReadOnlyDatabaseError('The database has to be opened in '
535                                         'read-write mode for get_directory')
536
537         msg_p = NotmuchMessageP()
538         status = Database._find_message_by_filename(self._db, _str(filename),
539                                                     byref(msg_p))
540         if status != STATUS.SUCCESS:
541             raise NotmuchError(status)
542         return msg_p and Message(msg_p, self) or None
543
544     def get_all_tags(self):
545         """Returns :class:`Tags` with a list of all tags found in the database
546
547         :returns: :class:`Tags`
548         :execption: :exc:`NotmuchError` with :attr:`STATUS`.NULL_POINTER
549                     on error
550         """
551         self._assert_db_is_initialized()
552         tags_p = Database._get_all_tags(self._db)
553         if tags_p == None:
554             raise NullPointerError()
555         return Tags(tags_p, self)
556
557     def create_query(self, querystring):
558         """Returns a :class:`Query` derived from this database
559
560         This is a shorthand method for doing::
561
562           # short version
563           # Automatically frees the Database() when 'q' is deleted
564
565           q  = Database(dbpath).create_query('from:"Biene Maja"')
566
567           # long version, which is functionally equivalent but will keep the
568           # Database in the 'db' variable around after we delete 'q':
569
570           db = Database(dbpath)
571           q  = Query(db,'from:"Biene Maja"')
572
573         This function is a python extension and not in the underlying C API.
574         """
575         return Query(self, querystring)
576
577     def __repr__(self):
578         return "'Notmuch DB " + self.get_path() + "'"
579
580     def _get_user_default_db(self):
581         """ Reads a user's notmuch config and returns his db location
582
583         Throws a NotmuchError if it cannot find it"""
584         try:
585             # python3.x
586             from configparser import SafeConfigParser
587         except ImportError:
588             # python2.x
589             from ConfigParser import SafeConfigParser
590
591         config = SafeConfigParser()
592         conf_f = os.getenv('NOTMUCH_CONFIG',
593                            os.path.expanduser('~/.notmuch-config'))
594         config.readfp(codecs.open(conf_f, 'r', 'utf-8'))
595         if not config.has_option('database', 'path'):
596             raise NotmuchError(message="No DB path specified"
597                                        " and no user default found")
598         return config.get('database', 'path')
599
600     @property
601     def db_p(self):
602         """Property returning a pointer to `notmuch_database_t` or `None`
603
604         This should normally not be needed by a user (and is not yet
605         guaranteed to remain stable in future versions).
606         """
607         return self._db