
    h                    >   d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZmZmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z% dddiiZ&ddddiiiZ'd Z( G d dejR                        Z* G d de+      Z,y)zDatabase level operations.    N)Code)DEFAULT_CODEC_OPTIONS)DBRef)	iteritemsstring_type_unicode)SON)authcommon)_DatabaseAggregationCommandDatabaseChangeStream
Collection)CommandCursor)CollectionInvalidConfigurationErrorInvalidNameOperationFailure)_first_batch)ReadPreference)SONManipulator)DEFAULT_WRITE_CONCERNnamez$regexz	^(?!.*\$)filterz^(?!system\.)c                 P    | st        d      dD ]  }|| v st        d|z         y)z'Check if a database name is valid.
    z(database name cannot be the empty string) .$/\ "z.database names cannot contain the character %rN)r   )r   invalid_chars     S/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/database.py_check_namer&   +   sD     DEE? =4 -/;< = ==    c            	       2    e Zd ZdZ	 	 d: fd	Zd Zed        Zed        Zed        Z	ed        Z
ed	        Zed
        Zed        Z	 	 d:dZd Zd Zd Zd Zd Z	 	 d:dZ	 	 	 d;dZd Zd Zd Zd Zd<dZ	 	 	 d=dZddddej:                  edddf	dZddddedfdZ ddddedfdZ!d  Z"d>d!Z#d>d"Z$	 	 d?d#Z%d<d$Z&	 	 d@d%Z'dAd&Z(dAd'Z)d<d(Z*d>d)Z+d<d*Z,d+ Z-d, Z.d- Z/d. Z0d/ Z1d0 Z2e2Z3d1 Z4	 d<d2Z5dBd3Z6d<d4Z7	 	 dCd5Z8d6 Z9d<d7Z:d8 Z;d9 Z< xZ=S )DDatabasezA Mongo database.
    Nc                    t         t        |   |xs |j                  |xs |j                  |xs |j
                  |xs |j                         t        |t              st        dt        j                        |dk7  rt        |       t        |      | _        || _        g | _        g | _        g | _        g | _        y)aY  Get a database by client and name.

        Raises :class:`TypeError` if `name` is not an instance of
        :class:`basestring` (:class:`str` in python 3). Raises
        :class:`~pymongo.errors.InvalidName` if `name` is not a valid
        database name.

        :Parameters:
          - `client`: A :class:`~pymongo.mongo_client.MongoClient` instance.
          - `name`: The database name.
          - `codec_options` (optional): An instance of
            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
            default) client.codec_options is used.
          - `read_preference` (optional): The read preference to use. If
            ``None`` (the default) client.read_preference is used.
          - `write_concern` (optional): An instance of
            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
            default) client.write_concern is used.
          - `read_concern` (optional): An instance of
            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
            default) client.read_concern is used.

        .. mongodoc:: databases

        .. versionchanged:: 3.2
           Added the read_concern option.

        .. versionchanged:: 3.0
           Added the codec_options, read_preference, and write_concern options.
           :class:`~pymongo.database.Database` no longer returns an instance
           of :class:`~pymongo.collection.Collection` for attribute names
           with leading underscores. You must use dict-style lookups instead::

               db['__my_collection__']

           Not:

               db.__my_collection__
        name must be an instance of z	$externalN)superr)   __init__codec_optionsread_preferencewrite_concernread_concern
isinstancer   	TypeError__name__r&   r   _Database__name_Database__client _Database__incoming_manipulators(_Database__incoming_copying_manipulators _Database__outgoing_manipulators(_Database__outgoing_copying_manipulators)selfclientr   r.   r/   r0   r1   	__class__s          r%   r-   zDatabase.__init__;   s    R 	h&1V115v551V11/F//		1 $,'2';';> ? ? ;tn')$/1,')$/1,r'   c                    t        j                  dt        d       t               fd}|j	                         rL ||d      r| j
                  j                  d|        ||d      r| j                  j                  d|       yy ||d      r| j                  j                  d|        ||d      r| j                  j                  d|       yy)	zAdd a new son manipulator to this database.

        **DEPRECATED** - `add_son_manipulator` is deprecated.

        .. versionchanged:: 3.0
          Deprecated add_son_manipulator.
        z!add_son_manipulator is deprecated   
