Database – The underlying notmuch database

class Database([path=None[, create=False[, mode=MODE.READ_ONLY]]])

The Database is the highest-level object that notmuch provides. It references a notmuch database, and can be opened in read-only or read-write mode. A Query can be derived from or be applied to a specific database to find messages. Also adding and removing messages to the database happens via this object. Modifications to the database are not atmic by default (see begin_atomic()) and once a database has been modified, all other database objects pointing to the same data-base will throw an XapianError as the underlying database has been modified. Close and reopen the database to continue working with it.

Database objects implement the context manager protocol so you can use the with statement to ensure that the database is properly closed. See close() for more information.

Note

Any function in this class can and will throw an NotInitializedError if the database was not intitialized properly.

If path is None, we will try to read a users notmuch configuration and use his configured database. The location of the configuration file can be specified through the environment variable NOTMUCH_CONFIG, falling back to the default ~/.notmuch-config.

If create is True, the database will always be created in MODE.READ_WRITE mode. Default mode for opening is READ_ONLY.

Parameters:
  • path (str or None) – Directory to open/create the database in (see above for behavior if None)
  • create (bool) – Pass False to open an existing, True to create a new database.
  • mode (MODE) – Mode to open a database in. Is always MODE.READ_WRITE when creating a new one.
Raises:

NotmuchError or derived exception in case of failure.

create(path)

Creates a new notmuch database

This function is used by __init__() and usually does not need to be called directly. It wraps the underlying notmuch_database_create function and creates a new notmuch database at path. It will always return a database in MODE .READ_WRITE mode as creating an empty database for reading only does not make a great deal of sense.

Parameters:path (str) – A directory in which we should create the database.
Raises:NotmuchError in case of any failure (possibly after printing an error message on stderr).
open(path, status=MODE.READ_ONLY)

Opens an existing database

This function is used by __init__() and usually does not need to be called directly. It wraps the underlying notmuch_database_open function.

Parameters:status (MODE) – Open the database in read-only or read-write mode
Raises:Raises NotmuchError in case of any failure (possibly after printing an error message on stderr).
close()

Closes the notmuch database.

Warning

This function closes the notmuch database. From that point on every method invoked on any object ever derived from the closed database may cease to function and raise a NotmuchError.

get_path()

Returns the file path of an open database

get_version()

Returns the database format version

Returns:The database version as positive integer
needs_upgrade()

Does this database need to be upgraded before writing to it?

If this function returns True then no functions that modify the database (index_file(), Message.add_tag(), Directory.set_mtime(), etc.) will work unless upgrade() is called successfully first.

Returns:True or False
upgrade()

Upgrades the current database

After opening a database in read-write mode, the client should check if an upgrade is needed (notmuch_database_needs_upgrade) and if so, upgrade with this function before making any modifications.

NOT IMPLEMENTED: The optional progress_notify callback can be used by the caller to provide progress indication to the user. If non-NULL it will be called periodically with ‘progress’ as a floating-point value in the range of [0.0..1.0] indicating the progress made so far in the upgrade process.

TODO:catch exceptions, document return values and etc…
begin_atomic()

Begin an atomic database operation

Any modifications performed between a successful begin_atomic() and a end_atomic() will be applied to the database atomically. Note that, unlike a typical database transaction, this only ensures atomicity, not durability; neither begin nor end necessarily flush modifications to disk.

Returns:STATUS.SUCCESS or raises
Raises:NotmuchError: STATUS.XAPIAN_EXCEPTION Xapian exception occurred; atomic section not entered.

Added in notmuch 0.9

end_atomic()

Indicate the end of an atomic database operation

See begin_atomic() for details.

Returns:

STATUS.SUCCESS or raises

Raises:
NotmuchError:
STATUS.XAPIAN_EXCEPTION

A Xapian exception occurred; atomic section not ended.

STATUS.UNBALANCED_ATOMIC:

end_atomic has been called more times than begin_atomic.

Added in notmuch 0.9

get_directory(path)

Returns a Directory of path,

Parameters:path – An unicode string containing the path relative to the path of database (see get_path()), or else should be an absolute path with initial components that match the path of ‘database’.
Returns:Directory or raises an exception.
Raises:FileError if path is not relative database or absolute with initial components same as database.
index_file(filename, sync_maildir_flags=False, decrypt_policy=None)

Adds a new message to the database

Parameters:
  • filename

    should be a path relative to the path of the open database (see get_path()), or else should be an absolute filename with initial components that match the path of the database.

    The file should be a single mail message (not a multi-message mbox) that is expected to remain at its current location, since the notmuch database will reference the filename, and will not copy the entire contents of the file.

  • sync_maildir_flags – If the message contains Maildir flags, we will -depending on the notmuch configuration- sync those tags to initial notmuch tags, if set to True. It is False by default to remain consistent with the libnotmuch API. You might want to look into the underlying method Message.maildir_flags_to_tags().
  • decrypt_policy – If the message contains any encrypted parts, and decrypt_policy is set to DECRYPTION_POLICY.TRUE, notmuch will try to decrypt the message and index the cleartext, stashing any discovered session keys. If it is set to DECRYPTION_POLICY.FALSE, it will never try to decrypt during indexing. If it is set to DECRYPTION_POLICY.AUTO, then it will try to use any stashed session keys it knows about, but will not try to access the user’s secret keys. DECRYPTION_POLICY.NOSTASH behaves the same as DECRYPTION_POLICY.TRUE except that no session keys are stashed in the database. If decrypt_policy is set to None (the default), then the database itself will decide whether to decrypt, based on the index.decrypt configuration setting (see notmuch-config(1)).
