
    g2h                       d Z ddlmZ ddlmZ ddlZddlZddlZddlZddlZej                  dk(  Z
e
rddlZ	 ddlZddlZ	 ddlmZ g dZeg dz  Z eed	e      Z eed
e      Z edd      Z edd      Z e       j3                         Z ej6                         ZdZdZdZ ej@                         sddl!Z!erejD                  ndgddgdgg g dZ#dejD                  d   v Z$e$reez  Z e!jJ                         Z&e&jO                  e       e&jQ                  edde#d   e#d   e#d   e#d   e#d         Z)e&jU                  d      d         Z+ G d! d"e,      Z- G d# d$e-      Z. G d% d&e-      Z/ G d' d(e-      Z0 G d) d*e-      Z1 G d+ d,e-      Z2 G d- d.e-      Z3 G d/ d0e-      Z4 G d1 d2e-      Z5 G d3 d4e-      Z6 G d5 d6e-      Z7 G d7 d8e-      Z8 G d9 d:e-      Z9 G d; d<e-      Z: G d= d>e-      Z; G d? d@e-      Z< G dA dBe-      Z= G dC dDe-      Z> G dE dFe-      Z? G dG dHe-      Z@ G dI dJe-      ZA G dK dLe-      ZB G dM dNe-      ZC G dO dPe-      ZD G dQ dRe-      ZE G dS dTe-      ZF ej@                         s[i ZG eH eI       j                               D ]:  ZK ej                  eK      s eMeKe-      s eKe-us%eKeG ee)eKj                        <   < [KdU ZO G dV dWeP      ZQ eQ       ZRdX ZSdY ZTdZ ZUd[ ZVded\ZW G d] d^eP      ZX G d_ d`eP      ZYeXZZ G da dbeP      Z[ G dc ddeP      Z\y# e$ r ddlZY w xY w# e$ r dZY w xY w)fzh
CPython/CFFI wrapper for OpenLDAP's "Lightning" MDB database.

Please see https://lmdb.readthedocs.io/
    )absolute_import)with_statementNwin32)_config)CursorEnvironmentTransaction	_Databaseenable_drop_gilversion)BadDbiErrorBadRslotErrorBadTxnErrorBadValsizeErrorCorruptedErrorCursorFullErrorDbsFullError	DiskErrorErrorIncompatibleErrorInvalidErrorInvalidParameterErrorKeyExistsError	LockErrorMapFullErrorMapResizedErrorMemoryErrorNotFoundErrorPageFullErrorPageNotFoundError
PanicErrorReadersFullErrorReadonlyErrorTlsFullErrorTxnFullErrorVersionMismatchErrorunicodebytes0755   0111az  
    typedef int mode_t;
    typedef ... MDB_env;
    typedef struct MDB_txn MDB_txn;
    typedef struct MDB_cursor MDB_cursor;
    typedef unsigned int MDB_dbi;
    enum MDB_cursor_op {
        MDB_FIRST,
        MDB_FIRST_DUP,
        MDB_GET_BOTH,
        MDB_GET_BOTH_RANGE,
        MDB_GET_CURRENT,
        MDB_GET_MULTIPLE,
        MDB_LAST,
        MDB_LAST_DUP,
        MDB_NEXT,
        MDB_NEXT_DUP,
        MDB_NEXT_MULTIPLE,
        MDB_NEXT_NODUP,
        MDB_PREV,
        MDB_PREV_DUP,
        MDB_PREV_NODUP,
        MDB_SET,
        MDB_SET_KEY,
        MDB_SET_RANGE,
        ...
    };
    typedef enum MDB_cursor_op MDB_cursor_op;

    struct MDB_val {
        size_t mv_size;
        void *mv_data;
        ...;
    };
    typedef struct MDB_val MDB_val;

    struct MDB_stat {
        unsigned int ms_psize;
        unsigned int ms_depth;
        size_t ms_branch_pages;
        size_t ms_leaf_pages;
        size_t ms_overflow_pages;
        size_t ms_entries;
        ...;
    };
    typedef struct MDB_stat MDB_stat;

    struct MDB_envinfo {
        void *me_mapaddr;
        size_t me_mapsize;
        size_t me_last_pgno;
        size_t me_last_txnid;
        unsigned int me_maxreaders;
        unsigned int me_numreaders;
        ...;
    };
    typedef struct MDB_envinfo MDB_envinfo;

    typedef int (*MDB_cmp_func)(const MDB_val *a, const MDB_val *b);
    typedef void (*MDB_rel_func)(MDB_val *item, void *oldptr, void *newptr,
                   void *relctx);

    char *mdb_strerror(int err);
    int mdb_env_create(MDB_env **env);
    int mdb_env_open(MDB_env *env, const char *path, unsigned int flags,
                     mode_t mode);
    int mdb_env_copy2(MDB_env *env, const char *path, int flags);
    int mdb_env_copyfd2(MDB_env *env, int fd, int flags);
    int mdb_env_stat(MDB_env *env, MDB_stat *stat);
    int mdb_env_info(MDB_env *env, MDB_envinfo *stat);
    int mdb_env_get_maxkeysize(MDB_env *env);
    int mdb_env_sync(MDB_env *env, int force);
    void mdb_env_close(MDB_env *env);
    int mdb_env_set_flags(MDB_env *env, unsigned int flags, int onoff);
    int mdb_env_get_flags(MDB_env *env, unsigned int *flags);
    int mdb_env_get_path(MDB_env *env, const char **path);
    int mdb_env_set_mapsize(MDB_env *env, size_t size);
    int mdb_env_set_maxreaders(MDB_env *env, unsigned int readers);
    int mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers);
    int mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs);
    int mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags,
                      MDB_txn **txn);
    int mdb_txn_commit(MDB_txn *txn);
    void mdb_txn_reset(MDB_txn *txn);
    int mdb_txn_renew(MDB_txn *txn);
    void mdb_txn_abort(MDB_txn *txn);
    size_t mdb_txn_id(MDB_txn *txn);
    int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags,
                     MDB_dbi *dbi);
    int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *stat);
    int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del_);
    int mdb_get(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
    int mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **cursor);
    void mdb_cursor_close(MDB_cursor *cursor);
    int mdb_cursor_del(MDB_cursor *cursor, unsigned int flags);
    int mdb_cursor_count(MDB_cursor *cursor, size_t *countp);
    int mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val*data, int op);

    typedef int (MDB_msg_func)(const char *msg, void *ctx);
    int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx);
    int mdb_reader_check(MDB_env *env, int *dead);
    int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags);

    #define MDB_VERSION_MAJOR ...
    #define MDB_VERSION_MINOR ...
    #define MDB_VERSION_PATCH ...

    #define EACCES ...
    #define EAGAIN ...
    #define EINVAL ...
    #define ENOMEM ...
    #define ENOSPC ...

    #define MDB_BAD_RSLOT ...
    #define MDB_BAD_DBI ...
    #define MDB_BAD_TXN ...
    #define MDB_BAD_VALSIZE ...
    #define MDB_CORRUPTED ...
    #define MDB_CURSOR_FULL ...
    #define MDB_DBS_FULL ...
    #define MDB_INCOMPATIBLE ...
    #define MDB_INVALID ...
    #define MDB_KEYEXIST ...
    #define MDB_MAP_FULL ...
    #define MDB_MAP_RESIZED ...
    #define MDB_NOTFOUND ...
    #define MDB_PAGE_FULL ...
    #define MDB_PAGE_NOTFOUND ...
    #define MDB_PANIC ...
    #define MDB_READERS_FULL ...
    #define MDB_TLS_FULL ...
    #define MDB_TXN_FULL ...
    #define MDB_VERSION_MISMATCH ...

    #define MDB_APPEND ...
    #define MDB_APPENDDUP ...
    #define MDB_CP_COMPACT ...
    #define MDB_CREATE ...
    #define MDB_DUPFIXED ...
    #define MDB_DUPSORT ...
    #define MDB_INTEGERDUP ...
    #define MDB_INTEGERKEY ...
    #define MDB_MAPASYNC ...
    #define MDB_NODUPDATA ...
    #define MDB_NOLOCK ...
    #define MDB_NOMEMINIT ...
    #define MDB_NOMETASYNC ...
    #define MDB_NOOVERWRITE ...
    #define MDB_NORDAHEAD ...
    #define MDB_NOSUBDIR ...
    #define MDB_NOSYNC ...
    #define MDB_NOTLS ...
    #define MDB_RDONLY ...
    #define MDB_REVERSEKEY ...
    #define MDB_WRITEMAP ...

    // Helpers below inline MDB_vals. Avoids key alloc/dup on CPython, where
    // CFFI will use PyString_AS_STRING when passed as an argument.
    static int pymdb_del(MDB_txn *txn, MDB_dbi dbi,
                         char *key_s, size_t keylen,
                         char *val_s, size_t vallen);
    static int pymdb_put(MDB_txn *txn, MDB_dbi dbi,
                         char *key_s, size_t keylen,
                         char *val_s, size_t vallen,
                         unsigned int flags);
    static int pymdb_get(MDB_txn *txn, MDB_dbi dbi,
                         char *key_s, size_t keylen,
                         MDB_val *val_out);
    static int pymdb_cursor_get(MDB_cursor *cursor,
                                char *key_s, size_t key_len,
                                char *data_s, size_t data_len,
                                MDB_val *key, MDB_val *data, int op);
    static int pymdb_cursor_put(MDB_cursor *cursor,
                                char *key_s, size_t keylen,
                                char *val_s, size_t vallen, int flags);

    // Prefaults a range
    static void preload(int rc, void *x, size_t size);

z
    int mdb_env_copy3(MDB_env *env, const char *path, unsigned int flags, MDB_txn *txn);
    int mdb_env_copyfd3(MDB_env *env, int fd, unsigned int flags, MDB_txn *txn);
a  
    #include <sys/stat.h>
    #include "lmdb.h"
    #include "preload.h"

    // Helpers below inline MDB_vals. Avoids key alloc/dup on CPython, where
    // CFFI will use PyString_AS_STRING when passed as an argument.
    static int pymdb_get(MDB_txn *txn, MDB_dbi dbi, char *key_s, size_t keylen,
                         MDB_val *val_out)
    {
        MDB_val key = {keylen, key_s};
        int rc = mdb_get(txn, dbi, &key, val_out);
        return rc;
    }

    static int pymdb_put(MDB_txn *txn, MDB_dbi dbi, char *key_s, size_t keylen,
                         char *val_s, size_t vallen, unsigned int flags)
    {
        MDB_val key = {keylen, key_s};
        MDB_val val = {vallen, val_s};
        return mdb_put(txn, dbi, &key, &val, flags);
    }

    static int pymdb_del(MDB_txn *txn, MDB_dbi dbi, char *key_s, size_t keylen,
                         char *val_s, size_t vallen)
    {
        MDB_val key = {keylen, key_s};
        MDB_val val = {vallen, val_s};
        MDB_val *valptr;
        if(vallen == 0) {
            valptr = NULL;
        } else {
            valptr = &val;
        }
        return mdb_del(txn, dbi, &key, valptr);
    }

    static int pymdb_cursor_get(MDB_cursor *cursor,
                                char *key_s, size_t key_len,
                                char *data_s, size_t data_len,
                                MDB_val *key, MDB_val *data, int op)
    {
        MDB_val tmp_key = {key_len, key_s};
        MDB_val tmp_data = {data_len, data_s};
        int rc = mdb_cursor_get(cursor, &tmp_key, &tmp_data, op);
        if(! rc) {
            *key = tmp_key;
            *data = tmp_data;
        }
        return rc;
    }

    static int pymdb_cursor_put(MDB_cursor *cursor, char *key_s, size_t keylen,
                                char *val_s, size_t vallen, int flags)
    {
        MDB_val tmpkey = {keylen, key_s};
        MDB_val tmpval = {vallen, val_s};
        return mdb_cursor_put(cursor, &tmpkey, &tmpval, flags);
    }