stacklevelc                 ^    t        | |      j                  t        |      j                  k7  S )z(Test if this method has been overridden.)getattr__func__)instancemethodbases     r%   method_overwrittenz8Database.add_son_manipulator.<locals>.method_overwritten   s0    &""*(gdF.C.L.LM Nr'   transform_incomingr   transform_outgoingN)
warningswarnDeprecationWarningr   	will_copyr8   insertr:   r7   r9   )r;   manipulatorrH   rG   s      @r%   add_son_manipulatorzDatabase.add_son_manipulatory   s     	9(Q	8	N
   "!+/CD44;;A{K!+/CD44;;A{K E "+/CD,,33A{C!+/CD,,33A{C Er'   c                     t        |       S )z**DEPRECATED**: :class:`SystemJS` helper for this :class:`Database`.

        See the documentation for :class:`SystemJS` for more details.
        )SystemJSr;   s    r%   	system_jszDatabase.system_js   s     ~r'   c                     | j                   S )z/The client instance for this :class:`Database`.)r6   rT   s    r%   r<   zDatabase.client   s     }}r'   c                     | j                   S )z#The name of this :class:`Database`.)r5   rT   s    r%   r   zDatabase.name   s     {{r'   c                     t        j                  dt        d       | j                  D cg c]  }|j                  j
                   c}S c c}w )z**DEPRECATED**: All incoming SON manipulators.

        .. versionchanged:: 3.5
          Deprecated.

        .. versionadded:: 2.0
        z.Database.incoming_manipulators() is deprecatedr?   r@   )rK   rL   rM   r7   r=   r4   r;   rP   s     r%   incoming_manipulatorszDatabase.incoming_manipulators   P     	F(Q	8 $(#?#?A %%.. A 	A A   Ac                     t        j                  dt        d       | j                  D cg c]  }|j                  j
                   c}S c c}w )z**DEPRECATED**: All incoming SON copying manipulators.

        .. versionchanged:: 3.5
          Deprecated.

        .. versionadded:: 2.0
        z6Database.incoming_copying_manipulators() is deprecatedr?   r@   )rK   rL   rM   r8   r=   r4   rY   s     r%   incoming_copying_manipulatorsz&Database.incoming_copying_manipulators   P     	N(Q	8 $(#G#GI %%.. I 	I Ir\   c                     t        j                  dt        d       | j                  D cg c]  }|j                  j
                   c}S c c}w )z**DEPRECATED**: All outgoing SON manipulators.

        .. versionchanged:: 3.5
          Deprecated.

        .. versionadded:: 2.0
        z.Database.outgoing_manipulators() is deprecatedr?   r@   )rK   rL   rM   r9   r=   r4   rY   s     r%   outgoing_manipulatorszDatabase.outgoing_manipulators   r[   r\   c                     t        j                  dt        d       | j                  D cg c]  }|j                  j
                   c}S c c}w )z**DEPRECATED**: All outgoing SON copying manipulators.

        .. versionchanged:: 3.5
          Deprecated.

        .. versionadded:: 2.0
        z6Database.outgoing_copying_manipulators() is deprecatedr?   r@   )rK   rL   rM   r:   r=   r4   rY   s     r%   outgoing_copying_manipulatorsz&Database.outgoing_copying_manipulators   r_   r\   c           	          t        | j                  | j                  |xs | j                  |xs | j                  |xs | j
                  |xs | j                        S )aC  Get a clone of this database changing the specified settings.

          >>> db1.read_preference
          Primary()
          >>> from pymongo import ReadPreference
          >>> db2 = db1.with_options(read_preference=ReadPreference.SECONDARY)
          >>> db1.read_preference
          Primary()
          >>> db2.read_preference
          Secondary(tag_sets=None)

        :Parameters:
          - `codec_options` (optional): An instance of
            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
            default) the :attr:`codec_options` of this :class:`Collection`
            is used.
          - `read_preference` (optional): The read preference to use. If
            ``None`` (the default) the :attr:`read_preference` of this
            :class:`Collection` is used. See :mod:`~pymongo.read_preferences`
            for options.
          - `write_concern` (optional): An instance of
            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
            default) the :attr:`write_concern` of this :class:`Collection`
            is used.
          - `read_concern` (optional): An instance of
            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
            default) the :attr:`read_concern` of this :class:`Collection`
            is used.

        .. versionadded:: 3.8
        )r)   r<   r5   r.   r/   r0   r1   )r;   r.   r/   r0   r1   s        r%   with_optionszDatabase.with_options   sW    B %;););'?4+?+?%;););$9(9(9; 	;r'   c                     t        |t              r4| j                  |j                  k(  xr | j                  |j
                  k(  S t        S N)r2   r)   r6   r<   r5   r   NotImplementedr;   others     r%   __eq__zDatabase.__eq__
  s<    eX&MMU\\1 .KK5::-/r'   c                     | |k(   S rg    ri   s     r%   __ne__zDatabase.__ne__  s    5=  r'   c                 <    d| j                   d| j                  dS )Nz	Database(z, ))r6   r5   rT   s    r%   __repr__zDatabase.__repr__  s    %)]]DKK@@r'   c           	      p    |j                  d      rt        d|d|d|d      | j                  |      S )Get a collection of this database by name.

        Raises InvalidName if an invalid collection name is used.

        :Parameters:
          - `name`: the name of the collection to get
        _zDatabase has no attribute z. To access the z collection, use database[z].)
startswithAttributeError__getitem__r;   r   s     r%   __getattr__zDatabase.__getattr__  s?     ??3 48$FG G %%r'   c                     t        | |      S )rs   r   rx   s     r%   rw   zDatabase.__getitem__$  s     $%%r'   c           	      $    t        | |d||||      S )ag  Get a :class:`~pymongo.collection.Collection` with the given name
        and options.

        Useful for creating a :class:`~pymongo.collection.Collection` with
        different codec options, read preference, and/or write concern from
        this :class:`Database`.

          >>> db.read_preference
          Primary()
          >>> coll1 = db.test
          >>> coll1.read_preference
          Primary()
          >>> from pymongo import ReadPreference
          >>> coll2 = db.get_collection(
          ...     'test', read_preference=ReadPreference.SECONDARY)
          >>> coll2.read_preference
          Secondary(tag_sets=None)

        :Parameters:
          - `name`: The name of the collection - a string.
          - `codec_options` (optional): An instance of
            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
            default) the :attr:`codec_options` of this :class:`Database` is
            used.
          - `read_preference` (optional): The read preference to use. If
            ``None`` (the default) the :attr:`read_preference` of this
            :class:`Database` is used. See :mod:`~pymongo.read_preferences`
            for options.
          - `write_concern` (optional): An instance of
            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
            default) the :attr:`write_concern` of this :class:`Database` is
            used.
          - `read_concern` (optional): An instance of
            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
            default) the :attr:`read_concern` of this :class:`Database` is
            used.
        Fr   )r;   r   r.   r/   r0   r1   s         r%   get_collectionzDatabase.get_collection.  s"    N $}o<) 	)r'   c           
          | j                   j                  |      5 }|r|j                  s%|| j                  d|i|      v rt	        d|z        t        | |d||||fd|i|cddd       S # 1 sw Y   yxY w)a&
  Create a new :class:`~pymongo.collection.Collection` in this
        database.

        Normally collection creation is automatic. This method should
        only be used to specify options on
        creation. :class:`~pymongo.errors.CollectionInvalid` will be
        raised if the collection already exists.

        Options should be passed as keyword arguments to this method. Supported
        options vary with MongoDB release. Some examples include:

          - "size": desired initial size for the collection (in
            bytes). For capped collections this size is the max
            size of the collection.
          - "capped": if True, this is a capped collection
          - "max": maximum number of objects if capped (optional)

        See the MongoDB documentation for a full list of supported options by
        server version.

        :Parameters:
          - `name`: the name of the collection to create
          - `codec_options` (optional): An instance of
            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
            default) the :attr:`codec_options` of this :class:`Database` is
            used.
          - `read_preference` (optional): The read preference to use. If
            ``None`` (the default) the :attr:`read_preference` of this
            :class:`Database` is used.
          - `write_concern` (optional): An instance of
            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
            default) the :attr:`write_concern` of this :class:`Database` is
            used.
          - `read_concern` (optional): An instance of
            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
            default) the :attr:`read_concern` of this :class:`Database` is
            used.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): additional keyword arguments will
            be passed as options for the create collection command

        .. versionchanged:: 3.11
           This method is now supported inside multi-document transactions
           with MongoDB 4.4+.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.4
           Added the collation option.

        .. versionchanged:: 3.0
           Added the codec_options, read_preference, and write_concern options.

        .. versionchanged:: 2.2
           Removed deprecated argument: options
        r   )r   sessionzcollection %s already existsTr~   N)r6   _tmp_sessionin_transactionlist_collection_namesr   r   )	r;   r   r.   r/   r0   r1   r~   kwargsss	            r%   create_collectionzDatabase.create_collectionY  s    ~ ]]''0 
	AA a..D66 &~q 7 : :'(F(MNNdD$-}*A45A9?A
	A 
	A 
	As   AA--A6c                 L    | j                   D ]  }|j                  ||      } |S )z%Apply incoming manipulators to `son`.)r7   rI   r;   son