Returns:

On success, we return

  1. a Message object that can be used for things such as adding tags to the just-added message.

  2. one of the following STATUS values:

    STATUS.SUCCESS

    Message successfully added to database.

    STATUS.DUPLICATE_MESSAGE_ID

    Message has the same message ID as another message already in the database. The new filename was successfully added to the list of the filenames for the existing message.

Return type:

2-tuple(Message, STATUS)

Raises:

Raises a NotmuchError with the following meaning. If such an exception occurs, nothing was added to the database.

STATUS.FILE_ERROR

An error occurred trying to open the file, (such as permission denied, or file not found, etc.).

STATUS.FILE_NOT_EMAIL

The contents of filename don’t look like an email message.

STATUS.READ_ONLY_DATABASE

Database was opened in read-only mode so no message can be added.

remove_message(filename)

Removes a message (filename) from the given notmuch database

Note that only this particular filename association is removed from the database. If the same message (as determined by the message ID) is still available via other filenames, then the message will persist in the database for those filenames. When the last filename is removed for a particular message, the database content for that message will be entirely removed.

Returns:

A STATUS value with the following meaning:

STATUS.SUCCESS

The last filename was removed and the message was removed from the database.

STATUS.DUPLICATE_MESSAGE_ID

This filename was removed but the message persists in the database with at least one other filename.

Raises:

Raises a NotmuchError with the following meaning. If such an exception occurs, nothing was removed from the database.

STATUS.READ_ONLY_DATABASE

Database was opened in read-only mode so no message can be removed.

find_message(msgid)

Returns a Message as identified by its message ID

Wraps the underlying notmuch_database_find_message function.

Parameters:

msgid (unicode or str) – The message ID

Returns:

Message or None if no message is found.

Raises:
OutOfMemoryError

If an Out-of-memory occurred while constructing the message.

XapianError

In case of a Xapian Exception. These exceptions include “Database modified” situations, e.g. when the notmuch database has been modified by another program in the meantime. In this case, you should close and reopen the database and retry.

NotInitializedError if

the database was not intitialized.

find_message_by_filename(filename)

Find a message with the given filename

Returns:If the database contains a message with the given filename, then a class:Message: is returned. This function returns None if no message is found with the given filename.
Raises:OutOfMemoryError if an Out-of-memory occurred while constructing the message.
Raises:XapianError in case of a Xapian Exception. These exceptions include “Database modified” situations, e.g. when the notmuch database has been modified by another program in the meantime. In this case, you should close and reopen the database and retry.
Raises:NotInitializedError if the database was not intitialized.

Added in notmuch 0.9

get_all_tags()

Returns Tags with a list of all tags found in the database

Returns:Tags
Execption:NotmuchError with STATUS.NULL_POINTER on error
create_query(querystring)

Returns a Query derived from this database

This is a shorthand method for doing:

# short version
# Automatically frees the Database() when 'q' is deleted

q  = Database(dbpath).create_query('from:"Biene Maja"')

# long version, which is functionally equivalent but will keep the
# Database in the 'db' variable around after we delete 'q':

db = Database(dbpath)
q  = Query(db,'from:"Biene Maja"')

This function is a python extension and not in the underlying C API.

get_config(key)

Return the value of the given config key.

Note that only config values that are stored in the database are searched and returned. The config file is not read.

Parameters:key (str) – the config key under which a value should be looked up, it should probably be in the form “section.key”
Returns:the config value or the empty string if no value is present for that key
Return type:str
Raises:NotmuchError in case of failure.
get_configs(prefix='')

Return a generator of key, value pairs where the start of key matches the given prefix

Note that only config values that are stored in the database are searched and returned. The config file is not read. If no prefix is given all config values are returned.

This could be used to get all named queries into a dict for example:

queries = {k[6:]: v for k, v in db.get_configs('query.')}
Parameters:prefix (str) – a string by which the keys should be selected
Yields:all key-value pairs where prefix matches the beginning of the key
Ytype:pairs of str
Raises:NotmuchError in case of failure.
set_config(key, value)

Set a config value in the notmuch database.

If an empty string is provided as value the key is unset!

Parameters:
  • key (str) – the key to set
  • value (str) – the value to store under key
Returns:

None

Raises:

NotmuchError in case of failure.

MODE

Defines constants that are used as the mode in which to open a database.

MODE.READ_ONLY
Open the database in read-only mode
MODE.READ_WRITE
Open the database in read-write mode