z-wz	lib/mdb.cz
lib/midl.clib)extra_compile_argsextra_sourcesextra_include_dirsextra_library_dirs	librariesz-DHAVE_PATCHED_LMDB=1r-   	lmdb_cffilmdbr.   r/   r1   r0   )
modulenameext_packagesourcesr-   include_dirsr1   library_dirszint(char *, void *)c                     t         j                  j                  t        j	                  |       j                                y)zJmdb_msg_func() callback. Appends `s` to _callbacks.msg_func list.
        r   )
_callbacksmsg_funcappend_ffistringdecode)s_s     )lib/python3.12/site-packages/lmdb/cffi.py	_msg_funcrC   }  s,     	""4;;q>#8#8#:;    c                       e Zd ZdZddZy)r   zjRaised when an LMDB-related error occurs, and no more specific
    :py:class:`lmdb.Error` subclass exists.c                     || _         || _        t        j                  t        j                  |            | _        |}|r)|d| j                  }t        | dd       }|r	|d|dz  }t        j                  | |       y )Nz: MDB_HINTz ())
whatcoder=   r>   _libmdb_strerrorreasongetattr	Exception__init__)selfrI   rJ   msghints        rB   rP   zError.__init__  so    		kk$"3"3D"9:"DKK0C4T2D$((4%rD   N)r   )__name__
__module____qualname____doc__rP    rD   rB   r   r     s    /
&rD   r   c                       e Zd ZdZdZy)r   zKey/data pair already exists.MDB_KEYEXISTNrT   rU   rV   rW   MDB_NAMErX   rD   rB   r   r     s
    'HrD   r   c                       e Zd ZdZdZy)r   a   No matching key/data pair found.

    Normally py-lmdb indicates a missing key by returning ``None``, or a
    user-supplied default value, however LMDB may return this error where
    py-lmdb does not know to convert it into a non-exceptional return.
    MDB_NOTFOUNDNr[   rX   rD   rB   r   r     s     HrD   r   c                       e Zd ZdZdZy)r    zRequest page not found.MDB_PAGE_NOTFOUNDNr[   rX   rD   rB   r    r      s
    !"HrD   r    c                       e Zd ZdZdZy)r   z#Located page was of the wrong type.MDB_CORRUPTEDNr[   rX   rD   rB   r   r     s
    -HrD   r   c                       e Zd ZdZdZy)r!   zUpdate of meta page failed.	MDB_PANICNr[   rX   rD   rB   r!   r!     s
    %HrD   r!   c                       e Zd ZdZdZy)r&   z&Database environment version mismatch.MDB_VERSION_MISMATCHNr[   rX   rD   rB   r&   r&     s
    0%HrD   r&   c                       e Zd ZdZdZy)r   zFile is not an MDB file.MDB_INVALIDNr[   rX   rD   rB   r   r     s
    "HrD   r   c                       e Zd ZdZdZdZy)r   z$Environment map_size= limit reached.MDB_MAP_FULLz4Please use a larger Environment(map_size=) parameterNrT   rU   rV   rW   r\   rG   rX   rD   rB   r   r     s    .HEHrD   r   c                       e Zd ZdZdZdZy)r   z#Environment max_dbs= limit reached.MDB_DBS_FULLz3Please use a larger Environment(max_dbs=) parameterNrk   rX   rD   rB   r   r     s    -HDHrD   r   c                       e Zd ZdZdZdZy)r"   z'Environment max_readers= limit reached.MDB_READERS_FULLz7Please use a larger Environment(max_readers=) parameterNrk   rX   rD   rB   r"   r"     s    1!HHHrD   r"   c                       e Zd ZdZdZy)r$   z<Thread-local storage keys full - too many environments open.MDB_TLS_FULLNr[   rX   rD   rB   r$   r$     s
    FHrD   r$   c                       e Zd ZdZdZdZy)r%   z;Transaciton has too many dirty pages - transaction too big.MDB_TXN_FULLz+Please do less work within your transactionNrk   rX   rD   rB   r%   r%     s    EH<HrD   r%   c                       e Zd ZdZdZy)r   z,Internal error - cursor stack limit reached.MDB_CURSOR_FULLNr[   rX   rD   rB   r   r     s
    6 HrD   r   c                       e Zd ZdZdZy)r   z(Internal error - page has no more space.MDB_PAGE_FULLNr[   rX   rD   rB   r   r     s
    2HrD   r   c                       e Zd ZdZdZy)r   z4Database contents grew beyond environment map_size=.MDB_MAP_RESIZEDNr[   rX   rD   rB   r   r     s
    > HrD   r   c                       e Zd ZdZdZy)r   z3Operation and DB incompatible, or DB flags changed.MDB_INCOMPATIBLENr[   rX   rD   rB   r   r     s
    =!HrD   r   c                       e Zd ZdZdZy)r   z'Invalid reuse of reader locktable slot.MDB_BAD_RSLOTNr[   rX   rD   rB   r   r     s
    1HrD   r   c                       e Zd ZdZdZy)r   z+The specified DBI was changed unexpectedly.MDB_BAD_DBINr[   rX   rD   rB   r   r     s
    5HrD   r   c                       e Zd ZdZdZy)r   z0Transaction cannot recover - it must be aborted.MDB_BAD_TXNNr[   rX   rD   rB   r   r     s
    :HrD   r   c                       e Zd ZdZdZy)r   z7Too big key/data, key is empty, or wrong DUPFIXED size.MDB_BAD_VALSIZENr[   rX   rD   rB   r   r     s
    A HrD   r   c                       e Zd ZdZdZy)r#   z3An attempt was made to modify a read-only database.EACCESNr[   rX   rD   rB   r#   r#     s
    =HrD   r#   c                       e Zd ZdZdZy)r   z#An invalid parameter was specified.EINVALNr[   rX   rD   rB   r   r     s
    -HrD   r   c                       e Zd ZdZdZy)r   z.The environment was locked by another process.EAGAINNr[   rX   rD   rB   r   r     s
    8HrD   r   c                       e Zd ZdZdZy)r   zOut of memory.ENOMEMNr[   rX   rD   rB   r   r     s
    HrD   r   c                       e Zd ZdZdZy)r   zNo more disk space.ENOSPCNr[   rX   rD   rB   r   r     s
    HrD   r   c                 B    t        j                  |t              | |      S )zLookup and instantiate the correct exception class for the error code
    `rc`, using :py:class:`Error` if no better class exists.)
_error_mapgetr   )rI   rcs     rB   _errorr     s     >>"e$T2..rD   c                   "    e Zd ZdZd Zd Zd Zy)-Some_LMDB_Resource_That_Was_Deleted_Or_ClosedaB  We need this because CFFI on PyPy treats None as cffi.NULL, instead of
    throwing an exception it feeds LMDB null pointers. That means simply
    replacing native handles with None during _invalidate() will cause NULL
    pointer dereferences. Instead use this class, and its weird name to cause a
    TypeError, with a very obvious string in the exception text.

    The only alternatives to this are inserting a check around every single use
    of a native handle to ensure the handle is still valid prior to calling
    LMDB, or doing no crash-safety checking at all.
    c                      yNr   rX   rQ   s    rB   __nonzero__z9Some_LMDB_Resource_That_Was_Deleted_Or_Closed.__nonzero__  s    rD   c                      y)NFrX   r   s    rB   __bool__z6Some_LMDB_Resource_That_Was_Deleted_Or_Closed.__bool__  s    rD   c                      y)Nz><This used to be a LMDB resource but it was deleted or closed>rX   r   s    rB   __repr__z6Some_LMDB_Resource_That_Was_Deleted_Or_Closed.__repr__  s    OrD   N)rT   rU   rV   rW   r   r   r   rX   rD   rB   r   r     s    	PrD   r   c                 V    t         j                  | j                  | j                        S )z0Convert a MDB_val cdata to a CFFI buffer object.r=   buffermv_datamv_sizemvs    rB   _mvbufr   "  s    ;;rzz2::..rD   c                 \    t         j                  | j                  | j                        dd S )z(Convert a MDB_val cdata to Python bytes.Nr   r   s    rB   _mvstrr   &  s     ;;rzz2::.q11rD   c                 Z    t         j                  d| j                  | j                         y r   )rK   preloadr   r   r   s    rB   r   r   *  s    LLBJJ

+rD   c                       y)zDeprecated.NrX   rX   rD   rB   r   r   -  s    rD   c                     | r9t         j                  t         j                  t         j                  t        rdfS dfS t         j                  t         j                  t         j                  fS )a  
    Return a tuple of integers `(major, minor, patch)` describing the LMDB
    library version that the binding is linked against. The version of the
    binding itself is available from ``lmdb.__version__``.

        `subpatch`:
            If true, returns a 4 integer tuple consisting of the same plus
            an extra integer that represents any patches applied by py-lmdb
            itself (0 representing no patches).

       r   )rK   MDB_VERSION_MAJORMDB_VERSION_MINORMDB_VERSION_PATCH_have_patched_lmdb)subpatchs    rB   r   r   0  sg     &&&&&&'0 	0 ./0 	0
 """"""$ $rD   c                       e Zd ZdZddddddeddddddddfdZd	 Zd
 Zd ZdZ	dZ