collectionrP   s       r%   _apply_incoming_manipulatorsz%Database._apply_incoming_manipulators  s0    77 	BK00jAC	B
r'   c                 L    | j                   D ]  }|j                  ||      } |S )z-Apply incoming copying manipulators to `son`.)r8   rI   r   s       r%   $_apply_incoming_copying_manipulatorsz-Database._apply_incoming_copying_manipulators  s0    ?? 	BK00jAC	B
r'   c                 N    | j                  ||      }| j                  ||      }|S )zApply manipulators to an incoming SON object before it gets stored.

        :Parameters:
          - `son`: the son object going into the database
          - `collection`: the collection the son object is being saved in
        )r   r   )r;   r   r   s      r%   _fix_incomingzDatabase._fix_incoming  s-     //Z@77ZH
r'   c                     t        | j                        D ]  }|j                  ||      } t        | j                        D ]  }|j                  ||      } |S )zApply manipulators to a SON object as it comes out of the database.

        :Parameters:
          - `son`: the son object coming out of the database
          - `collection`: the collection the son object was saved in
        )reversedr9   rJ   r:   r   s       r%   _fix_outgoingzDatabase._fix_outgoing  se     $D$@$@A 	BK00jAC	B#D$H$HI 	BK00jAC	B
r'   c                 $   | j                   j                  |d      5 }t        | t        |||dudddii      }| j                   j	                  |j
                  |j                  |      ||j                         cddd       S # 1 sw Y   yxY w)	aa	  Perform a database-level aggregation.

        See the `aggregation pipeline`_ documentation for a list of stages
        that are supported.

        Introduced in MongoDB 3.6.

        .. code-block:: python

           # Lists all operations currently running on the server.
           with client.admin.aggregate([{"$currentOp": {}}]) as cursor:
               for operation in cursor:
                   print(operation)

        All optional `aggregate command`_ parameters should be passed as
        keyword arguments to this method. Valid options include, but are not
        limited to:

          - `allowDiskUse` (bool): Enables writing to temporary files. When set
            to True, aggregation stages can write data to the _tmp subdirectory
            of the --dbpath directory. The default is False.
          - `maxTimeMS` (int): The maximum amount of time to allow the operation
            to run in milliseconds.
          - `batchSize` (int): The maximum number of documents to return per
            batch. Ignored if the connected mongod or mongos does not support
            returning aggregate results using a cursor.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`.

        The :meth:`aggregate` method obeys the :attr:`read_preference` of this
        :class:`Database`, except when ``$out`` or ``$merge`` are used, in
        which case  :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`
        is used.

        .. note:: This method does not support the 'explain' option. Please
           use :meth:`~pymongo.database.Database.command` instead.

        .. note:: The :attr:`~pymongo.database.Database.write_concern` of
           this collection is automatically applied to this operation.

        :Parameters:
          - `pipeline`: a list of aggregation pipeline stages
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): See list of options above.

        :Returns:
          A :class:`~pymongo.command_cursor.CommandCursor` over the result
          set.

        .. versionadded:: 3.9

        .. _aggregation pipeline:
            https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline

        .. _aggregate command:
            https://docs.mongodb.com/manual/reference/command/aggregate
        FcloseNcursor
firstBatch   )user_fields)	retryable)r<   r   r   r   _retryable_read
get_cursorget_read_preference_performs_write)r;   pipeliner~   r   r   cmds         r%   	aggregatezDatabase.aggregate  s    v [[%%gU%; 	3q-mXvwd7J%a'89;C ;;.. 7 7 :A!111 / 3		3 	3 	3s   ABBc
                 *    t        | |||||||||	
      S )a  Watch changes on this database.

        Performs an aggregation with an implicit initial ``$changeStream``
        stage and returns a
        :class:`~pymongo.change_stream.DatabaseChangeStream` cursor which
        iterates over changes on all collections in this database.

        Introduced in MongoDB 4.0.

        .. code-block:: python

           with db.watch() as stream:
               for change in stream:
                   print(change)

        The :class:`~pymongo.change_stream.DatabaseChangeStream` iterable
        blocks until the next change document is returned or an error is
        raised. If the
        :meth:`~pymongo.change_stream.DatabaseChangeStream.next` method
        encounters a network error when retrieving a batch from the server,
        it will automatically attempt to recreate the cursor such that no
        change events are missed. Any error encountered during the resume
        attempt indicates there may be an outage and will be raised.

        .. code-block:: python

            try:
                with db.watch(
                        [{'$match': {'operationType': 'insert'}}]) as stream:
                    for insert_change in stream:
                        print(insert_change)
            except pymongo.errors.PyMongoError:
                # The ChangeStream encountered an unrecoverable error or the
                # resume attempt failed to recreate the cursor.
                logging.error('...')

        For a precise description of the resume process see the
        `change streams specification`_.

        :Parameters:
          - `pipeline` (optional): A list of aggregation pipeline stages to
            append to an initial ``$changeStream`` stage. Not all
            pipeline stages are valid after a ``$changeStream`` stage, see the
            MongoDB documentation on change streams for the supported stages.
          - `full_document` (optional): The fullDocument to pass as an option
            to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
            When set to 'updateLookup', the change notification for partial
            updates will include both a delta describing the changes to the
            document, as well as a copy of the entire document that was
            changed from some time after the change occurred.
          - `resume_after` (optional): A resume token. If provided, the
            change stream will start returning changes that occur directly
            after the operation specified in the resume token. A resume token
            is the _id value of a change document.
          - `max_await_time_ms` (optional): The maximum time in milliseconds
            for the server to wait for changes before responding to a getMore
            operation.
          - `batch_size` (optional): The maximum number of documents to return
            per batch.
          - `collation` (optional): The :class:`~pymongo.collation.Collation`
            to use for the aggregation.
          - `start_at_operation_time` (optional): If provided, the resulting
            change stream will only return changes that occurred at or after
            the specified :class:`~bson.timestamp.Timestamp`. Requires
            MongoDB >= 4.0.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `start_after` (optional): The same as `resume_after` except that
            `start_after` can resume notifications after an invalidate event.
            This option and `resume_after` are mutually exclusive.

        :Returns:
          A :class:`~pymongo.change_stream.DatabaseChangeStream` cursor.

        .. versionchanged:: 3.9
           Added the ``start_after`` parameter.

        .. versionadded:: 3.7

        .. mongodoc:: changeStreams

        .. _change streams specification:
            https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst
        r   )
