o
    ?8¾\¸5  ã                   @   sÊ   d Z ddl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mZmZ dZdd	„ ZG d
d„ deƒZG dd„ deƒZG dd„ deeƒZG dd„ deƒZeddƒZG dd„ deƒZeƒ Zdd„ ZdS )z(Tools for specifying BSON codec options.é    N)Úabstractmethod)Ú
namedtuple)ÚABCÚabcÚabstractpropertyÚstring_type)ÚALL_UUID_REPRESENTATIONSÚPYTHON_LEGACYÚUUID_REPRESENTATION_NAMESée   c                 C   s   t | ddƒ}|tkS )z9Determine if a document_class is a RawBSONDocument class.Ú_type_markerN)ÚgetattrÚ_RAW_BSON_DOCUMENT_MARKER)Údocument_classÚmarker© r   úD/var/www/html/env/lib/python3.10/site-packages/bson/codec_options.pyÚ_raw_document_class    s   r   c                   @   ó(   e Zd ZdZedd„ ƒZedd„ ƒZdS )ÚTypeEncoderaP  Base class for defining type codec classes which describe how a
    custom type can be transformed to one of the types BSON understands.

    Codec classes must implement the ``python_type`` attribute, and the
    ``transform_python`` method to support encoding.

    See :ref:`custom-type-type-codec` documentation for an example.
    c                 C   ó   dS )z<The Python type to be converted into something serializable.Nr   ©Úselfr   r   r   Úpython_type/   ó   zTypeEncoder.python_typec                 C   r   )z<Convert the given Python object into something serializable.Nr   ©r   Úvaluer   r   r   Útransform_python4   r   zTypeEncoder.transform_pythonN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   r   r   r   &   ó    
r   c                   @   r   )ÚTypeDecodera6  Base class for defining type codec classes which describe how a
    BSON type can be transformed to a custom type.

    Codec classes must implement the ``bson_type`` attribute, and the
    ``transform_bson`` method to support decoding.

    See :ref:`custom-type-type-codec` documentation for an example.
    c                 C   r   )z0The BSON type to be converted into our own type.Nr   r   r   r   r   Ú	bson_typeC   r   zTypeDecoder.bson_typec                 C   r   )z/Convert the given BSON value into our own type.Nr   r   r   r   r   Útransform_bsonH   r   zTypeDecoder.transform_bsonN)r   r   r    r!   r   r$   r   r%   r   r   r   r   r#   :   r"   r#   c                   @   s   e Zd ZdZdS )Ú	TypeCodecaÕ  Base class for defining type codec classes which describe how a
    custom type can be transformed to/from one of the types :mod:`bson`
    can already encode/decode.

    Codec classes must implement the ``python_type`` attribute, and the
    ``transform_python`` method to support encoding, as well as the
    ``bson_type`` attribute, and the ``transform_bson`` method to support
    decoding.

    See :ref:`custom-type-type-codec` documentation for an example.
    N)r   r   r    r!   r   r   r   r   r&   N   s    r&   c                   @   s2   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ ZdS )ÚTypeRegistrya¥  Encapsulates type codecs used in encoding and / or decoding BSON, as
    well as the fallback encoder. Type registries cannot be modified after
    instantiation.

    ``TypeRegistry`` can be initialized with an iterable of type codecs, and
    a callable for the fallback encoder::

      >>> from bson.codec_options import TypeRegistry
      >>> type_registry = TypeRegistry([Codec1, Codec2, Codec3, ...],
      ...                              fallback_encoder)

    See :ref:`custom-type-type-registry` documentation for an example.

    :Parameters:
      - `type_codecs` (optional): iterable of type codec instances. If
        ``type_codecs`` contains multiple codecs that transform a single
        python or BSON type, the transformation specified by the type codec
        occurring last prevails. A TypeError will be raised if one or more
        type codecs modify the encoding behavior of a built-in :mod:`bson`
        type.
      - `fallback_encoder` (optional): callable that accepts a single,
        unencodable python value and transforms it into a type that
        :mod:`bson` can encode. See :ref:`fallback-encoder-callable`
        documentation for an example.
    Nc                 C   s²   t |pg ƒ| _|| _i | _i | _| jd urt|ƒstd| ƒ‚| jD ]4}d}t|tƒr9|  	|¡ d}|j