dZdZd Zd Zd ZddZddZddZd Zd Zd Zd Zd Zd Zd Zd Z	 	 	 ddZd dZy)!r   a  
    Structure for a database environment. An environment may contain multiple
    databases, all residing in the same shared-memory map and underlying disk
    file.

    To write to the environment a :py:class:`Transaction` must be created. One
    simultaneous write transaction is allowed, however there is no limit on the
    number of read transactions even when a write transaction exists.

    This class is aliased to `lmdb.open`.

    It is a serious error to have open the same LMDB file in the same process at
    the same time.  Failure to heed this may lead to data corruption and
    interpreter crash.

    Equivalent to `mdb_env_open()
    <http://lmdb.tech/doc/group__mdb.html#ga1fe2740e25b1689dc412e7b9faadba1b>`_

        `path`:
            Location of directory (if `subdir=True`) or file prefix to store
            the database.

        `map_size`:
            Maximum size database may grow to; used to size the memory mapping.
            If database grows larger than ``map_size``, an exception will be
            raised and the user must close and reopen :py:class:`Environment`.
            On 64-bit there is no penalty for making this huge (say 1TB). Must
            be <2GB on 32-bit.

            .. note::

                **The default map size is set low to encourage a crash**, so
                users can figure out a good value before learning about this
                option too late.

        `subdir`:
            If ``True``, `path` refers to a subdirectory to store the data and
            lock files in, otherwise it refers to a filename prefix.

        `readonly`:
            If ``True``, disallow any write operations. Note the lock file is
            still modified. If specified, the ``write`` flag to
            :py:meth:`begin` or :py:class:`Transaction` is ignored.

        `metasync`:
            If ``False``, flush system buffers to disk only once per
            transaction, omit the metadata flush. Defer that until the system
            flushes files to disk, or next commit or :py:meth:`sync`.

            This optimization maintains database integrity, but a system crash
            may undo the last committed transaction. I.e. it preserves the ACI
            (atomicity, consistency, isolation) but not D (durability) database
            property.

        `sync`:
            If ``False``, don't flush system buffers to disk when committing a
            transaction. This optimization means a system crash can corrupt the
            database or lose the last transactions if buffers are not yet
            flushed to disk.

            The risk is governed by how often the system flushes dirty buffers
            to disk and how often :py:meth:`sync` is called.  However, if the
            filesystem preserves write order and `writemap=False`, transactions
            exhibit ACI (atomicity, consistency, isolation) properties and only
            lose D (durability).  I.e. database integrity is maintained, but a
            system crash may undo the final transactions.

            Note that `sync=False, writemap=True` leaves the system with no
            hint for when to write transactions to disk, unless :py:meth:`sync`
            is called. `map_async=True, writemap=True` may be preferable.

        `mode`:
            File creation mode.

        `create`:
            If ``False``, do not create the directory `path` if it is missing.

        `readahead`:
            If ``False``, LMDB will disable the OS filesystem readahead
            mechanism, which may improve random read performance when a
            database is larger than RAM.

        `writemap`:
            If ``True``, use a writeable memory map unless `readonly=True`.
            This is faster and uses fewer mallocs, but loses protection from
            application bugs like wild pointer writes and other bad updates
            into the database. Incompatible with nested transactions.

            Processes with and without `writemap` on the same environment do
            not cooperate well.

        `meminit`:
            If ``False`` LMDB will not zero-initialize buffers prior to writing
            them to disk. This improves performance but may cause old heap data
            to be written saved in the unused portion of the buffer. Do not use
            this option if your application manipulates confidential data (e.g.
            plaintext passwords) in memory. This option is only meaningful when
            `writemap=False`; new pages are always zero-initialized when
            `writemap=True`.

        `map_async`:
             When ``writemap=True``, use asynchronous flushes to disk. As with
             ``sync=False``, a system crash can then corrupt the database or
             lose the last transactions. Calling :py:meth:`sync` ensures
             on-disk database integrity until next commit.

        `max_readers`:
            Maximum number of simultaneous read transactions. Can only be set
            by the first process to open an environment, as it affects the size
            of the lock file and shared memory area. Attempts to simultaneously
            start more than this many *read* transactions will fail.

        `max_dbs`:
            Maximum number of databases available. If 0, assume environment
            will be used as a single database.

        `max_spare_txns`:
            Read-only transactions to cache after becoming unused. Caching
            transactions avoids two allocations, one lock and linear scan
            of the shared environment per invocation of :py:meth:`begin`,
            :py:class:`Transaction`, :py:meth:`get`, :py:meth:`gets`, or
            :py:meth:`cursor`. Should match the process's maximum expected
            concurrent transactions (e.g. thread count).

        `lock`:
            If ``False``, don't do any locking. If concurrent access is
            anticipated, the caller must manage all concurrency itself. For
            proper operation the caller must enforce single-writer semantics,
            and must ensure that no readers are using old transactions while a
            writer is active. The simplest approach is to use an exclusive lock
            so that no readers may be active at all when a writer begins.
    i   TF~   r   r   c                    || _         g | _        t        j                  d      }t        j                  |      }|rt        d|      |d   | _        t               | _	        d| _
        | j                  |       t        j                  | j                  |      }|rt        d|      t        j                  | j                  |      }|rt        d|      |	r|r|s	 t        j                  ||       t        j&                  }|s|t        j(                  z  }|r|t        j*                  z  }|| _        |s|t        j.                  z  }|s|t        j0                  z  }|r|t        j2                  z  }|
s|t        j4                  z  }|r|t        j6                  z  }|s|t        j8                  z  }|s|t        j:                  z  }t=        |t>              r#|jA                  tC        jD                               }t        jG                  | j                  |||tH         z        }|rt        ||      | jK                  tM                     5 }tO        | |d dddddd		      | _(        d d d        d | jP                  i| _)        y # t         $ r)}|j"                  t"        j$                  k7  r Y d }~d }~ww xY w# 1 sw Y   RxY w)
Nz
MDB_env **mdb_env_creater   Fmdb_env_set_maxreadersmdb_env_set_maxdbs)dbT)	envtxnnamereverse_keydupsortcreate
integerkey
integerdupdupfixed)*_max_spare_txns_spare_txnsr=   newrK   r   r   _envset_deps_creating_db_in_readonlyset_mapsizer   r   osmkdirEnvironmentErrorerrnoEEXIST	MDB_NOTLSMDB_NOSUBDIR
MDB_RDONLYreadonlyMDB_NOMETASYNC
MDB_NOSYNCMDB_MAPASYNCMDB_NORDAHEADMDB_WRITEMAPMDB_NOMEMINIT
MDB_NOLOCK
isinstanceUnicodeTypeencodesysgetfilesystemencodingmdb_env_openO_0111beginobjectr
   _db_dbs)rQ   pathmap_sizesubdirr   metasyncsync	map_asyncmoder   	readaheadwritemapmeminitmax_readersmax_dbsmax_spare_txnslockenvppr   eflagsr   s                         rB   rP   zEnvironment.__init__  sb   
  .&  ')2..!H	U
(-%"((K@1266$$TYY8-r22fXt$
 T&&&ET__$E T(((ET__$ET&&&ET'''ET&&&ET'''ET__$EdK(;;s88:;Dtyy$tvg~Fr""ZZ68Z$ !  
DH % 488$	[ $ 77ell* +@ %$s$   J  
J5 	J2	J--J25J>c                     | S NrX   r   s    rB   	__enter__zEnvironment.__enter__      rD   c                 $    | j                          y r   closerQ   _1_2_3s       rB   __exit__zEnvironment.__exit__      

rD   c                 $    | j                          y r   r   r   s    rB   __del__zEnvironment.__del__  r  rD   Nc                 `    t         j                  | j                  |      }|rt        d|      y)a  Change the maximum size of the map file. This function will fail if
        any transactions are active in the current process.

        `map_size`:
            The new size in bytes.

        Equivalent to `mdb_env_set_mapsize()
        <http://lmdb.tech/doc/group__mdb.html#gaa2506ec8dab3d969b0e609cd82e619e5>`_

        Warning:
        There's a data race in the underlying library that may cause
        catastrophic loss of data if you use this method.

        You are safe if one of the following are true:
            * Only one process accessing a particular LMDB file ever calls
              this method.

            * You use locking external to this library to ensure that only one
              process accessing the current LMDB file can be inside this function.
        mdb_env_set_mapsizeN)rK   r  r   r   )rQ   r   r   s      rB   r   zEnvironment.set_mapsize'  s0    * %%dii:.33 rD   c                 6   | j                   r| j                  rA| j                  r5| j                  j                         j                          | j                  r5d| _        | j                  rF| j                  r:t
        j                  | j                  j                                | j                  r:d| _        | j                  r| j                  j                          d| _        d| _	        t
        j                  | j                          t        | _         yy)a  Close the environment, invalidating any open iterators, cursors, and
        transactions. Repeat calls to :py:meth:`close` have no effect.

        Equivalent to `mdb_env_close()
        <http://lmdb.tech/doc/group__mdb.html#ga4366c43ada8874588b6a62fbda2d1e95>`_
        N)r   r   pop_invalidater   rK   mdb_txn_abortr   clearr   mdb_env_close_invalidr   s    rB   r   zEnvironment.close@  s     99zzjjJJNN$002 jjDJ&&&&t'7'7';';'=> &&#Dyy		!DIDHtyy) DI# rD   c                     t         j                  d      }t        j                  | j                  |      }|rt        d|      t         j                  |d         j                  t        j                               S )zDirectory path or file name prefix where this environment is
        stored.

        Equivalent to `mdb_env_get_path()
        <http://lmdb.tech/doc/group__mdb.html#gac699fdd8c4f8013577cb933fb6a757fe>`_
        zchar **mdb_env_get_pathr   )
r=   r   rK   r  r   r   r>   r?   r   r   )rQ   r   r   s      rB   r   zEnvironment.pathZ  s`     xx	"""499d3+R00{{47#**3+D+D+FGGrD   c                    |rt         j                  nd}|rt        st        d      |r|st        d      |j	                  t        j                               }t        rMt         j                  | j                  |||r|j                  nt        j                        }|rt        d|      yt         j                  | j                  ||      }|rt        d|      y)a  Make a consistent copy of the environment in the given destination
        directory.

        `compact`:
            If ``True``, perform compaction while copying: omit free pages and
            sequentially renumber all pages in output. This option consumes
            more CPU and runs more slowly than the default, but may produce a
            smaller output database.

        `txn`:
            If provided, the backup will be taken from the database with
            respect to that transaction, otherwise a temporary read-only
            transaction will be created.  Note:  this parameter being non-None
            is not available if the module was built with LMDB_PURE.  Note:
            this parameter may be set only if compact=True.

        Equivalent to `mdb_env_copy2() or mdb_env_copy3()
        <http://lmdb.tech/doc/group__mdb.html#ga5d51d6130325f7353db0955dbedbc378>`_
        r   :Non-patched LMDB doesn't support transaction with env.copy.txn argument only compatible with compact=Truemdb_env_copy3mdb_env_copy2N)rK   MDB_CP_COMPACTr   	TypeErrorr   r   r   r  r   _txnr=   NULLr   r  )rQ   r   compactr   r   encodedr   s          rB   copyzEnvironment.copyg  s    ( (/##A)XYYuLMM++c779:##DIIw3sxxTXT]T]^B_b11  ##DIIw>B_b11 rD   c                    |rt         st        d      t        rt        j                  |      }|rt
        j                  nd}|r|st        d      t         rMt
        j                  | j                  |||r|j                  nt        j                        }|rt        d|      yt
        j                  | j                  ||      }|rt        d|      y)a?  Copy a consistent version of the environment to file descriptor
        `fd`.

        `compact`:
            If ``True``, perform compaction while copying: omit free pages and
            sequentially renumber all pages in output. This option consumes
            more CPU and runs more slowly than the default, but may produce a
            smaller output database.

        `txn`:
            If provided, the backup will be taken from the database with
            respect to that transaction, otherwise a temporary read-only
            transaction will be created.  Note:  this parameter being non-None
            is not available if the module was built with LMDB_PURE.

        Equivalent to `mdb_env_copyfd2() or mdb_env_copyfd3
        <http://lmdb.tech/doc/group__mdb.html#ga5d51d6130325f7353db0955dbedbc378>`_
        r  r   r  mdb_env_copyfd3mdb_env_copyfd2N)r   r  is_win32msvcrtget_osfhandlerK   r  r  r   r  r=   r  r   r  )rQ   fdr  r   r   r   s         rB   copyfdzEnvironment.copyfd  s    & )XYY%%b)B'.##AuLMM%%diiUCHHQUQZQZ[B.33  %%diiU;B.33 rD   c                 `    t         j                  | j                  |      }|rt        d|      y)a  Flush the data buffers to disk.

        Equivalent to `mdb_env_sync()
        <http://lmdb.tech/doc/group__mdb.html#ga85e61f05aa68b520cc6c3b981dba5037>`_

        Data is always written to disk when :py:meth:`Transaction.commit` is
        called, but the operating system may keep it buffered. MDB always
        flushes the OS buffers upon commit as well, unless the environment was
        opened with `sync=False` or `metasync=False`.

        `force`:
            If ``True``, force a synchronous flush. Otherwise if the
            environment was opened with `sync=False` the flushes will be
            omitted, and with `map_async=True` they will be asynchronous.
        mdb_env_syncN)rK   r$  r   r   )rQ   forcer   s      rB   r   zEnvironment.sync  s/      tyy%0,, rD   c                     |j                   |j                  |j                  |j                  |j                  |j
                  dS )z&Convert a MDB_stat to a dict.
        )psizedepthbranch_pages