r;   r   full_documentresume_aftermax_await_time_ms
batch_size	collationstart_at_operation_timer~   start_afters
             r%   watchzDatabase.watch  s+    n $(M<9J	#:G 	r'   Fr   Tc                 "   t        |t              rt        ||fg      }|j                  |       | j                  j                  |      5 }|j                  | j                  |||||||	|
|| j                        cddd       S # 1 sw Y   yxY w)zInternal command helper.)r0   parse_write_concern_errorr~   r<   N)r2   r   r	   updater6   r   commandr5   )r;   	sock_infor   slave_okvaluecheckallowable_errorsr/   r.   r0   r   r~   r   r   s                 r%   _commandzDatabase._commandg  s     g{+GU+,-Gv]]''0 	&A$$ +*C}} % &	& 	& 	&s   0BBc                     |&|xr |j                         xs t        j                  }| j                  j	                  ||      5 \  }	}
 | j
                  |	||
|||||fd|i|cddd       S # 1 sw Y   yxY w)aZ  Issue a MongoDB command.

        Send command `command` to the database and return the
        response. If `command` is an instance of :class:`basestring`
        (:class:`str` in python 3) then the command {`command`: `value`}
        will be sent. Otherwise, `command` must be an instance of
        :class:`dict` and will be sent as is.

        Any additional keyword arguments will be added to the final
        command document before it is sent.

        For example, a command like ``{buildinfo: 1}`` can be sent
        using:

        >>> db.command("buildinfo")

        For a command where the value matters, like ``{collstats:
        collection_name}`` we can do:

        >>> db.command("collstats", collection_name)

        For commands that take additional arguments we can use
        kwargs. So ``{filemd5: object_id, root: file_root}`` becomes:

        >>> db.command("filemd5", object_id, root=file_root)

        :Parameters:
          - `command`: document representing the command to be issued,
            or the name of the command (for simple commands only).

            .. note:: the order of keys in the `command` document is
               significant (the "verb" must come first), so commands
               which require multiple keys (e.g. `findandmodify`)
               should use an instance of :class:`~bson.son.SON` or
               a string and kwargs instead of a Python `dict`.

          - `value` (optional): value to use for the command verb when
            `command` is passed as a string
          - `check` (optional): check the response for errors, raising
            :class:`~pymongo.errors.OperationFailure` if there are any
          - `allowable_errors`: if `check` is ``True``, error messages
            in this list will be ignored by error-checking
          - `read_preference` (optional): The read preference for this
            operation. See :mod:`~pymongo.read_preferences` for options.
            If the provided `session` is in a transaction, defaults to the
            read preference configured for the transaction.
            Otherwise, defaults to
            :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
          - `codec_options`: A :class:`~bson.codec_options.CodecOptions`
            instance.
          - `session` (optional): A
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): additional keyword arguments will
            be added to the command document before it is sent

        .. note:: :meth:`command` does **not** obey this Database's
           :attr:`read_preference` or :attr:`codec_options`. You must use the
           `read_preference` and `codec_options` parameters instead.

        .. note:: :meth:`command` does **not** apply any custom TypeDecoders
           when decoding the command response.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.0
           Removed the `as_class`, `fields`, `uuid_subtype`, `tag_sets`,
           and `secondary_acceptable_latency_ms` option.
           Removed `compile_re` option: PyMongo now always represents BSON
           regular expressions as :class:`~bson.regex.Regex` objects. Use
           :meth:`~bson.regex.Regex.try_compile` to attempt to convert from a
           BSON regular expression to a Python regular expression object.
           Added the `codec_options` parameter.

        .. versionchanged:: 2.7
           Added `compile_re` option. If set to False, PyMongo represented BSON
           regular expressions as :class:`~bson.regex.Regex` objects instead of
           attempting to compile BSON regular expressions as Python native
           regular expressions, thus preventing errors for some incompatible
           patterns, see `PYTHON-500`_.

        .. versionchanged:: 2.3
           Added `tag_sets` and `secondary_acceptable_latency_ms` options.
        .. versionchanged:: 2.2
           Added support for `as_class` - the class you want to use for
           the resulting documents

        .. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500

        .. mongodoc:: commands
        Nr~   )_txn_read_preferencer   PRIMARYr6   _socket_for_readsr   )r;   r   r   r   r   r/   r.   r~   r   r   r   s              r%   r   zDatabase.command  s    | " ' JG,H,H,J  9"0"8"8 ]],,* 	K-Bi 4==GXu!&(8/!.K8?KCIK	K 	K 	Ks   A..A7c                      &|xr |j                         xs t        j                   fd}	 j                  j	                  |	|      S )z5Same as command but used for retryable read commands.c           
      <     
j                   ||	fd| iS )Nr~   )r   )r~   serverr   r   r   r   r.   r   r   r/   r;   r   s       r%   _cmdz.Database._retryable_read_command.<locals>._cmd  s=     4==GXu!&(8/!.K8?KCIK Kr'   r   r   r   r6   r   )
r;   r   r   r   r   r/   r.   r~   r   r   s
   ``````` ` r%   _retryable_read_commandz Database._retryable_read_command  s[     " ' JG,H,H,J  9"0"8"8 	K 	K
 }},,/7, 	,r'   c           	         | j                  d|      }|j                  dkD  r|t        ddi fg      }|j                  |       | j                  j                  |d      5 }| j                  |||||      d   }	t        ||	|j                  ||d	u
      cd	d	d	       S t        }