| j|j< t|tƒrGd}|j| j|j< |sVtdtjtjtj|f ƒ‚q"d S )Nz%fallback_encoder %r is not a callableFTz5Expected an instance of %s, %s, or %s, got %r instead)ÚlistÚ_TypeRegistry__type_codecsÚ_fallback_encoderÚ_encoder_mapÚ_decoder_mapÚcallableÚ	TypeErrorÚ
isinstancer   Ú_validate_type_encoderr   r   r#   r%   r$   r   r&   )r   Útype_codecsÚfallback_encoderÚcodecÚis_valid_codecr   r   r   Ú__init__w   s6   
ÿ



þÿÿ÷zTypeRegistry.__init__c                 C   s:   ddl m} |D ]}t|j|ƒrd||f }t|ƒ‚qd S )Nr   )Ú_BUILT_IN_TYPESzYTypeEncoders cannot change how built-in types are encoded (encoder %s transforms type %s))Úbsonr6   Ú
issubclassr   r.   )r   r3   r6   ÚpytypeÚerr_msgr   r   r   r0   ‘   s   þüÿz#TypeRegistry._validate_type_encoderc                 C   s   d| j j| j| jf S )Nz'%s(type_codecs=%r, fallback_encoder=%r))Ú	__class__r   r)   r*   r   r   r   r   Ú__repr__š   s   
þzTypeRegistry.__repr__c                 C   s6   t |t| ƒƒs	tS | j|jko| j|jko| j|jkS )N)r/   ÚtypeÚNotImplementedr,   r+   r*   )r   Úotherr   r   r   Ú__eq__Ÿ   s   
ÿ
þzTypeRegistry.__eq__)NN)r   r   r    r!   r5   r0   r<   r@   r   r   r   r   r'   ]   s    
	r'   ÚCodecOptions©r   Útz_awareÚuuid_representationÚunicode_decode_error_handlerÚtzinfoÚtype_registryc                   @   s>   e Zd ZdZededddfdd„Zdd„ Zd	d
„ Zdd„ Z	dS )rA   aÔ  Encapsulates options used encoding and / or decoding BSON.

    The `document_class` option is used to define a custom type for use
    decoding BSON documents. Access to the underlying raw BSON bytes for
    a document is available using the :class:`~bson.raw_bson.RawBSONDocument`
    type::

      >>> from bson.raw_bson import RawBSONDocument
      >>> from bson.codec_options import CodecOptions
      >>> codec_options = CodecOptions(document_class=RawBSONDocument)
      >>> coll = db.get_collection('test', codec_options=codec_options)
      >>> doc = coll.find_one()
      >>> doc.raw
      '\x16\x00\x00\x00\x07_id\x00[0\x165\x91\x10\xea\x14\xe8\xc5\x8b\x93\x00'

    The document class can be any type that inherits from
    :class:`~collections.MutableMapping`::

      >>> class AttributeDict(dict):
      ...     # A dict that supports attribute access.
      ...     def __getattr__(self, key):
      ...         return self[key]
      ...     def __setattr__(self, key, value):
      ...         self[key] = value
      ...
      >>> codec_options = CodecOptions(document_class=AttributeDict)
      >>> coll = db.get_collection('test', codec_options=codec_options)
      >>> doc = coll.find_one()
      >>> doc._id
      ObjectId('5b3016359110ea14e8c58b93')

    See :doc:`/examples/datetimes` for examples using the `tz_aware` and
    `tzinfo` options.

    See :class:`~bson.binary.UUIDLegacy` for examples using the
    `uuid_representation` option.

    :Parameters:
      - `document_class`: BSON documents returned in queries will be decoded
        to an instance of this class. Must be a subclass of
        :class:`~collections.MutableMapping`. Defaults to :class:`dict`.
      - `tz_aware`: If ``True``, BSON datetimes will be decoded to timezone
        aware instances of :class:`~datetime.datetime`. Otherwise they will be
        naive. Defaults to ``False``.
      - `uuid_representation`: The BSON representation to use when encoding
        and decoding instances of :class:`~uuid.UUID`. Defaults to
        :data:`~bson.binary.PYTHON_LEGACY`.
      - `unicode_decode_error_handler`: The error handler to apply when
        a Unicode-related error occurs during BSON decoding that would
        otherwise raise :exc:`UnicodeDecodeError`. Valid options include
        'strict', 'replace', and 'ignore'. Defaults to 'strict'.
      - `tzinfo`: A :class:`~datetime.tzinfo` subclass that specifies the
        timezone to/from which :class:`~datetime.datetime` objects should be
        encoded/decoded.
      - `type_registry`: Instance of :class:`TypeRegistry` used to customize
        encoding and decoding behavior.

    .. versionadded:: 3.8
       `type_registry` attribute.

    .. warning:: Care must be taken when changing
       `unicode_decode_error_handler` from its default value ('strict').
       The 'replace' and 'ignore' modes should not be used when documents
       retrieved from the server will be modified in the client application
       and stored back to the server.
    FÚstrictNc              	   C   s°   t |tjƒst|ƒstdƒ‚t|tƒstdƒ‚|tvrtdƒ‚t|t	d fƒs*tdƒ‚|d ur>t|t