leaf_pagesoverflow_pagesentries)ms_psizems_depthms_branch_pagesms_leaf_pagesms_overflow_pages
ms_entries)rQ   sts     rB   _convert_statzEnvironment._convert_stat  s>     [[[[..** 22}}
 	
rD   c                     t         j                  d      }t        j                  | j                  |      }|rt        d|      | j                  |      S )av  stat()

        Return some environment statistics for the default database as a dict:

        +--------------------+---------------------------------------+
        | ``psize``          | Size of a database page in bytes.     |
        +--------------------+---------------------------------------+
        | ``depth``          | Height of the B-tree.                 |
        +--------------------+---------------------------------------+
        | ``branch_pages``   | Number of internal (non-leaf) pages.  |
        +--------------------+---------------------------------------+
        | ``leaf_pages``     | Number of leaf pages.                 |
        +--------------------+---------------------------------------+
        | ``overflow_pages`` | Number of overflow pages.             |
        +--------------------+---------------------------------------+
        | ``entries``        | Number of data items.                 |
        +--------------------+---------------------------------------+

        Equivalent to `mdb_env_stat()
        <http://lmdb.tech/doc/group__mdb.html#gaf881dca452050efbd434cd16e4bae255>`_
        
MDB_stat *mdb_env_stat)r=   r   rK   r7  r   r   r4  )rQ   r3  r   s      rB   statzEnvironment.stat  sI    , XXl#tyy"-,,!!"%%rD   c                 L   t         j                  d      }t        j                  | j                  |      }|rt        d|      t        t         j                  d|j                              |j                  |j                  |j                  |j                  |j                  dS )a"  Return some nice environment information as a dict:

        +--------------------+---------------------------------------------+
        | ``map_addr``       | Address of database map in RAM.             |
        +--------------------+---------------------------------------------+
        | ``map_size``       | Size of database map in RAM.                |
        +--------------------+---------------------------------------------+
        | ``last_pgno``      | ID of last used page.                       |
        +--------------------+---------------------------------------------+
        | ``last_txnid``     | ID of last committed transaction.           |
        +--------------------+---------------------------------------------+
        | ``max_readers``    | Number of reader slots allocated in the     |
        |                    | lock file. Equivalent to the value of       |
        |                    | `maxreaders=` specified by the first        |
        |                    | process opening the Environment.            |
        +--------------------+---------------------------------------------+
        | ``num_readers``    | Maximum number of reader slots in           |
        |                    | simultaneous use since the lock file was    |
        |                    | initialized.                                |
        +--------------------+---------------------------------------------+

        Equivalent to `mdb_env_info()
        <http://lmdb.tech/doc/group__mdb.html#ga18769362c7e7d6cf91889a028a5c5947>`_
        zMDB_envinfo *mdb_env_infolong)map_addrr   	last_pgno
last_txnidr   num_readers)r=   r   rK   r:  r   r   intcast
me_mapaddr
me_mapsizeme_last_pgnome_last_txnidme_maxreadersme_numreaders)rQ   infor   s      rB   rH  zEnvironment.info  s    2 xx(tyy$/,,DIIfdoo>?**,,----
 	
rD   c           
          t         j                  dd      }t        j                  | j                  |      }|rt        d|      |d   }|t        j                  z   t        |t        j                  z        |t        j                  z   |t        j                  z   t        |t        j                  z        |t        j                  z   t        |t        j                  z        |t        j                  z   |t        j                  z   d	S )zdReturn a dict describing Environment constructor flags used to
        instantiate this environment.unsigned int[]r   mdb_env_get_flagsr   )	r   r   r   r   r   r   r   r   r   )r=   r   rK   rK  r   r   r   boolr   r   r   r   r   r   r   r   )rQ   flags_r   r   s       rB   r   zEnvironment.flags  s     *A.##DIIv6,b11q	 4#4#445UT__45"T%8%88901ed&7&778#d&8&889UT%6%667!D$6$66701

 
	
rD   c                 @    t         j                  | j                        S )zReturn the maximum size in bytes of a record's key part. This
        matches the ``MDB_MAXKEYSIZE`` constant set at compile time.)rK   mdb_env_get_maxkeysizer   r   s    rB   max_key_sizezEnvironment.max_key_size(  s     **49955rD   c                     t         j                  dd      }t        j                  | j                  |      }|rt        d|      |d   S )zReturn the maximum number of readers specified during open of the
        environment by the first process. This is the same as `max_readers=`
        specified to the constructor if this process was the first to open the
        environment.rJ  r   mdb_env_get_maxreadersr   )r=   r   rK   rR  r   r   )rQ   readers_r   s      rB   r   zEnvironment.max_readers-  sF    
 88,a0((H=1266{rD   c                    g t         _        	 t        j                  | j                  t
        t        j                        }|rt        d|      t               j                  t         j                        t         `S # t         `w xY w)zaReturn a multi line Unicode string describing the current state of
        the reader lock table.mdb_reader_list)r:   r;   rK   rU  r   rC   r=   r  r   r   joinrQ   r   s     rB   readerszEnvironment.readers8  sa     !
	$%%diiDIIFB.33=%%j&9&9:#
#s   A'A; ;Bc                     t         j                  dd      }t        j                  | j                  |      }|rt        d|      |d   S )zSearch the reader lock table for stale entries, for example due to a
        crashed process. Returns the number of stale entries that were cleared.
        zint[]r   mdb_reader_checkr   )r=   r   rK   rZ  r   r   )rQ   reapedr   s      rB   reader_checkzEnvironment.reader_checkD  sE     '1%""499f5+R00ayrD   c	                    t        |t              rt        d      ||s|s|s|s|rt        d      | j                  j                  |      }	|	r|	S |rd}|rd}|rt        | ||||||||	      }	nH	 d| _        | j                  | j                         5 }t        | ||||||||	      }	ddd       d| _        |	| j                  |<   |	S # 1 sw Y   !xY w# d| _        w xY w)a  
        Open a database, returning an instance of :py:class:`_Database`. Repeat
        :py:meth:`Environment.open_db` calls for the same name will return the
        same handle. As a special case, the main database is always open.

        Equivalent to `mdb_dbi_open()
        <http://lmdb.tech/doc/group__mdb.html#gac08cad5b096925642ca359a6d6f0562a>`_

        Named databases are implemented by *storing a special descriptor in the
        main database*. All databases in an environment *share the same file*.
        Because the descriptor is present in the main database, attempts to
        create a named database will fail if a key matching the database's name
        already exists. Furthermore *the key is visible to lookups and
        enumerations*. If your main database keyspace conflicts with the names
        you use for named databases, then move the contents of your main
        database to another named database.

        ::

            >>> env = lmdb.open('/tmp/test', max_dbs=2)
            >>> with env.begin(write=True) as txn:
            ...     txn.put('somename', 'somedata')

            >>> # Error: database cannot share name of existing key!
            >>> subdb = env.open_db('somename')

        A newly created database will not exist if the transaction that created
        it aborted, nor if another process deleted it. The handle resides in
        the shared environment, it is not owned by the current transaction or
        process. Only one thread should call this function; it is not
        mutex-protected in a read-only transaction.

        The `dupsort`, `integerkey`, `integerdup`, and `dupfixed` parameters are
        ignored if the database already exists.  The state of those settings are
        persistent and immutable per database.  See :py:meth:`_Database.flags`
        to view the state of those options for an opened database.  A consequence
        of the immutability of these flags is that the default non-named database
        will never have these flags set.

        Preexisting transactions, other than the current transaction and any
        parents, must not use the new handle, nor must their children.

            `key`:
                Bytestring database name. If ``None``, indicates the main
                database should be returned, otherwise indicates a named
                database should be created inside the main database.

                In other words, *a key representing the database will be
                visible in the main database, and the database name cannot
                conflict with any existing key.*

            `txn`:
                Transaction used to create the database if it does not exist.
                If unspecified, a temporarily write transaction is used. Do not
                call :py:meth:`open_db` from inside an existing transaction
                without supplying it here. Note the passed transaction must
                have `write=True`.

            `reverse_key`:
                If ``True``, keys are compared from right to left (e.g. DNS
                names).

            `dupsort`:
                Duplicate keys may be used in the database. (Or, from another
                perspective, keys may have multiple data items, stored in
                sorted order.) By default keys must be unique and may have only
                a single data item.

            `create`:
                If ``True``, create the database if it doesn't exist, otherwise
                raise an exception.

            `integerkey`:
                If ``True``, indicates keys in the database are C unsigned
                or ``size_t`` integers encoded in native byte order. Keys must
                all be either unsigned or ``size_t``, they cannot be mixed in a
                single database.

            `integerdup`:
                If ``True``, values in the
                database are C unsigned or ``size_t`` integers encoded in
                native byte order.  Implies `dupsort` and `dupfixed` are
                ``True``.

            `dupfixed`:
                If ``True``, values for each key
                in database are of fixed size, allowing each additional
                duplicate value for a key to be stored without a header
                indicating its size.  Implies `dupsort` is ``True``.
        zkey must be bytesNz&May not set flags on the main databaseT)writeF)