d|v rdt        |d   gi}
t        | j                  j                  d      dz         }ddd|dgiddid|
ig}t        dd|fd|j                  di       fg      }| j                  |||      d   }	t        ||	|j                        S # 1 sw Y   y	xY w)z Internal listCollections helper.z$cmd)r/   r?   )listCollectionsr   r   Fr   )r/   r~   N)r~   explicit_sessionr   z$andutf8   .z$projectz$substrz$namer   )r   optionsz$match)r   zsystem.namespacesr   )r|   max_wire_versionr	   r   r6   r   r   r   address_INDEX_REGEXlenr   encodeget)r;   r   
slave_okayr~   r/   r   collr   tmp_sessionr   matchdblenr   s                r%   _list_collectionszDatabase._list_collections  s    ""O # 5%%)- "~' (CJJv++5 , * :-8sJ$3' ' ) *23 %%%'%,D%8:: : !E6!,x0@!AB		((0478Ey7E22F&G)*, -5!H
 9"H- &**Xr":;= >C ]]9c:>xHF vy/@/@AA5: :s    5D<<Ec                      ||d<   |xr |j                         xs t        j                   fd} j                  j	                  ||      S )a  Get a cursor over the collectons of this database.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `filter` (optional):  A query document to filter the list of
            collections returned from the listCollections command.
          - `**kwargs` (optional): Optional parameters of the
            `listCollections command
            <https://docs.mongodb.com/manual/reference/command/listCollections/>`_
            can be passed as keyword arguments to this method. The supported
            options differ by server version.

        :Returns:
          An instance of :class:`~pymongo.command_cursor.CommandCursor`.

        .. versionadded:: 3.6
        r   c                 2     j                   ||| fdiS )Nr/   )r   )r~   r   r   r   r   	read_prefr;   s       r%   r   z'Database.list_collections.<locals>._cmd4  s/    )4)):w@I r'   r   )r;   r~   r   r   r   r   s   `  ` @r%   list_collectionszDatabase.list_collections  s^    & %F8@'">">"@ /&.. 		
 }},,)W& 	&r'   c                     |d|d<   n4t        j                  d|       ||d<   |rt        |      dk(  r	d|v rd|d<    | j                  dd|i|D cg c]  }|d   	 c}S c c}w )a  Get a list of all the collection names in this database.

        For example, to list all non-system collections::

            filter = {"name": {"$regex": r"^(?!system\.)"}}
            db.list_collection_names(filter=filter)

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `filter` (optional):  A query document to filter the list of
            collections returned from the listCollections command.
          - `**kwargs` (optional): Optional parameters of the
            `listCollections command
            <https://docs.mongodb.com/manual/reference/command/listCollections/>`_
            can be passed as keyword arguments to this method. The supported
            options differ by server version.

        .. versionchanged:: 3.8
           Added the ``filter`` and ``**kwargs`` parameters.

        .. versionadded:: 3.6
        TnameOnlyr   r   r   r~   rm   )r   validate_is_mappingr   r   )r;   r~   r   r   results        r%   r   zDatabase.list_collection_names<  s    0 >!%F: &&x8%F8c&kQ.6V3C%)z" 4d33NGNvNP v P 	P Ps   A"c                     t        j                  dt        d       |ri nt        } | j                  d|dd|D cg c]  }|d   	 c}S c c}w )a  **DEPRECATED**: Get a list of all the collection names in this
        database.

        :Parameters:
          - `include_system_collections` (optional): if ``False`` list
            will not include system collections (e.g ``system.indexes``)
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.7
           Deprecated. Use :meth:`list_collection_names` instead.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        zBcollection_names is deprecated. Use list_collection_names instead.r?   r@   T)r~   r   r   rm   )rK   rL   rM   _SYSTEM_FILTERr   )r;   include_system_collectionsr~   kwsr   s        r%   collection_nameszDatabase.collection_namesa  so    " 	 7(Q	8 /bN3d33 JG=AJEHJK v K 	K Ks   Ac           
         |}t        |t              r|j                  }t        |t              st	        dt        j
                        | j                  j                  | j                  |       | j                  j                  |      5 }| j                  |dt        |      ddg| j                  |      d|      cddd       S # 1 sw Y   yxY w)a  Drop a collection.

        :Parameters:
          - `name_or_collection`: the name of a collection to drop or the
            collection object itself
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. note:: The :attr:`~pymongo.database.Database.write_concern` of
           this database is automatically applied to this operation when using
           MongoDB >= 3.4.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.4
           Apply this database's write concern automatically to this operation
           when connected to MongoDB >= 3.4.

        *name_or_collection must be an instance of dropzns not found   T)r   r   r0   r   r~   N)r2   r   r   r   r3   r4   r6   _purge_indexr5   _socket_for_writesr   r   _write_concern_for)r;   name_or_collectionr~   r   r   s        r%   drop_collectionzDatabase.drop_collectionz  s    * "dJ'99D$,0;0D0DG H H 	""4;;5]]--g6 	!)==6$"0"!5"55g>*. ! !	! 	! 	!s   2CCc                    |}t        |t              r|j                  }t        |t              st	        dt        j
                  d      t        dt        |      fd|fd|fg      }|||d<   | j                  ||      }d}	d	|v r=|d	   }
|
j                  d
      dk7  s|
j                  d      dk7  rt        |d|
      d|v rot        |d         D ]]  \  }}d	|v r>|d	   }
|
j                  d
      dk7  s|
j                  d      dk7  s8t        |d|
      |j                  dd      r[d}	 n n|j                  dd      sd}	|	st        |d|      |S )aw  Validate a collection.

        Returns a dict of validation info. Raises CollectionInvalid if
        validation fails.

        See also the MongoDB documentation on the `validate command`_.

        :Parameters:
          - `name_or_collection`: A Collection object or the name of a
            collection to validate.
          - `scandata`: Do extra checks beyond checking the overall
            structure of the collection.
          - `full`: Have the server do a more thorough scan of the
            collection. Use with `scandata` for a thorough scan
            of the structure of the collection and the individual
            documents.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `background` (optional): A boolean flag that determines whether
            the command runs in the background. Requires MongoDB 4.4+.

        .. versionchanged:: 3.11
           Added ``background`` parameter.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. _validate command: https://docs.mongodb.com/manual/reference/command/validate/
        r   z or Collectionvalidatescandatafull
backgroundr~   Tr   	exceptionr   corruptz
 invalid: rawvalidF)r2   r   r   r   r3   r4   r	   r   r   findr   r   r   )r;   r   r   r   r~   r   r   r   r   r   infort   ress                r%   validate_collectionzDatabase.validate_collection  s   @ "dJ'99D$,2=2F2FI J J J/)D># $ ! *Cc73v(#Dyy%+tyy/Cr/I'D$(GHHf_#F5M2 	3s?x=D		+."4 IIi0B6/8<d1D E E%0!E	 GU+E#f$EFFr'   c                    t        dd|fg      }| j                  j                  |      5 }|j                  dk\  r<| j                  j                  j                  ||| j                  |      cddd       S |rddini }t        |dd|d	d| j                  t        j                  || j                  j                  
      cddd       S # 1 sw Y   yxY w)
zHelper for running $currentOp.)	currentOpr   z$all   )r.   r~   NTadminz$cmd.sys.inprogr   )r	   r6   r   r   r   r   r.   r   r   r   r<   _event_listeners)r;   include_allr~   r   r   specs         r%   _current_opzDatabase._current_op  s    #fk%:;<]]--g6 
	B)))Q.}}**33s$2D2D# 4 %
	B 
	B *5~"#Iw8I$("dD4F4F$2$:$:C$(KK$@$@B
	B 
	B 
	Bs   AC7ACCc                 ^    t        j                  dt        d       | j                  ||      S )af  **DEPRECATED**: Get information on operations currently running.

        Starting with MongoDB 3.6 this helper is obsolete. The functionality
        provided by this helper is available in MongoDB 3.6+ using the
        `$currentOp aggregation pipeline stage`_, which can be used with
        :meth:`aggregate`. Note that, while this helper can only return
        a single document limited to a 16MB result, :meth:`aggregate`
        returns a cursor avoiding that limitation.

        Users of MongoDB versions older than 3.6 can use the `currentOp command`_
        directly::

          # MongoDB 3.2 and 3.4
          client.admin.command("currentOp")

        Or query the "inprog" virtual collection::

          # MongoDB 2.6 and 3.0
          client.admin["$cmd.sys.inprog"].find_one()

        :Parameters:
          - `include_all` (optional): if ``True`` also list currently
            idle operations in the result
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.9
           Deprecated.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. _$currentOp aggregation pipeline stage: https://docs.mongodb.com/manual/reference/operator/aggregation/currentOp/
        .. _currentOp command: https://docs.mongodb.com/manual/reference/command/currentOp/
        zFcurrent_op() is deprecated. See the documentation for more informationr?   r@   )rK   rL   rM   r   )r;   r   r~   s      r%   
current_opzDatabase.current_op  s0    H 	 )(Q	8 W55r'   c                 X    | j                  dd|      }|d   dk\  r|d   dk  sJ |d   S )a~  Get the database's current profiling level.

        Returns one of (:data:`~pymongo.OFF`,
        :data:`~pymongo.SLOW_ONLY`, :data:`~pymongo.ALL`).

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. mongodoc:: profiling
        profiler   r   wasr   r?   )r   )r;   r~   r   s      r%   profiling_levelzDatabase.profiling_level$  s?     iW=e}!fUmq&888e}r'   c                     t        |t              r
|dk  s|dkD  rt        d      |t        |t              st        d      || j	                  d|||       y| j	                  d||       y)	a  Set the database's profiling level.

        :Parameters:
          - `level`: Specifies a profiling level, see list of possible values
            below.
          - `slow_ms`: Optionally modify the threshold for the profile to
            consider a query or operation.  Even if the profiler is off queries
            slower than the `slow_ms` level will get written to the logs.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        Possible `level` values:

        +----------------------------+------------------------------------+
        | Level                      | Setting                            |
        +============================+====================================+
        | :data:`~pymongo.OFF`       | Off. No profiling.                 |
        +----------------------------+------------------------------------+
        | :data:`~pymongo.SLOW_ONLY` | On. Only includes slow operations. |
        +----------------------------+------------------------------------+
        | :data:`~pymongo.ALL`       | On. Includes all operations.       |
        +----------------------------+------------------------------------+

        Raises :class:`ValueError` if level is not one of
        (:data:`~pymongo.OFF`, :data:`~pymongo.SLOW_ONLY`,
        :data:`~pymongo.ALL`).

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. mongodoc:: profiling
        r   r?   z*level must be one of (OFF, SLOW_ONLY, ALL)Nzslow_ms must be an integerr   )slowmsr~   r   )r2   int
ValueErrorr3   r   )r;   levelslow_msr~   s       r%   set_profiling_levelzDatabase.set_profiling_level8  sn    B %%eaiIJJz'3'?899LLE'7LKLLE7L;r'   c                 >    t        | d   j                  |            S )a!  Returns a list containing current profiling information.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. mongodoc:: profiling
        zsystem.profiler   )listr   )r;   r~   s     r%   profiling_infozDatabase.profiling_infod  s#     D)*///@AAr'   c                    t        j                  dt        d       | j                  d      }|j	                  dd      }|y|j                  d      r4| j                  j                  }|r| j                  j                  ||       |S )	a:  **DEPRECATED**: Get the error if one occurred on the last operation.

        This method is obsolete: all MongoDB write operations (insert, update,
        remove, and so on) use the write concern ``w=1`` and report their
        errors by default.

        .. versionchanged:: 2.8
           Deprecated.
        zDatabase.error() is deprecatedr?   r@   getlasterrorerr Nz
not master)	rK   rL   rM   r   r   ru   r6   primary_handle_getlasterror)r;   error	error_msgr  s       r%   r  zDatabase.errorr  s|     	6(Q	8 ^,IIeR(	- mm++G227IFr'   c                 \    t        j                  dt        d       | j                  d      S )al  **DEPRECATED**: Get status information from the last operation.

        This method is obsolete: all MongoDB write operations (insert, update,
        remove, and so on) use the write concern ``w=1`` and report their
        errors by default.

        Returns a SON object with status information.

        .. versionchanged:: 2.8
           Deprecated.
        zlast_status() is deprecatedr?   r@   r  rK   rL   rM   r   rT   s    r%   last_statuszDatabase.last_status  s)     	3(Q	8 ||N++r'   c                     t        j                  dt        d       | j                  d      }|j	                  dd      y|S )a  **DEPRECATED**: Get the most recent error on this database.

        This method is obsolete: all MongoDB write operations (insert, update,
        remove, and so on) use the write concern ``w=1`` and report their
        errors by default.

        Only returns errors that have occurred since the last call to
        :meth:`reset_error_history`. Returns None if no such errors have
        occurred.

        .. versionchanged:: 2.8
           Deprecated.
        zprevious_error() is deprecatedr?   r@   getpreverrorr  r   N)rK   rL   rM   r   r   )r;   r  s     r%   previous_errorzDatabase.previous_error  sA     	6(Q	8 ^,99UA&r'   c                 ^    t        j                  dt        d       | j                  d       y)a  **DEPRECATED**: Reset the error history of this database.

        This method is obsolete: all MongoDB write operations (insert, update,
        remove, and so on) use the write concern ``w=1`` and report their
        errors by default.

        Calls to :meth:`previous_error` will only return errors that have
        occurred since the most recent call to this method.

        .. versionchanged:: 2.8
           Deprecated.
        z#reset_error_history() is deprecatedr?   r@   
reseterrorNr  rT   s    r%   reset_error_historyzDatabase.reset_error_history  s&     	;(Q	8 	\"r'   c                     | S rg   rm   rT   s    r%   __iter__zDatabase.__iter__  s    r'   c                     t        d      )Nz!'Database' object is not iterable)r3   rT   s    r%   __next__zDatabase.__next__  s    ;<<r'   c                 0    | j                   dk(  r|ryy|ryy)z/Return the default user role for this database.r   readAnyDatabaserootreaddbOwner)r   )r;   	read_onlys     r%   _default_rolezDatabase._default_role  s     99( r'   c                    i }|s|r3d|vr/t        j                  dt               | j                  |      g|d<   |rt        j                  dt               |d|v rt	        d      ||d<   | j
                  j                  r/| j
                  j                  r| j
                  j                  |d<   |j                  |       |rd	}nd
} | j                  ||fd|i| y)zCUse a command to create (if create=True) or modify a user.
        roleszZCreating a user with the read_only option or without roles is deprecated in MongoDB >= 2.6zIThe read_only option is deprecated in MongoDB >= 2.6, use 'roles' insteadNdigestPasswordzzThe digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option.pwdwriteConcern
createUser
updateUserr~   )
rK   rL   rM   r'  r   r0   acknowledgeddocumentr   r   )	r;   creater   passwordr&  r~   r   optscommand_names	            r%   _create_or_update_userzDatabase._create_or_update_user  s     G6$9MM #$68 "//	:;DMMM 89KM 6)( *D E E #DK **t/A/A/J/J#'#5#5#>#>D F'L'L\4AADAr'   c                 P   t        j                  dt        d       t        |t              st        dt        j                        |Et        |t              st        dt        j                        t        |      dk(  rt        d      |%t        j                  d	|      }d
|v rt        d      	 | j                  d||      } | j                  |d    |||fd|i| y# t        $ r3}|j                  dk(  r | j                  d|||fd|i| n Y d}~yd}~ww xY w)ab	  **DEPRECATED**: Create user `name` with password `password`.

        Add a new user with permissions for this :class:`Database`.

        .. note:: Will change the password if user `name` already exists.

        .. note:: add_user is deprecated and will be removed in PyMongo
          4.0. Starting with MongoDB 2.6 user management is handled with four
          database commands, createUser_, usersInfo_, updateUser_, and
          dropUser_.

          To create a user::

            db.command("createUser", "admin", pwd="password", roles=["root"])

          To create a read-only user::

            db.command("createUser", "user", pwd="password", roles=["read"])

          To change a password::

            db.command("updateUser", "user", pwd="newpassword")

          Or change roles::

            db.command("updateUser", "user", roles=["readWrite"])

        .. _createUser: https://docs.mongodb.com/manual/reference/command/createUser/
        .. _usersInfo: https://docs.mongodb.com/manual/reference/command/usersInfo/
        .. _updateUser: https://docs.mongodb.com/manual/reference/command/updateUser/
        .. _dropUser: https://docs.mongodb.com/manual/reference/command/createUser/

        .. warning:: Never create or modify users over an insecure network without
          the use of TLS. See :doc:`/examples/tls` for more information.

        :Parameters:
          - `name`: the name of the user to create
          - `password` (optional): the password of the user to create. Can not
            be used with the ``userSource`` argument.
          - `read_only` (optional): if ``True`` the user will be read only
          - `**kwargs` (optional): optional fields for the user document
            (e.g. ``userSource``, ``otherDBRoles``, or ``roles``). See
            `<http://docs.mongodb.org/manual/reference/privilege-documents>`_
            for more information.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.7
           Added support for SCRAM-SHA-256 users with MongoDB 4.0 and later.

        .. versionchanged:: 3.6
           Added ``session`` parameter. Deprecated add_user.

        .. versionchanged:: 2.5
           Added kwargs support for optional fields introduced in MongoDB 2.4

        .. versionchanged:: 2.2
           Added support for read only users
        zoadd_user is deprecated and will be removed in PyMongo 4.0. Use db.command with createUser or updateUser insteadr?   r@   r+   N password must be an instance of r   zpassword can't be emptyr&  r)  z(Can not use read_only and roles together	usersInfor   usersr~      T)rK   rL   rM   r2   r   r3   r4   r   r  r   validate_booleanr   r   r5  r   code)r;   r   r2  r&  r~   r   uinfoexcs           r%   add_userzDatabase.add_user  s`   z 	  !3	C $,0;0D0DG H Hh44?4H4H!K L L8}! !:;; //YGI& ( *H I I	LLdGLDE'D''7^#dHi++#)+   	 xx2~+++$)P=DPHNP P		s   80C) )	D%2)D  D%c                    t        j                  dt        d       t        d|fg      }| j                  j
                  r/| j                  j                  r| j                  j                  |d<   | j                  ||       y)a[  **DEPRECATED**: Remove user `name` from this :class:`Database`.

        User `name` will no longer have permissions to access this
        :class:`Database`.

        .. note:: remove_user is deprecated and will be removed in PyMongo
          4.0. Use the dropUser command instead::

            db.command("dropUser", "user")

        :Parameters:
          - `name`: the name of the user to remove
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.6
           Added ``session`` parameter. Deprecated remove_user.
        zbremove_user is deprecated and will be removed in PyMongo 4.0. Use db.command with dropUser insteadr?   r@   dropUserr,  r   N)rK   rL   rM   r	   r0   r/  r0  r   )r;   r   r~   r   s       r%   remove_userzDatabase.remove_user[  sr    & 	  !3	C J%&'**t/A/A/J/J"&"4"4"="=CS'*r'   c                 f   |,t        |t              st        dt        j                        |,t        |t              st        dt        j                        |,t        |t              st        dt        j                        t	        j
                  d|       t	        j                         }t        |      D ]#  \  }}t	        j                  ||      \  }	}
|
||	<   % t        j                  |||||| j                        }| j                  j                  | j                  |d       y)a  **DEPRECATED**: Authenticate to use this database.

        .. warning:: Starting in MongoDB 3.6, calling :meth:`authenticate`
          invalidates all existing cursors. It may also leave logical sessions
          open on the server for up to 30 minutes until they time out.

        Authentication lasts for the life of the underlying client
        instance, or until :meth:`logout` is called.

        Raises :class:`TypeError` if (required) `name`, (optional) `password`,
        or (optional) `source` is not an instance of :class:`basestring`
        (:class:`str` in python 3).

        .. note::
          - This method authenticates the current connection, and
            will also cause all new :class:`~socket.socket` connections
            in the underlying client instance to be authenticated automatically.

          - Authenticating more than once on the same database with different
            credentials is not supported. You must call :meth:`logout` before
            authenticating with new credentials.

          - When sharing a client instance between multiple threads, all
            threads will share the authentication. If you need different
            authentication profiles for different purposes you must use
            distinct client instances.

        :Parameters:
          - `name`: the name of the user to authenticate. Optional when
            `mechanism` is MONGODB-X509 and the MongoDB server version is
            >= 3.4.
          - `password` (optional): the password of the user to authenticate.
            Not used with GSSAPI or MONGODB-X509 authentication.
          - `source` (optional): the database to authenticate on. If not
            specified the current database is used.
          - `mechanism` (optional): See :data:`~pymongo.auth.MECHANISMS` for
            options. If no mechanism is specified, PyMongo automatically uses
            MONGODB-CR when connected to a pre-3.0 version of MongoDB,
            SCRAM-SHA-1 when connected to MongoDB 3.0 through 3.6, and
            negotiates the mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) when
            connected to MongoDB 4.0+.
          - `authMechanismProperties` (optional): Used to specify
            authentication mechanism specific options. To specify the service
            name for GSSAPI authentication pass
            ``authMechanismProperties='SERVICE_NAME:<service name>'``.
            To specify the session token for MONGODB-AWS authentication pass
            ``authMechanismProperties='AWS_SESSION_TOKEN:<session token>'``.

        .. versionchanged:: 3.7
           Added support for SCRAM-SHA-256 with MongoDB 4.0 and later.

        .. versionchanged:: 3.5
           Deprecated. Authenticating multiple users conflicts with support for
           logical sessions in MongoDB 3.6. To authenticate as multiple users,
           create multiple instances of MongoClient.

        .. versionadded:: 2.8
           Use SCRAM-SHA-1 with MongoDB 3.0 and later.

        .. versionchanged:: 2.5
           Added the `source` and `mechanism` parameters. :meth:`authenticate`
           now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
           authentication fails due to invalid credentials or configuration
           issues.

        .. mongodoc:: authenticate
        r+   r7  zsource must be an instance of 	mechanismT)connect)r2   r   r3   r4   r   validate_auth_mechanism_CaseInsensitiveDictionaryr   validate_auth_optionr
   _build_credentials_tupler   r<   _cache_credentials)r;   r   r2  sourcerD  r   validated_optionsoptionr   