jƒs8tdƒ‚|s>tdƒ‚|pBtƒ }t|tƒsLtdƒ‚t | ||||||f¡S )Nztdocument_class must be dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a sublass of collections.MutableMappingztz_aware must be True or FalsezMuuid_representation must be a value from bson.binary.ALL_UUID_REPRESENTATIONSz5unicode_decode_error_handler must be a string or Nonez-tzinfo must be an instance of datetime.tzinfoz8cannot specify tzinfo without also setting tz_aware=Truez1type_registry must be an instance of TypeRegistry)r8   r   ÚMutableMappingr   r.   r/   Úboolr   Ú
ValueErrorr   ÚdatetimerF   r'   ÚtupleÚ__new__)Úclsr   rC   rD   rE   rF   rG   r   r   r   rN   ñ   s6   ÿ
ÿÿ

ÿÿzCodecOptions.__new__c                 C   sD   | j tu rdnt| j ƒ}t | j| j¡}d|| j|| j| j| j	f S )z;Representation of the arguments used to create this object.Údictztdocument_class=%s, tz_aware=%r, uuid_representation=%s, unicode_decode_error_handler=%r, tzinfo=%r, type_registry=%r)
r   rP   Úreprr
   ÚgetrD   rC   rE   rF   rG   )r   Údocument_class_reprÚuuid_rep_reprr   r   r   Ú_arguments_repr  s   þÿþýzCodecOptions._arguments_reprc                 C   s   d| j j|  ¡ f S )Nz%s(%s))r;   r   rU   r   r   r   r   r<   #  s   zCodecOptions.__repr__c              
   K   sN   t | d| j¡| d| j¡| d| j¡| d| j¡| d| j¡| d| j¡ƒS )ah  Make a copy of this CodecOptions, overriding some options::

            >>> from bson.codec_options import DEFAULT_CODEC_OPTIONS
            >>> DEFAULT_CODEC_OPTIONS.tz_aware
            False
            >>> options = DEFAULT_CODEC_OPTIONS.with_options(tz_aware=True)
            >>> options.tz_aware
            True

        .. versionadded:: 3.5
        r   rC   rD   rE   rF   rG   )rA   rR   r   rC   rD   rE   rF   rG   )r   Úkwargsr   r   r   Úwith_options&  s   ÿùzCodecOptions.with_options)
r   r   r    r!   rP   r	   rN   rU   r<   rW   r   r   r   r   rA   ­   s    C
ý"c              
   C   sP   t |  dtj¡|  dtj¡|  dtj¡|  dtj¡|  dtj¡|  dtj¡d�S )zParse BSON codec options.r   rC   ÚuuidrepresentationrE   rF   rG   rB   )	rA   rR   ÚDEFAULT_CODEC_OPTIONSr   rC   rD   rE   rF   rG   )Úoptionsr   r   r   Ú_parse_codec_options@  s&   ÿÿÿþÿõr[   )r!   rL   r   r   Úcollectionsr   Úbson.py3compatr   r   r   Úbson.binaryr   r	   r
   r   r   r   r#   r&   Úobjectr'   Ú_options_baserA   rY   r[   r   r   r   r   Ú<module>   s(   Jþ 