r   r   r  
ValueErrorr   r   r
   r   r   r   )
rQ   keyr   r   r   r   r   r   r   r   s
             rB   open_dbzEnvironment.open_dbN  s    z c;'/00;K7jJ'EFFYY]]3IHG4c;%z8=B604-ZZ$--&7Z8C"4c;#-z8EB 9 16-		#	 98 16-s$   1$C C	)C 	CC 	Cc                      t        | ||||      S )z)Shortcut for :py:class:`lmdb.Transaction`)r	   )rQ   r   parentr^  bufferss        rB   r   zEnvironment.begin  s    4VUG<<rD   )FNF)NNFFTFFFNNFF)rT   rU   rV   rW   O_0755rP   r   r   r  r   r   r   r   r   r   r   r  r"  r   r4  r8  rH  r   rP  r   rX  r\  ra  r   rX   rD   rB   r   r   G  s    CH '/t$TUTTE3!	K%Z DEKD42!4H#2J$4L-(

&8$
L
(6
	
$ FK:?zx=rD   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)r
   z
    Internal database handle.  This class is opaque, save a single method.

    Should not be constructed directly.  Use :py:meth:`Environment.open_db`
    instead.
    c
                 X   |j                   j                  |        t               | _         || _        d}
|r|
t        j
                  z  }
|r|
t        j                  z  }
|r|
t        j                  z  }
|r|
t        j                  z  }
|r|
t        j                  z  }
|	r|
t        j                  z  }
t        j                  d      }d | _        t        j                  |j                  |xs t        j                   |
|      }|rt#        d|      |d   | _        | j%                  |       y )Nr   z	MDB_dbi *mdb_dbi_open)r   addr   _namerK   MDB_REVERSEKEYMDB_DUPSORT
MDB_CREATEMDB_INTEGERKEYMDB_INTEGERDUPMDB_DUPFIXEDr=   r   _dbirj  r  r  r   _load_flags)rQ   r   r   r   r   r   r   r   r   r   r   dbippr   s                rB   rP   z_Database.__init__  s    		dU

T(((ET%%%ET__$ET(((ET(((ET&&&E%	sxx):E5I,,!H	rD   c                     t         j                  dd      }t        j                  |j                  | j
                  |      }|rt        d|      |d   | _        y)z(Load MDB's notion of the database flags.rJ  r   mdb_dbi_flagsr   N)r=   r   rK   rw  r  rs  r   _flags)rQ   r   rM  r   s       rB   rt  z_Database._load_flags  sJ    *A.$))V<"--QirD   c                    t        |      dkD  rt        d      t        | j                  t        j
                  z        t        | j                  t        j                  z        t        | j                  t        j                  z        t        | j                  t        j                  z        t        | j                  t        j                  z        dS )zYReturn the database's associated flags as a dict of _Database
        constructor kwargs.r   zflags takes 0 or 1 arguments)r   r   r   r   r   )
lenr  rL  rx  rK   rm  rn  rp  rq  rr  )rQ   argss     rB   r   z_Database.flags  s     t9q=:;;  d.A.A ABDKK$*:*::;t{{T-@-@@At{{T-@-@@AT[[4+<+<<=
 	
rD   c                     t         | _        y r   )r  rs  r   s    rB   r  z_Database._invalidate  s	    	rD   N)rT   rU   rV   rW   rP   rt  r   r  rX   rD   rB   r
   r
     s    6 
rD   r
   c                       e Zd ZdZeZeZdZdZdZ	ddZ
d Zd Zd Zd	 Zd
 Zd ZddZd Zd Zd ZddZ	 	 ddZddZddZedfdZddZy)r	   aP  
    A transaction object. All operations require a transaction handle,
    transactions may be read-only or read-write. Write transactions may not
    span threads. Transaction objects implement the context manager protocol,
    so that reliable release of the transaction happens even in the face of
    unhandled exceptions:

        .. code-block:: python

            # Transaction aborts correctly:
            with env.begin(write=True) as txn:
                crash()

            # Transaction commits automatically:
            with env.begin(write=True) as txn:
                txn.put('a', 'b')

    Equivalent to `mdb_txn_begin()
    <http://lmdb.tech/doc/group__mdb.html#gad7ea55da06b77513609efebd44b26920>`_

        `env`:
            Environment the transaction should be on.

        `db`:
            Default named database to operate on. If unspecified, defaults to
            the environment's main database. Can be overridden on a per-call
            basis below.

        `parent`:
            ``None``, or a parent transaction (see lmdb.h).

        `write`:
            Transactions are read-only by default. To modify the database, you
            must pass `write=True`. This flag is ignored if
            :py:class:`Environment` was opened with ``readonly=True``.

        `buffers`:
            If ``True``, indicates :py:func:`buffer` objects should be yielded
            instead of bytestrings. This setting applies to the
            :py:class:`Transaction` instance itself and any :py:class:`Cursors
            <Cursor>` created within the transaction.

            This feature significantly improves performance, since MDB has a
            zero-copy design, but it requires care when manipulating the
            returned buffer objects. The benefit of this facility is diminished
            when using small keys and values.
    NFr   c                 ~   |j                   j                  |        || _        |xs |j                  | _        |j                  | _        t
        j                  d      | _        t
        j                  d      | _        |rt        nt        | _        t               | _         |r/|| _        |j                  }|j                   j                  |        nt
        j                  }|r|j                   rd}t#        |t$        j&                        t
        j                  d      }t$        j)                  | j                  |d|      }	|	rt#        d|	      |d   | _        d| _        y 	 |j,                  rt.        |j0                  j3                         | _        |xj4                  dz  c_        t$        j7                  | j                        }	|	r| j                   r5| j                   j3                         j9                          | j                   r5t$        j;                  | j                         t<        | _        | j9                          t#        d|	      y # t.        $ rb t
        j                  d      }t$        j>                  }
t$        j)                  | j                  ||
|      }	|	rt#        d|	      |d   | _        Y y w xY w)	N	MDB_val *z1Cannot start write transaction with read-only envz
MDB_txn **r   mdb_txn_beginTr   mdb_txn_renew) r   rk  r   r   r   r=   r   _key_valr   r   _to_pyr   _parentr  r  r   r   rK   r   r  _writer   
IndexErrorr   r  r   r  r  r	  r  r   )rQ   r   r   rc  r^  rd  
parent_txnrR   txnppr   r   s              rB   rP   zTransaction.__init__I  s
   		d=HH	HH[)	HH[)	 'fVU
!DLJLLT"J||IS$++..HH\*E##DIIz1eDB_b11aDIDK%//$$OO//1	##q(#''		2**

(446 **&&tyy1 (DI$$& "55   %.''		:ueL "55!!H	%s   "B'I 
AI A(J<;J<c                     | j                   r| j                          | j                  j                  j	                  |        d | _        t        | _        y r   )r  abortr   r   discardr  r  r   r   s    rB   r  zTransaction._invalidate{  s6    99JJLt$	rD   c                 $    | j                          y r   )r  r   s    rB   r  zTransaction.__del__  r  rD   c                     | S r   rX   r   s    rB   r   zTransaction.__enter__  r   rD   c                 J    |r| j                          y | j                          y r   )r  commit)rQ   exc_type	exc_value	tracebacks       rB   r   zTransaction.__exit__  s    JJLKKMrD   c                 @    t         j                  | j                        S )a  id()

        Return the transaction's ID.

        This returns the identifier associated with this transaction. For a
        read-only transaction, this corresponds to the snapshot being read;
        concurrent readers will frequently have the same transaction ID.
        )rK   
mdb_txn_idr  r   s    rB   idzTransaction.id  s     tyy))rD   c                     t         j                  d      }t        j                  | j                  |j
                  |      }|rt        d|      | j                  j                  |      S )zstat(db)

        Return statistics like :py:meth:`Environment.stat`, except for a single
        DBI. `db` must be a database handle returned by :py:meth:`open_db`.
        r6  mdb_stat)	r=   r   rK   r  r  rs  r   r   r4  )rQ   r   r3  r   s       rB   r8  zTransaction.stat  sQ     XXl#]]499bggr2R((xx%%b))rD   c                    |j                   r5|j                   j                         j                          |j                   r5t        j	                  | j
                  |j                  |      }| xj                  dz  c_        |rt        d|      |j                  | j                  j                  v r"| j                  j                  |j                  = yy)aC  Delete all keys in a named database and optionally delete the named
        database itself. Deleting the named database causes it to become
        unavailable, and invalidates existing cursors.

        Equivalent to `mdb_drop()
        <http://lmdb.tech/doc/group__mdb.html#gab966fab3840fc54a6571dfb32b00f2db>`_
        r   mdb_dropN)r   r  r  rK   r  r  rs  
_mutationsr   rl  r   r   )rQ   r   deleter   s       rB   dropzTransaction.drop  s     hhHHLLN&&( hh]]499bggv61R((88txx}}$bhh' %rD   c                 H   | j                   j                  dkD  rt        j                  | j                         | j                   j
                  j                  | j                         | j                   xj                  dz  c_        t        | _        | j                          yy)Nr   r   TF)	r   r   rK   mdb_txn_resetr  r   r<   r  r  r   s    rB   _cache_sparezTransaction._cache_spare  sr     88##a'tyy)HH  ''		2HH$$)$ DIrD   c                 P   | j                   r5| j                   j                         j                          | j                   r5| j                  s| j	                         sIt
        j                  | j                        }t        | _        |rt        d|      | j                          yy)zCommit the pending transaction.

        Equivalent to `mdb_txn_commit()
        <http://lmdb.tech/doc/group__mdb.html#ga846fbd6f46105617ac9f4d76476f6597>`_
        mdb_txn_commitN)
r   r  r  r  r  rK   r  r  r  r   rW  s     rB   r  zTransaction.commit  sz     jjJJNN((* jj;;d//1$$TYY/B DI-r22 2rD   c                 h   | j                   r| j                  r5| j                  j                         j                          | j                  r5| j                  s| j                         s8t        j                  | j                         }t        | _         |rt        d|      | j                          yy)aq  Abort the pending transaction. Repeat calls to :py:meth:`abort` have
        no effect after a previously successful :py:meth:`commit` or
        :py:meth:`abort`, or after the associated :py:class:`Environment` has
        been closed.

        Equivalent to `mdb_txn_abort()
        <http://lmdb.tech/doc/group__mdb.html#ga73a5938ae4c3239ee11efa07eb22b882>`_
        r	  N)
r  r   r  r  r  r  rK   r	  r  r   rW  s     rB   r  zTransaction.abort  s     99**

 ,,. **{{$"3"3"5''		2$	 "55 rD   c                 D   t         j                  | j                  |xs | j                  j                  |t        |      | j                        }|r!|t         j                  k(  r|S t        d|      t        | j                         | j                  | j                        S )a3  Fetch the first value matching `key`, returning `default` if `key`
        does not exist. A cursor must be used to fetch all values for a key in
        a `dupsort=True` database.

        Equivalent to `mdb_get()
        <http://lmdb.tech/doc/group__mdb.html#ga8bf10cd91d3f3a83a34d04ce6b07992d>`_
        mdb_cursor_get)rK   	pymdb_getr  r   rs  rz  r  r^   r   r   r  )rQ   r`  defaultr   r   s        rB   r   zTransaction.get  sz     ^^DIIdhh'<'<S4996T&&&)2..		{{499%%rD   c           
         d}|s|t         j                  z  }|s|t         j                  z  }|r|t         j                  z  }t         j	                  | j
                  |xs | j                  j                  |t        |      |t        |      |      }| xj                  dz  c_	        |r |t         j                  k(  ryt        d|      y)aj  Store a record, returning ``True`` if it was written, or ``False``
        to indicate the key was already present and `overwrite=False`.
        On success, the cursor is positioned on the new record.

        Equivalent to `mdb_put()
        <http://lmdb.tech/doc/group__mdb.html#ga4fa8573d9236d54687c61827ebf8cac0>`_

            `key`:
                Bytestring key to store.

            `value`:
                Bytestring value to store.

            `dupdata`:
                If ``False`` and database was opened with `dupsort=True`, will return
                ``False`` if the key already has that value.  In other words, this only
                affects the return value.

            `overwrite`:
                If ``False``, do not overwrite any existing matching key.  If
                False and writing to a dupsort=True database, this will not add a value
                to the key and this function will return ``False``.

            `append`:
                If ``True``, append the pair to the end of the database without
                comparing its order first. Appending a key that is not greater
                than the highest existing key will fail and return ``False``.

            `db`:
                Named database to operate on. If unspecified, defaults to the
                database given to the :py:class:`Transaction` constructor.
        r   r   Fmdb_putT)rK   MDB_NODUPDATAMDB_NOOVERWRITE
MDB_APPEND	pymdb_putr  r   rs  rz  r  rZ   r   )	rQ   r`  valuedupdata	overwriter<   r   r   r   s	            rB   putzTransaction.put  s    D T'''ET)))ET__$E^^DIIdhh'<'<S5#e*eE1T&&&B''rD   c                     t        |xs | j                  |       5 }|j                  ||      cddd       S # 1 sw Y   yxY w)zUse a temporary cursor to invoke :py:meth:`Cursor.replace`.

            `db`:
                Named database to operate on. If unspecified, defaults to the
                database given to the :py:class:`Transaction` constructor.
        N)r   r   replace)rQ   r`  r  r   curss        rB   r  zTransaction.replace-  s2     BN$((D)T<<U+ *))s	   7A c                     t        |xs | j                  |       5 }|j                  |      cddd       S # 1 sw Y   yxY w)zUse a temporary cursor to invoke :py:meth:`Cursor.pop`.

            `db`:
                Named database to operate on. If unspecified, defaults to the
                database given to the :py:class:`Transaction` constructor.
        N)r   r   r  )rQ   r`  r   r  s       rB   r  zTransaction.pop7  s/     BN$((D)T88C= *))s   6?c           
         |t         }t        j                  | j                  |xs | j                  j
                  |t        |      |t        |            }| xj                  dz  c_        |r |t        j                  k(  ryt        d|      y)a  Delete a key from the database.

        Equivalent to `mdb_del()
        <http://lmdb.tech/doc/group__mdb.html#gab8182f9360ea69ac0afd4a4eaab1ddb0>`_

            `key`:
                The key to delete.

            value:
                If the database was opened with dupsort=True and value is not
                the empty bytestring, then delete elements matching only this
                `(key, value)` pair, otherwise all values for key are deleted.

        Returns True if at least one key was deleted.
        r   Fmdb_delT)
EMPTY_BYTESrK   	pymdb_delr  r   rs  rz  r  r^   r   )rQ   r`  r  r   r   s        rB   r  zTransaction.deleteA  su      =E^^DIIdhh'<'<S5#e*>1T&&&B''rD   c                 6    t        |xs | j                  |       S )z&Shortcut for ``lmdb.Cursor(db, self)``)r   r   )rQ   r   s     rB   cursorzTransaction.cursor]  s    bnDHHd++rD   rf  )T)NN)TTFNr   )rT   rU   rV   rW   r  r   r  r  r  r  rP   r  r  r   r   r  r8  r  r  r  r  r   r  r  r  r  r  r  rX   rD   rB   r	   r	     s    .d DDGF J0%d	*
*(" &&$ DI1f,! !, 8,rD   r	   c                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd,dZeZd-dZd.dZd,dZd-dZd.dZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!d Z"d/d!Z#d0d"Z$d# Z%d$ Z&d1d%Z'd& Z(d2d'Z)d2d(Z*d) Z+d* Z,d+ Z-y )3r   a  
    Structure for navigating a database.

    Equivalent to `mdb_cursor_open()
    <http://lmdb.tech/doc/group__mdb.html#ga9ff5d7bd42557fd5ee235dc1d62613aa>`_

        `db`:
            :py:class:`_Database` to navigate.

        `txn`:
            :py:class:`Transaction` to navigate.

    As a convenience, :py:meth:`Transaction.cursor` can be used to quickly
    return a cursor:

        ::

            >>> env = lmdb.open('/tmp/foo')
            >>> child_db = env.open_db('child_db')
            >>> with env.begin() as txn:
            ...     cursor = txn.cursor()           # Cursor on main database.
            ...     cursor2 = txn.cursor(child_db)  # Cursor on child database.

    Cursors start in an unpositioned state. If :py:meth:`iternext` or
    :py:meth:`iterprev` are used in this state, iteration proceeds from the
    start or end respectively. Iterators directly position using the cursor,
    meaning strange behavior results when multiple iterators exist on the same
    cursor.

    .. note::

        From the perspective of the Python binding, cursors return to an
        'unpositioned' state once any scanning or seeking method (e.g.
        :py:meth:`next`, :py:meth:`prev_nodup`, :py:meth:`set_range`) returns
        ``False`` or raises an exception. This is primarily to ensure safe,
        consistent semantics in the face of any error condition.

        When the Cursor returns to an unpositioned state, its :py:meth:`key`
        and :py:meth:`value` return empty strings to indicate there is no
        active position, although internally the LMDB cursor may still have a
        valid position.

        This may lead to slightly surprising behaviour when iterating the
        values for a `dupsort=True` database's keys, since methods such as
        :py:meth:`iternext_dup` will cause Cursor to appear unpositioned,
        despite it returning ``False`` only to indicate there are no more
        values for the current key. In that case, simply calling
        :py:meth:`next` would cause iteration to resume at the next available
        key.

        This behaviour may change in future.

    Iterator methods such as :py:meth:`iternext` and :py:meth:`iterprev` accept
    `keys` and `values` arguments. If both are ``True``, then the value of
    :py:meth:`item` is yielded on each iteration. If only `keys` is ``True``,
    :py:meth:`key` is yielded, otherwise only :py:meth:`value` is yielded.

    Prior to iteration, a cursor can be positioned anywhere in the database:

        ::

            >>> with env.begin() as txn:
            ...     cursor = txn.cursor()
            ...     if not cursor.set_range('5'): # Position at first key >= '5'.
            ...         print('Not found!')
            ...     else:
            ...         for key, value in cursor: # Iterate from first key >= '5'.
            ...             print((key, value))

    Iteration is not required to navigate, and sometimes results in ugly or
    inefficient code. In cases where the iteration order is not obvious, or is
    related to the data being read, use of :py:meth:`set_key`,
    :py:meth:`set_range`, :py:meth:`key`, :py:meth:`value`, and :py:meth:`item`
    may be preferable:

        ::

            >>> # Record the path from a child to the root of a tree.
            >>> path = ['child14123']
            >>> while path[-1] != 'root':
            ...     assert cursor.set_key(path[-1]), \
            ...         'Tree is broken! Path: %s' % (path,)
            ...     path.append(cursor.value())
    c                 H   |j                   j                  |        |j                   j                  |        || _        || _        |j                  | _        |j
                  | _        t        j                  d      | _        t        j                  d      | _	        d| _
        |j                  | _        t        j                  d      }d | _        t        j                  | j
                  | j                  |      }|rt        d|      |d   | _        |j                   | _        y )Nr  FzMDB_cursor **mdb_cursor_openr   )r   rk  r   r   rs  r  r=   r   r  r  _validr  _currK   r  r   r  _last_mutation)rQ   r   r   curppr   s        rB   rP   zCursor.__init__  s    
T		dGG	HH	HH[)	HH[)	jj)	!!$))TYY>*B//!H	 "nnrD   c                 2   | j                   rt        j                  | j                          | j                  j                  j                  |        | j                  j                  j                  |        t        | _         t        | _        t        | _	        y y r   )
r  rK   mdb_cursor_closer   r   r  r   r  rs  r  r   s    rB   r  zCursor._invalidate  sa    99!!$)),GGMM!!$'HHNN""4( DI DI DI rD   c                 $    | j                          y r   r  r   s    rB   r  zCursor.__del__      rD   c                 $    | j                          y)z3Close the cursor, freeing its associated resources.Nr  r   s    rB   r   zCursor.close  s    rD   c                     | S r   rX   r   s    rB   r   zCursor.__enter__  r   rD   c                 $    | j                          y r   r  r   s       rB   r   zCursor.__exit__  r  rD   c                     | j                   | j                  j                  k7  r| j                  t        j
                         | j                  | j                        S )zReturn the current key.)r  r   r  _cursor_getrK   MDB_GET_CURRENTr  r  r   s    rB   r`  z
Cursor.key  sC     $(("5"55T112{{499%%rD   c                     | j                   | j                  j                  k7  r| j                  t        j
                         t        | j                         | j                  | j                        S )zReturn the current value.)	r  r   r  r  rK   r  r   r  r  r   s    rB   r  zCursor.value  sO     $(("5"55T112		{{499%%rD   c                    | j                   | j                  j                  k7  r| j                  t        j
                         t        | j                         | j                  | j                        | j                  | j                        fS )z'Return the current `(key, value)` pair.)
r  r   r  r  rK   r  r   r  r  r  r   s    rB   itemzCursor.item  sa     $(("5"55T112		{{499%t{{499'===rD   c              #     K   |s| j                   }n|s| j                  }n| j                  }| j                  }| j                  }| j
                  }d}| j                  r6 |        t        j                  ||||      }| | _        | j                  r6|rBd| j                  _	        d| j
                  _	        |t        j                  k7  rt        d|      y y wNr   r  )r`  r  r  r  r  r  r  rK   r  r   r^   r   )	rQ   opkeysvaluesr   curr`  valr   s	            rB   _iterzCursor._iter  s     ((C**C))Ciiiiiikk%K$$S#sB7B &DK kk
  !DII !DIIT&&&-r22 ' s   BCACc                 |    | j                   s| j                          | j                  t        j                  ||      S )af  Return a forward iterator that yields the current element before
        calling :py:meth:`next`, repeating until the end of the database is
        reached. As a convenience, :py:class:`Cursor` implements the iterator
        protocol by automatically returning a forward iterator when invoked:

            ::

                >>> # Equivalent:
                >>> it = iter(cursor)
                >>> it = cursor.iternext(keys=True, values=True)

        If the cursor is not yet positioned, it is moved to the first key in
        the database, otherwise iteration proceeds from the current position.
        )r  firstr  rK   MDB_NEXTrQ   r  r  s      rB   iternextzCursor.iternext  s+     {{JJLzz$--v66rD   c                 D    | j                  t        j                  ||      S )a.  Return a forward iterator that yields the current value
        ("duplicate") of the current key before calling :py:meth:`next_dup`,
        repeating until the last value of the current key is reached.

        Only meaningful for databases opened with `dupsort=True`.

        .. code-block:: python

            if not cursor.set_key("foo"):
                print("No values found for 'foo'")
            else:
                for idx, data in enumerate(cursor.iternext_dup()):
                    print("%d'th value for 'foo': %s" % (idx, data))
        )r  rK   MDB_NEXT_DUPr  s      rB   iternext_dupzCursor.iternext_dup%  s     zz$++T6::rD   c                 |    | j                   s| j                          | j                  t        j                  ||      S )aC  Return a forward iterator that yields the current value
        ("duplicate") of the current key before calling :py:meth:`next_nodup`,
        repeating until the end of the database is reached.

        Only meaningful for databases opened with `dupsort=True`.

        If the cursor is not yet positioned, it is moved to the first key in
        the database, otherwise iteration proceeds from the current position.

        .. code-block:: python

            for key in cursor.iternext_nodup():
                print("Key '%s' has %d values" % (key, cursor.count()))
        )r  r  r  rK   MDB_NEXT_NODUPr  s      rB   iternext_nodupzCursor.iternext_nodup6  s-     {{JJLzz$--tV<<rD   c                 |    | j                   s| j                          | j                  t        j                  ||      S )a  Return a reverse iterator that yields the current element before
        calling :py:meth:`prev`, until the start of the database is reached.

        If the cursor is not yet positioned, it is moved to the last key in
        the database, otherwise iteration proceeds from the current position.

        ::

            >>> with env.begin() as txn:
            ...     for i, (key, value) in enumerate(txn.cursor().iterprev()):
            ...         print('%dth last item is (%r, %r)' % (1+i, key, value))
        )r  lastr  rK   MDB_PREVr  s      rB   iterprevzCursor.iterprevI  s+     {{IIKzz$--v66rD   c                 D    | j                  t        j                  ||      S )a  Return a reverse iterator that yields the current value
        ("duplicate") of the current key before calling :py:meth:`prev_dup`,
        repeating until the first value of the current key is reached.

        Only meaningful for databases opened with `dupsort=True`.
        )r  rK   MDB_PREV_DUPr  s      rB   iterprev_dupzCursor.iterprev_dupZ  s     zz$++T6::rD   c                 |    | j                   s| j                          | j                  t        j                  ||      S )a  Return a reverse iterator that yields the current value
        ("duplicate") of the current key before calling :py:meth:`prev_nodup`,
        repeating until the start of the database is reached.

        If the cursor is not yet positioned, it is moved to the last key in
        the database, otherwise iteration proceeds from the current position.

        Only meaningful for databases opened with `dupsort=True`.
        )r  r  r  rK   MDB_PREV_NODUPr  s      rB   iterprev_nodupzCursor.iterprev_nodupc  s-     {{IIKzz$--tV<<rD   c                    t         j                  | j                  | j                  | j                  |      }| x| _        }| j                  j                  | _        |rgd| j                  _	        d| j                  _	        |t         j                  k7  r2|t         j                  k(  r|t         j                  k(  st        d|      |S r  )rK   r  r  r  r  r  r   r  r  r   r^   r   r  r   )rQ   r  r   vs       rB   r  zCursor._cursor_getq  s      DIItyy"E & a"hh11 !DII !DIIT&&&dkk)bD4H4H.H !1266rD   c           
         t         j                  | j                  |t        |      |t        |      | j                  | j
                  |      }| x| _        }|rgd| j                  _        d| j
                  _        |t         j                  k7  r2|t         j                  k(  r|t         j                  k(  st        d|      |S r  )rK   pymdb_cursor_getr  rz  r  r  r  r   r^   r   r  r   )rQ   r  kr  r   s        rB   _cursor_get_kvzCursor._cursor_get_kv}  s    ""499aQCF#'99dii= & a !DII !DIIT&&&dkk)bD4H4H.H !1266rD   c                 @    | j                  t        j                        S )a  Move to the first key in the database, returning ``True`` on success
        or ``False`` if the database is empty.

        If the database was opened with `dupsort=True` and the key contains
        duplicates, the cursor is positioned on the first value ("duplicate").

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_FIRST
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   	MDB_FIRSTr   s    rB   r  zCursor.first  s     //rD   c                 @    | j                  t        j                        S )a  Move to the first value ("duplicate") for the current key, returning
        ``True`` on success or ``False`` if the database is empty.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_FIRST_DUP
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   MDB_FIRST_DUPr   s    rB   	first_dupzCursor.first_dup  s      2 233rD   c                 @    | j                  t        j                        S )a  Move to the last key in the database, returning ``True`` on success
        or ``False`` if the database is empty.

        If the database was opened with `dupsort=True` and the key contains
        duplicates, the cursor is positioned on the last value ("duplicate").

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_LAST
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   MDB_LASTr   s    rB   r  zCursor.last  s     ..rD   c                 @    | j                  t        j                        S )a  Move to the last value ("duplicate") for the current key, returning
        ``True`` on success or ``False`` if the database is empty.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_LAST_DUP
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   MDB_LAST_DUPr   s    rB   last_dupzCursor.last_dup        1 122rD   c                 @    | j                  t        j                        S )a  Move to the previous element, returning ``True`` on success or
        ``False`` if there is no previous item.

        For databases opened with `dupsort=True`, moves to the previous data
        item ("duplicate") for the current key if one exists, otherwise moves
        to the previous key.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_PREV
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   r  r   s    rB   prevzCursor.prev       ..rD   c                 @    | j                  t        j                        S )a  Move to the previous value ("duplicate") of the current key,
        returning ``True`` on success or ``False`` if there is no previous
        value.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_PREV_DUP
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   r  r   s    rB   prev_dupzCursor.prev_dup  s      1 122rD   c                 @    | j                  t        j                        S )a  Move to the last value ("duplicate") of the previous key, returning
        ``True`` on success or ``False`` if there is no previous key.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_PREV_NODUP
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   r  r   s    rB   
prev_nodupzCursor.prev_nodup        3 344rD   c                 @    | j                  t        j                        S )a  Move to the next element, returning ``True`` on success or ``False``
        if there is no next element.

        For databases opened with `dupsort=True`, moves to the next value
        ("duplicate") for the current key if one exists, otherwise moves to the
        first value of the next key.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_NEXT
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   r  r   s    rB   nextzCursor.next  r  rD   c                 @    | j                  t        j                        S )a  Move to the next value ("duplicate") of the current key, returning
        ``True`` on success or ``False`` if there is no next value.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_NEXT_DUP
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   r  r   s    rB   next_dupzCursor.next_dup  r  rD   c                 @    | j                  t        j                        S )a  Move to the first value ("duplicate") of the next key, returning
        ``True`` on success or ``False`` if there is no next key.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_NEXT_NODUP
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   r  r   s    rB   
next_nodupzCursor.next_nodup  r  rD   c                 L    | j                  t        j                  |t              S )a  Seek exactly to `key`, returning ``True`` on success or ``False`` if
        the exact key was not found. It is an error to :py:meth:`set_key` the
        empty bytestring.

        For databases opened with `dupsort=True`, moves to the first value
        ("duplicate") for the key.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_SET_KEY
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   MDB_SET_KEYr  rQ   r`  s     rB   set_keyzCursor.set_key  s     ""4#3#3S+FFrD   c                 D    | j                  t        j                  ||      S )a  Seek exactly to `(key, value)`, returning ``True`` on success or
        ``False`` if the exact key and value was not found. It is an error
        to :py:meth:`set_key` the empty bytestring.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_GET_BOTH
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   MDB_GET_BOTH)rQ   r`  r  s      rB   set_key_dupzCursor.set_key_dup!  s     ""4#4#4c5AArD   Nc                 p    | j                  t        j                  |t              r| j	                         S |S )zEquivalent to :py:meth:`set_key()`, except :py:meth:`value` is
        returned when `key` is found, otherwise `default`.
        )r  rK   r  r  r  )rQ   r`  r  s      rB   r   z