normalizedvalcredentialss               r%   authenticatezDatabase.authenticatew  s7   J Jt[$A0;0D0DG H H
8[(I0;0D0DG H Hj&E0;0D0DG H H&&{I>"==?&v. 	0MFE$99&%HOJ,/j)	0 33II 	&&II 	' 	
 r'   c                     t        j                  dt        d       | j                  j	                  | j
                         y)a  **DEPRECATED**: Deauthorize use of this database.

        .. warning:: Starting in MongoDB 3.6, calling :meth:`logout`
          invalidates all existing cursors. It may also leave logical sessions
          open on the server for up to 30 minutes until they time out.
        zDatabase.logout() is deprecatedr?   r@   N)rK   rL   rM   r<   _purge_credentialsr   rT   s    r%   logoutzDatabase.logout  s0     	7(Q	8 	&&tyy1r'   c                 B   t        |t              st        dt        |      z        |j                  ?|j                  | j
                  k7  r&t        d|j                  d| j
                  d       | |j                     j                  d|j                  ifd|i|S )a+  Dereference a :class:`~bson.dbref.DBRef`, getting the
        document it points to.

        Raises :class:`TypeError` if `dbref` is not an instance of
        :class:`~bson.dbref.DBRef`. Returns a document, or ``None`` if
        the reference does not point to a valid document.  Raises
        :class:`ValueError` if `dbref` has a database specified that
        is different from the current database.

        :Parameters:
          - `dbref`: the reference
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): any additional keyword arguments
            are the same as the arguments to
            :meth:`~pymongo.collection.Collection.find`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        zcannot dereference a %sz?trying to dereference a DBRef that points to another database (z not rp   _idr~   )
r2   r   r3   typedatabaser5   r  r   find_oneid)r;   dbrefr~   r   s       r%   dereferencezDatabase.dereference  s    * %'5UCDD>>%%..DKK*G?D~~?C{{L M M /tE$$%..EHH:'.:28: 	:r'   c                     t        j                  dt        d       t        |t              st	        |      }| j                  d||      }|j                  dd      S )a  **DEPRECATED**: Evaluate a JavaScript expression in MongoDB.

        :Parameters:
          - `code`: string representation of JavaScript code to be
            evaluated
          - `args` (optional): additional positional arguments are
            passed to the `code` being evaluated

        .. warning:: the eval command is deprecated in MongoDB 3.0 and
          will be removed in a future server version.
        zDatabase.eval() is deprecatedr?   r@   z$eval)argsretvalN)rK   rL   rM   r2   r   r   r   )r;   r<  r^  r   s       r%   evalzDatabase.eval  sR     	5(Q	8 $%:Dgt$7zz(D))r'   c                 v    t        d| j                  d| j                  j                  j                  d      )zJThis is only here so that some API misusages are easier to debug.
        z='Database' object is not callable. If you meant to call the 'z' method on a 'z5' object it is failing because no such method exists.)r3   r5   r6   r=   r4   )r;   r^  r   s      r%   __call__zDatabase.__call__  s4      !KK)@)@)I)IK L 	Lr'   )NNNN)NNNNNrg   )	NNNNNNNNN)NN)TN)FFNN)FN)NNN)NNNDEFAULT)>r4   
__module____qualname____doc__r-   rQ   propertyrU   r<   r   rZ   r^   ra   rc   re   rk   rn   rq   ry   rw   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  r  r  r   nextr'  r5  r?  rB  rQ  rT  r\  r`  rb  __classcell__)r=   s   @r%   r)   r)   7   s>    JN26<2|D6       A A I I A A I I @D6:&;P!A&& HL8<))V 59>B59IAV	A3F EIAEFJZx 5:$"&8N8N4#+0$	&0 &'d!%t3TeKN 67d!%t3T, $BL&@#PJ ;?!%K2%!P AE'+IVB'6R(*<XB2,",#$= D! >B"BH\|+8 04,5bH2:<**Lr'   r)   c                   @    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zy
)rS   zE**DEPRECATED**: Helper class for dealing with stored JavaScript.
    c                     t        j                  dt        d       |j                  j                  s+|j
                  j                  |j                  t              }t        j                  | d|       y)z~**DEPRECATED**: Get a system js helper for the database `database`.

        SystemJS will be removed in PyMongo 4.0.
        zSystemJS is deprecatedr?   r@   )r0   _dbN)rK   rL   rM   r0   r/  r<   get_databaser   r   object__setattr__)r;   rX  s     r%   r-   zSystemJS.__init__(  sa    
 	.(Q	8 %%2233-B 4 DH 	41r'   c                     | j                   j                  j                  j                  d|i|t	        |      dd       y )NrV  )rV  r   T)rl  systemjsreplace_oner   r;   r   r<  s      r%   ro  zSystemJS.__setattr__6  s3    &&DM4$t*=t	Er'   c                 (    | j                  ||       y rg   )ro  rt  s      r%   __setitem__zSystemJS.__setitem__:  s    t$r'   c                 f    | j                   j                  j                  j                  d|i       y )NrV  )rl  rq  rr  
delete_onerx   s     r%   __delattr__zSystemJS.__delattr__=  s"    %%udm4r'   c                 &    | j                  |       y rg   )ry  rx   s     r%   __delitem__zSystemJS.__delitem__@  s    r'   c                       fdS )Nc                  X     j                   j                  t        ddi      g|  S )Nz8function() { return this[name].apply(this, arguments); }r   )scope)rl  r`  r   )r^  r   r;   s    r%   <lambda>z&SystemJS.__getattr__.<locals>.<lambda>D  s;    ]TXX]]4 1F 8>tn,F N IMN r'   rm   rx   s   ``r%   ry   zSystemJS.__getattr__C  s    N 	Nr'   c                 $    | j                  |      S rg   )ry   rx   s     r%   rw   zSystemJS.__getitem__I  s    %%r'   c                     | j                   j                  j                  j                  dg      D cg c]  }|d   	 c}S c c}w )zAGet a list of the names of the functions stored in this database.rV  )
projection)rl  rq  rr  r   )r;   xs     r%   r
  zSystemJS.listL  s8    "&((//"4"4"9"9eW"9"MNQ%NNNs   AN)r4   rd  re  rf  r-   ro  rv  ry  r{  ry   rw   r
  rm   r'   r%   rS   rS   $  s2    2E%5N&Or'   rS   )-rf  rK   	bson.coder   bson.codec_optionsr   
bson.dbrefr   bson.py3compatr   r   r   bson.sonr	   pymongor
   r   pymongo.aggregationr   pymongo.change_streamr   pymongo.collectionr   pymongo.command_cursorr   pymongo.errorsr   r   r   r   pymongo.messager   pymongo.read_preferencesr   pymongo.son_manipulatorr   pymongo.write_concernr   r   r   r&   
BaseObjectr)   rn  rS   rm   r'   r%   <module>r     s    !   4  ; ;    ; 6 ) 0. . ) 3 2 7 <01Vh0@%ABC	=jLv   jLZ/*Ov *Or'   