U
    d                     @   s   U d Z ddlmZmZmZmZmZ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eeeeeef d	d
dZG dd deeef ZG dd deZejedZeed< ejedZeed< dS )a  Tools for representing raw BSON documents.

Inserting and Retrieving RawBSONDocuments
=========================================

Example: Moving a document between different databases/collections

.. doctest::

  >>> import bson
  >>> from pymongo import MongoClient
  >>> from bson.raw_bson import RawBSONDocument
  >>> client = MongoClient(document_class=RawBSONDocument)
  >>> client.drop_database("db")
  >>> client.drop_database("replica_db")
  >>> db = client.db
  >>> result = db.test.insert_many(
  ...     [{"_id": 1, "a": 1}, {"_id": 2, "b": 1}, {"_id": 3, "c": 1}, {"_id": 4, "d": 1}]
  ... )
  >>> replica_db = client.replica_db
  >>> for doc in db.test.find():
  ...     print(f"raw document: {doc.raw}")
  ...     print(f"decoded document: {bson.decode(doc.raw)}")
  ...     result = replica_db.test.insert_one(doc)
  ...
  raw document: b'...'
  decoded document: {'_id': 1, 'a': 1}
  raw document: b'...'
  decoded document: {'_id': 2, 'b': 1}
  raw document: b'...'
  decoded document: {'_id': 3, 'c': 1}
  raw document: b'...'
  decoded document: {'_id': 4, 'd': 1}

For use cases like moving documents across different databases or writing binary
blobs to disk, using raw BSON documents provides better speed and avoids the
overhead of decoding or encoding BSON.
    )AnyDict	ItemsViewIteratorMappingOptional)_get_object_size_raw_to_dict)_RAW_BSON_DOCUMENT_MARKER)DEFAULT_CODEC_OPTIONS)CodecOptions)SONF)
bson_bytescodec_options	raw_arrayreturnc                 C   s   t | dt| d |t |dS )a%  Inflates the top level fields of a BSON document.

    :Parameters:
      - `bson_bytes`: the BSON bytes that compose this document
      - `codec_options`: An instance of
        :class:`~bson.codec_options.CodecOptions` whose ``document_class``
        must be :class:`RawBSONDocument`.
          r   )r	   lenr   )r   r   r    r   1/tmp/pip-unpacked-wheel-oblwsawz/bson/raw_bson.py_inflate_bson?   s      
   r   c                   @   s   e Zd ZdZdZeZdeee	 ddddZ
eeddd	Zeeef dd
dZeeeef dddZeee	eeef dddZeedddZee dddZedddZeedddZedddZdS )RawBSONDocumentzRepresentation for a MongoDB document that provides access to the raw
    BSON bytes that compose it.

    Only when a field is accessed or modified within the document does
    RawBSONDocument decode its bytes.
    )Z__rawZ__inflated_docZ__codec_optionsNr   r   r   c                 C   sP   || _ d| _|dkrt}nt|jts6td|j|| _t	|dt
| dS )a9  Create a new :class:`RawBSONDocument`

        :class:`RawBSONDocument` is a representation of a BSON document that
        provides access to the underlying raw BSON bytes. Only when a field is
        accessed or modified within the document does RawBSONDocument decode
        its bytes.

        :class:`RawBSONDocument` implements the ``Mapping`` abstract base
        class from the standard library so it can be used like a read-only
        ``dict``::

            >>> from bson import encode
            >>> raw_doc = RawBSONDocument(encode({'_id': 'my_doc'}))
            >>> raw_doc.raw
            b'...'
            >>> raw_doc['_id']
            'my_doc'

        :Parameters:
          - `bson_bytes`: the BSON bytes that compose this document
          - `codec_options` (optional): An instance of
            :class:`~bson.codec_options.CodecOptions` whose ``document_class``
            must be :class:`RawBSONDocument`. The default is
            :attr:`DEFAULT_RAW_BSON_OPTIONS`.

        .. versionchanged:: 3.8
          :class:`RawBSONDocument` now validates that the ``bson_bytes``
          passed in represent a single bson document.

        .. versionchanged:: 3.5
          If a :class:`~bson.codec_options.CodecOptions` is passed in, its
          `document_class` must be :class:`RawBSONDocument`.
        Nz>RawBSONDocument cannot use CodecOptions with document class {}r   )_RawBSONDocument__raw_RawBSONDocument__inflated_docDEFAULT_RAW_BSON_OPTIONS
issubclassdocument_classr   	TypeErrorformat_RawBSONDocument__codec_optionsr   r   )selfr   r   r   r   r   __init__[   s    "zRawBSONDocument.__init__)r   c                 C   s   | j S )z+The raw BSON bytes composing this document.)r   r#   r   r   r   raw   s    zRawBSONDocument.rawc                 C   s
   | j  S )z4Lazily decode and iterate elements in this document.)_RawBSONDocument__inflateditemsr%   r   r   r   r(      s    zRawBSONDocument.itemsc                 C   s"   | j d kr| | j| j| _ | j S N)r   r   r   r"   r%   r   r   r   Z
__inflated   s    
zRawBSONDocument.__inflatedc                 C   s
   t | |S r)   r   r   r   r   r   r   r      s    zRawBSONDocument._inflate_bson)itemr   c                 C   s
   | j | S r)   )r'   )r#   r,   r   r   r   __getitem__   s    zRawBSONDocument.__getitem__c                 C   s
   t | jS r)   )iterr'   r%   r   r   r   __iter__   s    zRawBSONDocument.__iter__c                 C   s
   t | jS r)   )r   r'   r%   r   r   r   __len__   s    zRawBSONDocument.__len__)otherr   c                 C   s   t |tr| j|jkS tS r)   )
isinstancer   r   r&   NotImplemented)r#   r1   r   r   r   __eq__   s    
zRawBSONDocument.__eq__c                 C   s   d | jj| j| jS )Nz{}({!r}, codec_options={!r}))r!   	__class____name__r&   r"   r%   r   r   r   __repr__   s
    zRawBSONDocument.__repr__)N)r6   
__module____qualname____doc__	__slots__r
   Z_type_markerbytesr   r   r$   propertyr&   r   strr   r(   r   r'   staticmethodr   r-   r   r/   intr0   boolr4   r7   r   r   r   r   r   P   s    1r   c                   @   s.   e Zd ZdZeeeeeef dddZ	dS )_RawArrayBSONDocumentzKA RawBSONDocument that only expands sub-documents and arrays when accessed.r   c                 C   s   t | |ddS )NTr   r*   r+   r   r   r   r      s    z#_RawArrayBSONDocument._inflate_bsonN)
r6   r8   r9   r:   r?   r<   r   r   r   r   r   r   r   r   rB      s   rB   )r   r   _RAW_ARRAY_BSON_OPTIONSN)F)r:   typingr   r   r   r   r   r   Zbsonr   r	   Zbson.codec_optionsr
   r   DEFAULTr   Zbson.sonr   r<   rA   r   r>   r   rB   Zwith_optionsr   __annotations__rC   r   r   r   r   <module>   s$   '    
h