Cursor.get/  s-     t//kB::<rD   c                 p   rdk  rt        d      s|r|st        d      |rst        d      r!t        j                  }t        j                  }n t        j                  }t        j
                  }t               }t               }|D ]  | j                        s| j                  s#| j                  |       t        | j                         | j                  | j                        | j                  | j                        r`fdt        dt!                    D        }	|r|	D ]  \  }
}|j#                  |
|z           n1|	D ]  \  }
}|j%                  |
|f        n|j%                  f       |r| j                  |       n
| j                  r |rt'        |      S |S )a  Returns an iterable of `(key, value)` 2-tuples containing results
        for each key in the iterable `keys`.

            `keys`:
                Iterable to read keys from.

            `dupdata`:
                If ``True`` and database was opened with `dupsort=True`, read
                all duplicate values for each matching key.

            `dupfixed_bytes`:
                If database was opened with `dupsort=True` and `dupfixed=True`,
                accepts the size of each value, in bytes, and applies an
                optimization reducing the number of database lookups.

            `keyfixed`:
                If `dupfixed_bytes` is set and database key size is fixed,
                setting keyfixed=True will result in this function returning
                a memoryview to the results as a structured array of bytes.
                The structured array can be instantiated by passing the
                memoryview buffer to NumPy:

                .. code-block:: python

                    key_bytes, val_bytes = 4, 8
                    dtype = np.dtype([(f'S{key_bytes}', f'S{val_bytes}}')])
                    arr = np.frombuffer(
                        cur.getmulti(keys, dupdata=True, dupfixed_bytes=val_bytes, keyfixed=True)
                    )

        r   z*dupfixed_bytes must be a positive integer.z1dupdata is required for dupfixed_bytes/key_bytes.z)dupfixed_bytes is required for key_bytes.c              3   2   K   | ]  }||z    f  y wr   rX   ).0idupfixed_bytesr`  r  s     rB   	<genexpr>z"Cursor.getmulti.<locals>.<genexpr>p  s+      I%G !#aN(:";<%Gs   )r   rK   MDB_GET_MULTIPLEMDB_NEXT_MULTIPLEr  r  	bytearraylistr  r  r  r   r  r  r  rangerz  extendr<   
memoryview)rQ   r  r  r  keyfixedget_opnext_opalstgenr  r  r`  r  s      `        @@rB   getmultizCursor.getmulti7  s~   @ nq0EFF'LMMnDEE**F,,G))F''GKfC||C kk$$V,DII&++dii0C++dii0C%I%*1c#h%GI $(+1 !Q ), ),1 #

Aq6 2 ), 

C:.((1- kk 4 a= JrD   c                 p    |s| j                         S | j                  t        j                  |t              S )aH  Seek to the first key greater than or equal to `key`, returning
        ``True`` on success, or ``False`` to indicate key was past end of
        database. Behaves like :py:meth:`first` if `key` is the empty
        bytestring.

        For databases opened with `dupsort=True`, moves to the first value
        ("duplicate") for the key.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_SET_RANGE
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  r  rK   MDB_SET_RANGEr  r  s     rB   	set_rangezCursor.set_range  s.     ::<""4#5#5sKHHrD   c                     | j                  t        j                  ||      }| j                  t        j                         |S )a-  Seek to the first key/value pair greater than or equal to `key`,
        returning ``True`` on success, or ``False`` to indicate that `value` was past the
        last value of `key` or that `(key, value)` was past the end end of database.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_get()
        <http://lmdb.tech/doc/group__mdb.html#ga48df35fb102536b32dfbb801a47b4cb0>`_
        with `MDB_GET_BOTH_RANGE
        <http://lmdb.tech/doc/group__mdb.html#ga1206b2af8b95e7f6b0ef6b28708c9127>`_
        )r  rK   MDB_GET_BOTH_RANGEr  r  )rQ   r`  r  r   s       rB   set_range_dupzCursor.set_range_dup  s9       !8!8#uE 	--.	rD   c                 ,   | j                   }|r|rt        j                  nd}t        j                  | j                  |      }| j
                  xj                  dz  c_        |rt        d|      | j                  t        j                         |dk(  }|S )a  Delete the current element and move to the next, returning ``True``
        on success or ``False`` if the database was empty.

        If `dupdata` is ``True``, delete all values ("duplicates") for the
        current key, otherwise delete only the currently positioned value. Only
        meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_del()
        <http://lmdb.tech/doc/group__mdb.html#ga26a52d3efcfd72e5bf6bd6960bf75f95>`_
        r   r   mdb_cursor_del)
r  rK   r  r0  r  r   r  r   r  r  )rQ   r  r  r   r   s        rB   r  zCursor.delete  s}     KK*1D&&qE$$TYY6BHH1$-r22T112aArD   c                     t         j                  d      }t        j                  | j                  |      }|rt        d|      |d   S )a
  Return the number of values ("duplicates") for the current key.

        Only meaningful for databases opened with `dupsort=True`.

        Equivalent to `mdb_cursor_count()
        <http://lmdb.tech/doc/group__mdb.html#ga4041fd1e1862c6b7d5f10590b86ffbe2>`_
        zsize_t *mdb_cursor_countr   )r=   r   rK   r2  r  r   )rQ   countpr   s      rB   countzCursor.count  sC     *%""499f5+R00ayrD   c           	      <   d}|s|t         j                  z  }|s|t         j                  z  }|rX| j                  j                  j
                  t         j                  z  r|t         j                  z  }n|t         j                  z  }t         j                  | j                  |t        |      |t        |      |      }| j                  xj                  dz  c_        |r |t         j                  k(  ryt        d|      | j                  t         j                          y)a  Store a record, returning ``True`` if it was written, or ``False``
        to indicate the key was already present and `overwrite=False`. On
        success, the cursor is positioned on the key.

        Equivalent to `mdb_cursor_put()
        <http://lmdb.tech/doc/group__mdb.html#ga1f83ccb40011837ff37cc32be01ad91e>`_

            `key`:
                Bytestring key to store.

            `val`:
                Bytestring value to store.

            `dupdata`:
                If ``False`` and database was opened with `dupsort=True`, will return
                ``False`` if the key already has that value.  In other words, this only
                affects the return value.

            `overwrite`:
                If ``False``, do not overwrite the value for the key if it
                exists, just return ``False``. For databases opened with
                `dupsort=True`, ``False`` will always be returned if a
                duplicate key/value pair is inserted, regardless of the setting
                for `overwrite`.

            `append`:
                If ``True``, append the pair to the end of the database without
                comparing its order first. Appending a key that is not greater
                than the highest existing key will fail and return ``False``.
        r   r   Fmdb_cursor_putTrK   r  r  r   r   rx  rn  MDB_APPENDDUPr  pymdb_cursor_putr  rz  r  rZ   r   r  r  )rQ   r`  r  r  r  r<   r   r   s           rB   r  z
Cursor.put  s    > T'''ET)))Exx||""T%5%55+++(""499c3s8S#c(ERq T&&&)2..--.rD   c           
      x   d}|s|t         j                  z  }|s|t         j                  z  }|rX| j                  j                  j
                  t         j                  z  r|t         j                  z  }n|t         j                  z  }d}d}|D ]  \  }}	t         j                  | j                  |t        |      |	t        |	      |      }
| j                  xj                  dz  c_        |dz  }|
sc|
t         j                  k(  r|dz  }|t        d|
       | j                  t         j                          |||z
  fS )aW  Invoke :py:meth:`put` for each `(key, value)` 2-tuple from the
        iterable `items`. Elements must be exactly 2-tuples, they may not be of
        any other type, or tuple subclass.

        Returns a tuple `(consumed, added)`, where `consumed` is the number of
        elements read from the iterable, and `added` is the number of new
        entries added to the database. `added` may be less than `consumed` when
        `overwrite=False`.

            `items`:
                Iterable to read records from.

            `dupdata`:
                If ``True`` and database was opened with `dupsort=True`, add
                pair as a duplicate if the given key already exists. Otherwise
                overwrite any existing matching key.

            `overwrite`:
                If ``False``, do not overwrite the value for the key if it
                exists, just return ``False``. For databases opened with
                `dupsort=True`, ``False`` will always be returned if a
                duplicate key/value pair is inserted, regardless of the setting
                for `overwrite`.

            `append`:
                If ``True``, append records to the end of the database without
                comparing their order first. Appending a key that is not
                greater than the highest existing key will cause corruption.
        r   r   r6  r7  )rQ   itemsr  r  r<   r   addedskippedr`  r  r   s              rB   putmultizCursor.putmulti	  s   < T'''ET)))Exx||""T%5%55+++(JC&&tyy#s3x',c%j%ABHH1$QJE***qLG !1266   	--.ego%%rD   c           	         | j                   j                  t        j                  z  rw| j	                  t        j
                  |t              r<t        | j                         t        | j                        }| j                  d       nd}| j                  ||       |S t        j                  }t        |      }t        j                  | j                  |||t        |      |      }| j                   xj"                  dz  c_        |sy|t        j$                  k7  rt'        d|      | j)                  t        j*                         t        | j                         t        | j                        }t        j                  | j                  |||t        |      d      }| j                   xj"                  dz  c_        |rt'        d|      | j)                  t        j*                         |S )aB  Store a record, returning its previous value if one existed. Returns
        ``None`` if no previous value existed. This uses the best available
        mechanism to minimize the cost of a `set-and-return-previous`
        operation.

        For databases opened with `dupsort=True`, only the first data element
        ("duplicate") is returned if it existed, all data elements are removed
        and the new `(key, data)` pair is inserted.

            `key`:
                Bytestring key to store.

            `value`:
                Bytestring value to store.
        TNr   r6  r   )r   rx  rK   rn  r  r  r  r   r  r   r  r  r  rz  r9  r  r   r  rZ   r   r  r  )rQ   r`  r  oldr   keylenr   s          rB   r  zCursor.replace:	  sl     77>>D,,,""4#3#3S+F		"TYY'D!HHS#J$$S""499c63C%Pq """)2..--.		TYY""499c63C!Lq )2..--.
rD   c                 ~   | j                  t        j                  |t              rt	        | j
                         t        | j
                        }t        j                  | j                  d      }| j                  xj                  dz  c_
        |rt        d|      | j                  t        j                         |S y)a  Fetch a record's value then delete it. Returns ``None`` if no
        previous value existed. This uses the best available mechanism to
        minimize the cost of a `delete-and-return-previous` operation.

        For databases opened with `dupsort=True`, the first data element
        ("duplicate") for the key will be popped.

            `key`:
                Bytestring key to delete.
        r   r   r0  N)r  rK   r  r  r   r  r   r0  r  r   r  r   r  r  )rQ   r`  r@  r   s       rB   r  z
Cursor.popg	  s     t//kBDII#C$$TYY2BHH1$-r22T112J CrD   c                     |s|s| j                         }n| j                  |      }|r"|s| j                          | j                         S |st	        d      S | j                         S )zgHelper for centidb. Please do not rely on this interface, it may be
        removed in future.
        rX   )r  r+  r  r  iterr  )rQ   r  reversefounds       rB   
_iter_fromzCursor._iter_from|	  sU     JJLENN1%E		==?"Bx==?"rD   )TT)FT)TFr   )FNFre  )TTF).rT   rU   rV   rW   rP   r  r  r   r   r   r`  r  r  r  r  __iter__r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r
  r  r  r  r   r(  r+  r.  r  r4  r  r>  r  r  rG  rX   rD   rB   r   r   b  s    Sh-*!&&>307$ H;"=&7";=

04/3/35/35GBM^I$&,1f6&p+Z*#rD   r   re  )]rW   
__future__r   r   r   inspectr   r   	threadingplatformr  r  __builtin__ImportErrorbuiltinsr3   r   __all__rN   strr   	BytesTyper@  rg  r   r   r  localr:   
_CFFI_CDEF_CFFI_CDEF_PATCHED_CFFI_VERIFY_reading_docscffiCONFIG_config_varsr   FFIr=   cdefverifyrK   callbackrC   rO   r   r   r   r    r   r!   r&   r   r   r   r"   r$   r%   r   r   r   r   r   r   r   r   r#   r   r   r   r   r   r  globalsr  objisclass
issubclassr\   r   r   r   r  r   r   r   r   r   r   r
   openr	   r   rX   rD   rB   <module>rd     s  . ' %   	 
 <<7"# 
   > k9c2K#.		VQ	VQm""$ Y__
s
h 
<| t &-7>>#f%|4$g 3L 1GNNCW4XX((
488:DIIj;;|"-#)+O<*67K*L$01E$F!-k!:$01E$F  HD 
]]() *&I &U E # #U  &5 &5 F5 F
E5 E
Iu I
5 =5 =
!e !E !e !" "E % % !e !E E  %  
 tJGI$$&'7??3JsE$:s%?O69JwtS\\23 ( 	/
PF P& 9:/2,$.E
=& E
=P9 9v R,& R,j
i#V i#m1  #"#  Gs#   L+ L; +	L87L8;MM