X-Git-Url: https://git.notmuchmail.org/git?a=blobdiff_plain;f=bindings%2Fpython-cffi%2Fnotmuch2%2F_database.py;h=d7485b4d983d8f55efd92b8a8581dac86e415c3a;hb=HEAD;hp=7ef4fe170e23bfeba22f340d12806cd8c62b8785;hpb=34c5233894f5143baaf5d4fc94df68fc186409d6;p=notmuch diff --git a/bindings/python-cffi/notmuch2/_database.py b/bindings/python-cffi/notmuch2/_database.py index 7ef4fe17..d7485b4d 100644 --- a/bindings/python-cffi/notmuch2/_database.py +++ b/bindings/python-cffi/notmuch2/_database.py @@ -7,6 +7,7 @@ import pathlib import weakref import notmuch2._base as base +import notmuch2._config as config import notmuch2._capi as capi import notmuch2._errors as errors import notmuch2._message as message @@ -30,6 +31,9 @@ class Mode(enum.Enum): READ_ONLY = capi.lib.NOTMUCH_DATABASE_MODE_READ_ONLY READ_WRITE = capi.lib.NOTMUCH_DATABASE_MODE_READ_WRITE +class ConfigFile(enum.Enum): + EMPTY = b'' + SEARCH = capi.ffi.NULL class QuerySortOrder(enum.Enum): OLDEST_FIRST = capi.lib.NOTMUCH_SORT_OLDEST_FIRST @@ -70,6 +74,9 @@ class Database(base.NotmuchObject): :cvar EXCLUDE: Which messages to exclude from queries, ``TRUE``, ``FLAG``, ``FALSE`` or ``ALL``. See the query documentation for details. + :cvar CONFIG: Control loading of config file. Enumeration of + ``EMPTY`` (don't load a config file), and ``SEARCH`` (search as + in :ref:`config_search`) :cvar AddedMessage: A namedtuple ``(msg, dup)`` used by :meth:`add` as return value. :cvar STR_MODE_MAP: A map mapping strings to :attr:`MODE` items. @@ -80,9 +87,8 @@ class Database(base.NotmuchObject): still open. :param path: The directory of where the database is stored. If - ``None`` the location will be read from the user's - configuration file, respecting the ``NOTMUCH_CONFIG`` - environment variable if set. + ``None`` the location will be searched according to + :ref:`database` :type path: str, bytes, os.PathLike or pathlib.Path :param mode: The mode to open the database in. One of :attr:`MODE.READ_ONLY` OR :attr:`MODE.READ_WRITE`. For @@ -90,6 +96,8 @@ class Database(base.NotmuchObject): :attr:`MODE.READ_ONLY` and ``rw`` for :attr:`MODE.READ_WRITE`. :type mode: :attr:`MODE` or str. + :param config: Where to load the configuration from, if any. + :type config: :attr:`CONFIG.EMPTY`, :attr:`CONFIG.SEARCH`, str, bytes, os.PathLike, pathlib.Path :raises KeyError: if an unknown mode string is used. :raises OSError: or subclasses if the configuration file can not be opened. @@ -101,6 +109,7 @@ class Database(base.NotmuchObject): MODE = Mode SORT = QuerySortOrder EXCLUDE = QueryExclude + CONFIG = ConfigFile AddedMessage = collections.namedtuple('AddedMessage', ['msg', 'dup']) _db_p = base.MemoryPointer() STR_MODE_MAP = { @@ -108,18 +117,40 @@ class Database(base.NotmuchObject): 'rw': MODE.READ_WRITE, } - def __init__(self, path=None, mode=MODE.READ_ONLY): + @staticmethod + def _cfg_path_encode(path): + if isinstance(path,ConfigFile): + path = path.value + elif path is None: + path = capi.ffi.NULL + elif not hasattr(os, 'PathLike') and isinstance(path, pathlib.Path): + path = bytes(path) + else: + path = os.fsencode(path) + return path + + @staticmethod + def _db_path_encode(path): + if path is None: + path = capi.ffi.NULL + elif not hasattr(os, 'PathLike') and isinstance(path, pathlib.Path): + path = bytes(path) + else: + path = os.fsencode(path) + return path + + def __init__(self, path=None, mode=MODE.READ_ONLY, config=CONFIG.SEARCH): if isinstance(mode, str): mode = self.STR_MODE_MAP[mode] self.mode = mode - if path is None: - path = self.default_path() - if not hasattr(os, 'PathLike') and isinstance(path, pathlib.Path): - path = bytes(path) + db_pp = capi.ffi.new('notmuch_database_t **') cmsg = capi.ffi.new('char**') - ret = capi.lib.notmuch_database_open_verbose(os.fsencode(path), - mode.value, db_pp, cmsg) + ret = capi.lib.notmuch_database_open_with_config(self._db_path_encode(path), + mode.value, + self._cfg_path_encode(config), + capi.ffi.NULL, + db_pp, cmsg) if cmsg[0]: msg = capi.ffi.string(cmsg[0]).decode(errors='replace') capi.lib.free(cmsg[0]) @@ -131,18 +162,20 @@ class Database(base.NotmuchObject): self.closed = False @classmethod - def create(cls, path=None): + def create(cls, path=None, config=ConfigFile.EMPTY): """Create and open database in READ_WRITE mode. This is creates a new notmuch database and returns an opened instance in :attr:`MODE.READ_WRITE` mode. - :param path: The directory of where the database is stored. If - ``None`` the location will be read from the user's - configuration file, respecting the ``NOTMUCH_CONFIG`` - environment variable if set. + :param path: The directory of where the database is stored. + If ``None`` the location will be read searched by the + notmuch library (see notmuch(3)::notmuch_open_with_config). :type path: str, bytes or os.PathLike + :param config: The pathname of the notmuch configuration file. + :type config: :attr:`CONFIG.EMPTY`, :attr:`CONFIG.SEARCH`, str, bytes, os.PathLike, pathlib.Path + :raises OSError: or subclasses if the configuration file can not be opened. :raises configparser.Error: or subclasses if the configuration @@ -153,14 +186,13 @@ class Database(base.NotmuchObject): :returns: The newly created instance. """ - if path is None: - path = cls.default_path() - if not hasattr(os, 'PathLike') and isinstance(path, pathlib.Path): - path = bytes(path) + db_pp = capi.ffi.new('notmuch_database_t **') cmsg = capi.ffi.new('char**') - ret = capi.lib.notmuch_database_create_verbose(os.fsencode(path), - db_pp, cmsg) + ret = capi.lib.notmuch_database_create_with_config(cls._db_path_encode(path), + cls._cfg_path_encode(config), + capi.ffi.NULL, + db_pp, cmsg) if cmsg[0]: msg = capi.ffi.string(cmsg[0]).decode(errors='replace') capi.lib.free(cmsg[0]) @@ -175,7 +207,7 @@ class Database(base.NotmuchObject): ret = capi.lib.notmuch_database_destroy(db_pp[0]) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) - return cls(path, cls.MODE.READ_WRITE) + return cls(path, cls.MODE.READ_WRITE, config=config) @staticmethod def default_path(cfg_path=None): @@ -186,8 +218,8 @@ class Database(base.NotmuchObject): :param cfg_path: The pathname of the notmuch configuration file. If not specified tries to use the pathname provided in the - :env:`NOTMUCH_CONFIG` environment variable and falls back - to :file:`~/.notmuch-config. + :envvar:`NOTMUCH_CONFIG` environment variable and falls back + to :file:`~/.notmuch-config`. :type cfg_path: str, bytes, os.PathLike or pathlib.Path. :returns: The path of the database, which does not necessarily @@ -197,8 +229,11 @@ class Database(base.NotmuchObject): be opened. :raises configparser.Error: or subclasses if the configuration file can not be parsed. - :raises NotmuchError if the config file does not have the + :raises NotmuchError: if the config file does not have the database.path setting. + + .. deprecated:: 0.35 + Use the ``config`` parameter to :meth:`__init__` or :meth:`__create__` instead. """ if not cfg_path: cfg_path = _config_pathname() @@ -262,7 +297,7 @@ class Database(base.NotmuchObject): This is returned as a :class:`pathlib.Path` instance. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ try: return self._cache_path @@ -277,7 +312,7 @@ class Database(base.NotmuchObject): This is a positive integer. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ try: return self._cache_version @@ -296,7 +331,7 @@ class Database(base.NotmuchObject): A read-only database will never be upgradable. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ ret = capi.lib.notmuch_database_needs_upgrade(self._db_p) return bool(ret) @@ -320,7 +355,7 @@ class Database(base.NotmuchObject): not imply durability, it only ensures the changes are performed atomically. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ ctx = AtomicContext(self, '_db_p') return ctx @@ -330,7 +365,7 @@ class Database(base.NotmuchObject): Returned as a ``(revision, uuid)`` namedtuple. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ raw_uuid = capi.ffi.new('char**') rev = capi.lib.notmuch_database_get_revision(self._db_p, raw_uuid) @@ -387,7 +422,7 @@ class Database(base.NotmuchObject): READ_ONLY mode. :raises UpgradeRequiredError: The database must be upgraded first. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ if not hasattr(os, 'PathLike') and isinstance(filename, pathlib.Path): filename = bytes(filename) @@ -421,12 +456,12 @@ class Database(base.NotmuchObject): of it as ``dup = db.remove_message(name); if dup: ...``. :rtype: bool - :raises XapianError: A Xapian exception ocurred. + :raises XapianError: A Xapian exception occurred. :raises ReadOnlyDatabaseError: The database is opened in READ_ONLY mode. :raises UpgradeRequiredError: The database must be upgraded first. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ if not hasattr(os, 'PathLike') and isinstance(filename, pathlib.Path): filename = bytes(filename) @@ -457,8 +492,8 @@ class Database(base.NotmuchObject): :raises LookupError: If no message was found. :raises OutOfMemoryError: When there is no memory to allocate the message instance. - :raises XapianError: A Xapian exception ocurred. - :raises ObjectDestroyedError: if used after destoryed. + :raises XapianError: A Xapian exception occurred. + :raises ObjectDestroyedError: if used after destroyed. """ msg_pp = capi.ffi.new('notmuch_message_t **') ret = capi.lib.notmuch_database_find_message(self._db_p, @@ -488,8 +523,8 @@ class Database(base.NotmuchObject): a subclass of :exc:`KeyError`. :raises OutOfMemoryError: When there is no memory to allocate the message instance. - :raises XapianError: A Xapian exception ocurred. - :raises ObjectDestroyedError: if used after destoryed. + :raises XapianError: A Xapian exception occurred. + :raises ObjectDestroyedError: if used after destroyed. """ if not hasattr(os, 'PathLike') and isinstance(filename, pathlib.Path): filename = bytes(filename) @@ -522,7 +557,7 @@ class Database(base.NotmuchObject): :rtype: ImmutableTagSet - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ try: ref = self._cached_tagset @@ -536,6 +571,28 @@ class Database(base.NotmuchObject): self._cached_tagset = weakref.ref(tagset) return tagset + @property + def config(self): + """Return a mutable mapping with the settings stored in this database. + + This returns an mutable dict-like object implementing the + collections.abc.MutableMapping Abstract Base Class. + + :rtype: Config + + :raises ObjectDestroyedError: if used after destroyed. + """ + try: + ref = self._cached_config + except AttributeError: + config_mapping = None + else: + config_mapping = ref() + if config_mapping is None: + config_mapping = config.ConfigMapping(self, '_db_p') + self._cached_config = weakref.ref(config_mapping) + return config_mapping + def _create_query(self, query, *, omit_excluded=EXCLUDE.TRUE, sort=SORT.UNSORTED, # Check this default @@ -555,7 +612,7 @@ class Database(base.NotmuchObject): if exclude_tags is not None: for tag in exclude_tags: if isinstance(tag, str): - tag = str.encode('utf-8') + tag = tag.encode('utf-8') capi.lib.notmuch_query_add_tag_exclude(query_p, tag) return querymod.Query(self, query_p) @@ -570,7 +627,7 @@ class Database(base.NotmuchObject): :raises OutOfMemoryError: if no memory is available to allocate the query. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ query = self._create_query(query, omit_excluded=omit_excluded, @@ -587,7 +644,7 @@ class Database(base.NotmuchObject): :returns: An iterator over the messages found. :rtype: MessageIter - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ query = self._create_query(query, omit_excluded=omit_excluded, @@ -635,12 +692,13 @@ class AtomicContext: section is not active. When it is raised at exit time the atomic section is still active and you may need to try using :meth:`force_end`. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ def __init__(self, db, ptr_name): self._db = db self._ptr = lambda: getattr(db, ptr_name) + self._exit_fn = lambda: None def __del__(self): self._destroy() @@ -656,18 +714,22 @@ class AtomicContext: ret = capi.lib.notmuch_database_begin_atomic(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) + self._exit_fn = self._end_atomic return self - def __exit__(self, exc_type, exc_value, traceback): + def _end_atomic(self): ret = capi.lib.notmuch_database_end_atomic(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) + def __exit__(self, exc_type, exc_value, traceback): + self._exit_fn() + def force_end(self): """Force ending the atomic section. This can only be called once __exit__ has been called. It - will attept to close the atomic section (again). This is + will attempt to close the atomic section (again). This is useful if the original exit raised an exception and the atomic section is still open. But things are pretty ugly by now. @@ -675,12 +737,21 @@ class AtomicContext: not ended. :raises UnbalancedAtomicError: If the database was currently not in an atomic section. - :raises ObjectDestroyedError: if used after destoryed. + :raises ObjectDestroyedError: if used after destroyed. """ ret = capi.lib.notmuch_database_end_atomic(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) + def abort(self): + """Abort the transaction. + + Aborting a transaction will not commit any of the changes, but + will also implicitly close the database. + """ + self._exit_fn = lambda: None + self._db.close() + @functools.total_ordering class DbRevision: