o Sb@spdZddlmZmZmZmZmZmZmZm Z m Z m Z m Z m Z mZddlmZmZddlmZddlmZddlmZddlmZmZddlmZdd lmZdd lm Z dd l!m"Z"dd l#m$Z$m%Z%m&Z&dd l'm(Z(m)Z)ddl*m+Z+m,Z,ddl-m.Z.m/Z/m0Z0ddZ1erddlZ2ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:e dee;efdZdS)zDatabase level operations.) TYPE_CHECKINGAnyDictGenericListMappingMutableMappingNoReturnOptionalSequenceTypeVarUnioncast)DEFAULT_CODEC_OPTIONS CodecOptions)DBRef)SON) Timestamp)_csotcommon)_DatabaseAggregationCommandDatabaseChangeStream Collection) CommandCursor)_ecc_coll_name_ecoc_coll_name_esc_coll_name)CollectionInvalid InvalidName)ReadPreference _ServerMode) _CollationIn _DocumentType _PipelinecCs.|stddD] }||vrtd|qdS)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 )nameZ invalid_charr.7/tmp/pip-target-onvjaxws/lib/python/pymongo/database.py _check_name/s r0N) ClientSession) MongoClient) ReadConcern) WriteConcern_CodecDocumentType)boundcseZdZdZ    dadddedeedeeded d ed d dffd d Ze dbddZ e d efddZ    dadeedeeded d ed d df ddZ de d efddZde d efddZd efddZddZded eefdd Zded d!fd"d#Z    dadedeedeeded d ed d eef d$d%Zej      &dcdedeedeeded d ed d'ed(d)eed*e d eefd+d,Z ddd-ed'ed(d*e d eefd.d/Z           ded-eed0eed1eeee fd2eed3eed4ee d5ee!d'ed(d6eeee fd7ee d8eed e"efd9d:Z#d;d&de$j%e&ddZ'ej ; &     dfd?e(ee)ee ffd@e dAedBee*e(eefdeeddCd'ed(d7ee d*e d e+fdDdEZ,d;d&dde&dfdFdGZ-dHdIZ.   dgd'ed(dJeeee fd7ee d*e d ee/ee ff dKdLZ0   dgd'ed(dJeeee fd7ee d*e d e1ef dMdNZ2dhdOdPZ3ej   dgdQe(eefd'ed(d7ee dReeee fd e/ee ff dSdTZ4 < <   didQe(eefdUedVed'ed(dWeed7ee d e/ee ffdXdYZ5dZ6d e7fdZd[Z8e8Z9d e7fd\d]Z:  dhd^e;d'ed(d7ee d*e d eef d_d`Z<Z=S)jDatabasezA Mongo database.NclientMongoClient[_DocumentType]r- codec_optionsread_preference write_concernr4 read_concernr3returncsjtt||p |j|p |j|p|j|p|jt|ts t d|dkr(t |||_ ||_ |j j|_dS)a 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. .. seealso:: The MongoDB documentation on `databases `_. .. versionchanged:: 4.0 Removed the eval, system_js, error, last_status, previous_error, reset_error_history, authenticate, logout, collection_names, current_op, add_user, remove_user, profiling_level, set_profiling_level, and profiling_info methods. See the :ref:`pymongo4-migration-guide`. .. 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__ zname must be an instance of strz $externalN)superr7__init__r:r;r<r= isinstancestr TypeErrorr0_Database__name_Database__clientoptionstimeout_timeout)selfr8r-r:r;r<r= __class__r.r/r@Gs 7 zDatabase.__init__cC|jS)z/The client instance for this :class:`Database`.)rErIr.r.r/r8zDatabase.clientcCrL)z#The name of this :class:`Database`.)rDrMr.r.r/r-rNz Database.namezDatabase[_DocumentType]cCs.t|j|j|p |j|p |j|p|j|p|jS)aCGet 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 )r7r8rDr:r;r<r=)rIr:r;r<r=r.r.r/ with_optionss&zDatabase.with_optionsothercCs&t|tr|j|jko|j|jkStSN)rAr7rEr8rDr-NotImplementedrIrPr.r.r/__eq__s zDatabase.__eq__cCs ||k SrQr.rSr.r.r/__ne__s zDatabase.__ne__cCst|j|jfSrQ)hashrErDrMr.r.r/__hash__zDatabase.__hash__cCsd|j|jfS)NzDatabase(%r, %r))rErDrMr.r.r/__repr__rXzDatabase.__repr__cCs&|drtd|||f||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 _zLDatabase has no attribute %r. To access the %s collection, use database[%r].) startswithAttributeError __getitem__rIr-r.r.r/ __getattr__s  zDatabase.__getattr__zCollection[_DocumentType]cCs t||S)rZrr_r.r.r/r^s zDatabase.__getitem__cCst||d||||S)agGet 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)rIr-r:r;r<r=r.r.r/get_collections-zDatabase.get_collectionTsessionr1 check_existskwargsc Ks|d} | s$|jjjr$|jjjjr$|jjjjd|j|f} | |d<| r,td| |d} | r9td| |j |0} |rX| rG| j sX||j d|i| dvrXt d|t ||d||||fd| i|Wd S1srwYd S) ueCreate 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. :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`. - ``check_exists`` (optional): if True (the default), send a listCollections command to check if the collection already exists before creation. - `**kwargs` (optional): additional keyword arguments will be passed as options for the `create collection command`_ All optional `create collection command`_ parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to: - ``size`` (int): desired initial size for the collection (in bytes). For capped collections this size is the max size of the collection. - ``capped`` (bool): if True, this is a capped collection - ``max`` (int): maximum number of objects if capped (optional) - ``timeseries`` (dict): a document specifying configuration options for timeseries collections - ``expireAfterSeconds`` (int): the number of seconds after which a document in a timeseries collection expires - ``validator`` (dict): a document specifying validation rules or expressions for the collection - ``validationLevel`` (str): how strictly to apply the validation rules to existing documents during an update. The default level is "strict" - ``validationAction`` (str): whether to "error" on invalid documents (the default) or just "warn" about the violations but allow invalid documents to be inserted - ``indexOptionDefaults`` (dict): a document specifying a default configuration for indexes when creating a collection - ``viewOn`` (str): the name of the source collection or view from which to create the view - ``pipeline`` (list): a list of aggregation pipeline stages - ``comment`` (str): a user-provided comment to attach to this command. This option is only supported on MongoDB >= 4.4. - ``encryptedFields`` (dict): **(BETA)** Document that describes the encrypted fields for Queryable Encryption. For example:: { "escCollection": "enxcol_.encryptedCollection.esc", "eccCollection": "enxcol_.encryptedCollection.ecc", "ecocCollection": "enxcol_.encryptedCollection.ecoc", "fields": [ { "path": "firstName", "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')), "bsonType": "string", "queries": {"queryType": "equality"} }, { "path": "ssn", "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')), "bsonType": "string" } ] } - ``clusteredIndex`` (dict): Document that specifies the clustered index configuration. It must have the following form:: { // key pattern must be {_id: 1} key: , // required unique: , // required, must be ‘true’ name: , // optional, otherwise automatically generated v: , // optional, must be ‘2’ if provided } - ``changeStreamPreAndPostImages`` (dict): a document with a boolean field ``enabled`` for enabling pre- and post-images. .. versionchanged:: 4.2 Added the ``check_exists``, ``clusteredIndex``, and ``encryptedFields`` parameters. .. 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. .. _create collection command: https://mongodb.com/docs/manual/reference/command/create encryptedFields%s.%sZclusteredIndexr-)filterrbzcollection %s already existsTrbN)getr8rFauto_encryption_opts_encrypted_fields_mapr-rvalidate_is_mappingrE _tmp_sessionZin_transactionlist_collection_namesrr) rIr-r:r;r<r=rbrcrdencrypted_fieldsZclustered_indexsr.r.r/create_collection&sP         $zDatabase.create_collectionpipelinec Kst|jj|dd(}t|t|||dudddiid}|jj|j||||j dWdS1s3wYdS) a Perform a database-level aggregation. See the `aggregation pipeline`_ documentation for a list of stages that are supported. .. code-block:: python # Lists all operations currently running on the server. with client.admin.aggregate([{"$currentOp": {}}]) as cursor: for operation in cursor: print(operation) 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): extra `aggregate command`_ parameters. 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`. - `let` (dict): A dict of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. ``"$$var"``). This option is only supported on MongoDB >= 5.0. :Returns: A :class:`~pymongo.command_cursor.CommandCursor` over the result set. .. versionadded:: 3.9 .. _aggregation pipeline: https://mongodb.com/docs/manual/reference/operator/aggregation-pipeline .. _aggregate command: https://mongodb.com/docs/manual/reference/command/aggregate FcloseNcursorZ firstBatch)Z user_fields)Z retryable)r8rlrr_retryable_readZ get_cursorZget_read_preferenceZ_performs_write)rIrqrbrdrocmdr.r.r/ aggregates@ $zDatabase.aggregate full_document resume_aftermax_await_time_ms batch_size collationstart_at_operation_time start_aftercommentfull_document_before_changec Cst|||||||||| | | S)aWatch 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', 'whenAvailable', 'required'. 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. - `full_document_before_change`: Allowed values: 'whenAvailable' and 'required'. Change events may now result in a 'fullDocumentBeforeChange' response field. - `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. - `comment` (optional): A user-provided comment to attach to this command. :Returns: A :class:`~pymongo.change_stream.DatabaseChangeStream` cursor. .. versionchanged:: 4.2 Added ``full_document_before_change`` parameter. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.9 Added the ``start_after`` parameter. .. versionadded:: 3.7 .. seealso:: The MongoDB documentation on `changeStreams `_. .. _change streams specification: https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst r) rIrqryrzr{r|r}r~rbrrrr.r.r/watchsnzDatabase.watchruFc Kstt|tr t||fg}|| |j| } |j|j||||||| | |jd WdS1s3wYdS)zInternal command helper.)r<parse_write_concern_errorrbr8N)rArBrupdaterErlcommandrD) rI sock_inforvaluecheckallowable_errorsr;r:r<rrbrdror.r.r/_commands"  $zDatabase._commandrrrrz=Optional[bson.codec_options.CodecOptions[_CodecDocumentType]]c Ks|pt} |dur || d<|dur|r|ptj}|j||\} }|j| |||||| fd|i| WdS1s>wYdS)aIssue 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`. - `comment` (optional): A user-provided comment to attach to this command. - `**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. .. note:: If this client has been configured to use MongoDB Stable API (see :ref:`versioned-api-ref`), then :meth:`command` will automatically add API versioning options to the given command. Explicitly adding API versioning options in the command and declaring an API version on the client is not supported. .. 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. .. seealso:: The MongoDB documentation on `commands `_. Nrrb)r_txn_read_preferencer!PRIMARYrEZ_socket_for_readsr) rIrrrrr;r:rbrrdoptsrr.r.r/rs,b $zDatabase.commandc  sB|dur |r |p tj}fdd} j| ||S)z5Same as command but used for retryable read commands.Ncs"j||fd|iS)Nrb)rrbserverrr;rrr:rrdrIrr.r/_cmd>s z.Database._retryable_read_command.._cmdrr!rrErv) rIrrrrr;r:rbrdrr.rr/_retryable_read_command/s  z Database._retryable_read_commandc Ks|jd|d}tddifg}|||jj|dd#}|j||||dd}t|||j||du|d d } Wdn1sBwY| || S) z Internal listCollections helper.z$cmd)r;)ZlistCollectionsrurtFrr)r;rbNr)rbZexplicit_sessionr) rarrrErlrraddressrhZ_maybe_pin_connection) rIrrbr;rdZcollrwZ tmp_sessionrtZ cmd_cursorr.r.r/_list_collectionsMs(  zDatabase._list_collectionsrgc sP|dur|d<|r|ptj}|dur|d<fdd}j|||S)aLGet a cursor over the collections 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. - `comment` (optional): A user-provided comment to attach to this command. - `**kwargs` (optional): Optional parameters of the `listCollections command `_ 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 Nrgrcsj||fd|iS)Nr;)rrrdrIr.r/rsz'Database.list_collections.._cmdr)rIrbrgrrdZ read_prefrr.rr/list_collectionsbszDatabase.list_collectionscKst|dur||d<|durd|d<ntd|||d<|r't|dkr+d|vr+d|d<dd |jd d |i|DS) aGet 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. - `comment` (optional): A user-provided comment to attach to this command. - `**kwargs` (optional): Optional parameters of the `listCollections command `_ 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 NrTZnameOnlyrgrur-cSsg|]}|dqS)r-r.).0resultr.r.r/ sz2Database.list_collection_names..rbr.)rrklenr)rIrbrgrrdr.r.r/rms!  zDatabase.list_collection_namesc Csntd|fg}|dur||d<|j|}|j||ddg||d|dWdS1s0wYdS)NZdroprz ns not foundT)rr<rrb)rrEZ_socket_for_writesrZ_write_concern_for)rIr-rbrrrr.r.r/ _drop_helpers$zDatabase._drop_helpername_or_collectionrncCs |}t|tr |j}t|tstdd|j|f}|s0|jjjr0|jjjjr0|jjjj |}|sV|jjjrVt |j d|i||d}|rV|dd drV|ddd}|rt d||jt||||d |jt||||d |jt||||d ||||S) aIDrop 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`. - `comment` (optional): A user-provided comment to attach to this command. - `encrypted_fields`: **(BETA)** Document that describes the encrypted fields for Queryable Encryption. For example:: { "escCollection": "enxcol_.encryptedCollection.esc", "eccCollection": "enxcol_.encryptedCollection.ecc", "ecocCollection": "enxcol_.encryptedCollection.ecoc", "fields": [ { "path": "firstName", "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')), "bsonType": "string", "queries": {"queryType": "equality"} }, { "path": "ssn", "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')), "bsonType": "string" } ] } .. note:: The :attr:`~pymongo.database.Database.write_concern` of this database is automatically applied to this operation. .. versionchanged:: 4.2 Added ``encrypted_fields`` parameter. .. versionchanged:: 4.1 Added ``comment`` parameter. .. 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. z-name_or_collection must be an instance of strrfr-)rgrbrrrFrernrbr)rArr-rBrCr8rFrirjrhlistrrrkrrrr)rIrrbrrnr-Z full_nameZcollsr.r.r/drop_collectionsB:        zDatabase.drop_collectionscandatafull backgroundcCsP|}t|tr |j}t|tstdtd|fd|fd|fg}|dur(||d<|dur0||d<tt|j||d} d } d | vr[| d } | d d ksR| d d krZt d|| fnAd| vr| d D]-\} } d | vr| d } | d d ks| d d krt d|| fqe| ddsd} nqen| ddsd} | st d|| f| S)a!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+. - `comment` (optional): A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.11 Added ``background`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. _validate command: https://mongodb.com/docs/manual/reference/command/validate/ z;name_or_collection must be an instance of str or CollectionvalidaterrNrr)rbTr exceptionZcorruptz%s invalid: %srawvalidFz%s invalid: %r) rArr-rBrCrrdictrfindritemsrh)rIrrrrbrrr-rwrrinfor[resr.r.r/validate_collection'sD+    zDatabase.validate_collectioncCtd)Nz!'Database' object is not iterable)rCrMr.r.r/__next__}szDatabase.__next__cCr)NzwDatabase objects do not implement truth value testing or bool(). Please compare with None instead: database is not None)NotImplementedErrorrMr.r.r/__bool__szDatabase.__bool__dbrefcKsht|ts tdt||jdur"|j|jkr"td|j|jf||jjd|j if||d|S)aDereference 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`. - `comment` (optional): A user-provided comment to attach to this command. - `**kwargs` (optional): any additional keyword arguments are the same as the arguments to :meth:`~pymongo.collection.Collection.find`. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. zcannot dereference a %sNzItrying to dereference a DBRef that points to another database (%r not %r)Z_idr) rArrCtypeZdatabaserD ValueErrorZ collectionZfind_oneid)rIrrbrrdr.r.r/ dereferences   zDatabase.dereference)NNNN)r>r9)NNNNNTrQ) NNNNNNNNNNN)ruTNNNNN)NNN)NN)FFNNN)>__name__ __module__ __qualname____doc__rBr rr"r@propertyr8r-rOrboolrTrUintrWrYrr$r`r^rarapplyrpr%rrxrr#rrrr!rrrr rr r5rrrrrrrmrrr__iter__r rnextrrr __classcell__r.r.rJr/r7DsH  /  7  ' O      !   z  + 0   _   T r7)?rtypingrrrrrrrr r r r r rZbson.codec_optionsrrZ bson.dbrefrZbson.sonrZbson.timestamprZpymongorrZpymongo.aggregationrZpymongo.change_streamrZpymongo.collectionrZpymongo.command_cursorrZpymongo.commonrrrZpymongo.errorsrr Zpymongo.read_preferencesr!r"Zpymongo.typingsr#r$r%r0ZbsonZpymongo.client_sessionr1Zpymongo.mongo_clientr2Zpymongo.read_concernr3Zpymongo.write_concernr4rBr5Z BaseObjectr7r.r.r.r/s0<