o
    'hM                     @  sl  U d Z ddlmZ ddlZddlZddlZddlmZ ddl	m
Z
mZmZmZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZ dZd$ddZG dd dejZG dd dejZ G dd dee Z!eee e!f Z"eegef Z#G dd dZ$G dd de%ej&Z'G dd deZ(e
rG dd dee ee Z)nG dd de(Z)e) Z*de+d< d%d"d#Z,dS )&z(Tools for specifying BSON codec options.    )annotationsN)MutableMapping)TYPE_CHECKINGAnyCallableGenericIterableMapping
NamedTupleOptionalTupleTypeUnioncast)ALL_UUID_REPRESENTATIONSUUID_REPRESENTATION_NAMESUuidRepresentation)_DocumentTypee   document_classr   returnboolc                 C  s   t | dd}|tkS )z9Determine if a document_class is a RawBSONDocument class._type_markerN)getattr_RAW_BSON_DOCUMENT_MARKER)r   marker r   N/var/www/html/olx_land/venv/lib/python3.10/site-packages/bson/codec_options.py_raw_document_class/   s   r   c                   @  0   e Zd ZdZejd
ddZejd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.
    r   r   c                 C     dS )z<The Python type to be converted into something serializable.Nr   selfr   r   r   python_type?       zTypeEncoder.python_typevaluec                 C  r!   )z<Convert the given Python object into something serializable.Nr   r#   r&   r   r   r   transform_pythonC   r%   zTypeEncoder.transform_pythonNr   r   r&   r   r   r   )	__name__
__module____qualname____doc__abcabstractpropertyr$   abstractmethodr(   r   r   r   r   r    5       	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.
    r   r   c                 C  r!   )z0The BSON type to be converted into our own type.Nr   r"   r   r   r   	bson_typeR   r%   zTypeDecoder.bson_typer&   c                 C  r!   )z/Convert the given BSON value into our own type.Nr   r'   r   r   r   transform_bsonV   r%   zTypeDecoder.transform_bsonNr)   r*   )	r+   r,   r-   r.   r/   r0   r4   r1   r5   r   r   r   r   r3   H   r2   r3   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   r6   [   s    r6   c                   @  s>   e Zd ZdZ		ddd	d
ZdddZdddZd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.

    :param type_codecs: 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.
    :param fallback_encoder: 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.
    Ntype_codecsOptional[Iterable[_Codec]]fallback_encoderOptional[_Fallback]r   Nonec                 C  s   t |pg | _|| _i | _i | _| jd urt|std| | jD ];}d}t|tr9| 	| d}|j
| j|j< t|trGd}|j| j|j< |s]tdtj dtj dtj d|d	q"d S )	Nz%fallback_encoder %r is not a callableFTzExpected an instance of z, z, or z, got z instead)list_TypeRegistry__type_codecs_fallback_encoder_encoder_map_decoder_mapcallable	TypeError
isinstancer    _validate_type_encoderr(   r$   r3   r5   r4   r+   r6   )r#   r8   r:   codecis_valid_codecr   r   r   __init__   s,   




"zTypeRegistry.__init__rF   _Codecc                 C  sF   ddl m} |D ]}ttt|j|r d| d| d}t|qd S )Nr   )_BUILT_IN_TYPESzCTypeEncoders cannot change how built-in types are encoded (encoder z transforms type ))bsonrJ   
issubclassr   r6   r$   rC   )r#   rF   rJ   pytypeerr_msgr   r   r   rE      s   z#TypeRegistry._validate_type_encoderstrc                 C  s   d | jj| j| jS )Nz+{}(type_codecs={!r}, fallback_encoder={!r}))format	__class__r+   r>   r?   r"   r   r   r   __repr__   s
   zTypeRegistry.__repr__otherr   c                 C  s6   t |t| s	tS | j|jko| j|jko| j|jkS N)rD   typeNotImplementedrA   r@   r?   )r#   rT   r   r   r   __eq__   s   

zTypeRegistry.__eq__)NN)r8   r9   r:   r;   r   r<   )rF   rI   r   r<   r   rP   )rT   r   r   r   )r+   r,   r-   r.   rH   rE   rS   rX   r   r   r   r   r7   m   s    

r7   c                   @  s&   e Zd ZdZdZ	 dZ	 dZ	 dZdS )DatetimeConversionz$Options for decoding BSON datetimes.            N)r+   r,   r-   r.   DATETIMEDATETIME_CLAMPDATETIME_MSDATETIME_AUTOr   r   r   r   rZ      s    	rZ   c                   @  sF   e Zd ZU ded< ded< ded< ded< d	ed
< ded< ded< dS )_BaseCodecOptionszType[Mapping[str, Any]]r   r   tz_awareintuuid_representationrP   unicode_decode_error_handlerOptional[datetime.tzinfo]tzinfor7   type_registryOptional[DatetimeConversion]datetime_conversionN)r+   r,   r-   __annotations__r   r   r   r   rc      s   
 rc   c                   @  s   e Zd ZU ded< ded< ded< ded< d	ed
< ded< ded< 							d0d1ddZd2ddZd3ddZd4d!d"Zed5d%d&Z	d6d(d)Z
d7d*d+Zded,< d-ed.< d/S )8CodecOptionszType[_DocumentType]r   r   rd   re   rf   Optional[str]rg   rh   ri   r7   rj   Optional[int]rl   .cls!Type[CodecOptions[_DocumentType]]Optional[Type[_DocumentType]]Optional[TypeRegistry]r   CodecOptions[_DocumentType]c                 C     d S rU   r   )rq   r   rd   rf   rg   ri   rj   rl   r   r   r   __new__   s   
CodecOptions.__new__kwargsr   CodecOptions[Any]c                 K  rv   rU   r   r#   ry   r   r   r   with_options     CodecOptions.with_optionsrP   c                 C  rv   rU   r   r"   r   r   r   _arguments_repr  r}   CodecOptions._arguments_reprdict[Any, Any]c                 C  rv   rU   r   r"   r   r   r   _options_dict
  r}   CodecOptions._options_dictobjIterable[Any]c                 C  rv   rU   r   )rq   r   r   r   r   _make  s   zCodecOptions._makedict[str, Any]c                 C  rv   rU   r   r"   r   r   r   _asdict  r}   zCodecOptions._asdictc                 K  rv   rU   r   r{   r   r   r   _replace  r}   zCodecOptions._replace_sourcez
Tuple[str]_fieldsN).......)rq   rr   r   rs   rd   r   rf   rp   rg   ro   ri   rh   rj   rt   rl   rp   r   ru   )ry   r   r   rz   rY   )r   r   )r   r   r   ru   r   r   )ry   r   r   ru   )r+   r,   r-   rm   rw   r|   r   r   classmethodr   r   r   r   r   r   r   rn      s2   
 




rn   c                      sf   e Zd ZdZ fddZddejdddejfd%ddZ	d&ddZ
d'ddZd&dd Zd(d#d$Z  ZS ))rn   z:Encapsulates options used encoding and / or decoding BSON.c                   s   t    dS )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.abc.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 :doc:`/examples/uuid` for examples using the `uuid_representation`
            option.

            :param document_class: BSON documents returned in queries will be decoded
                to an instance of this class. Must be a subclass of
                :class:`~collections.abc.MutableMapping`. Defaults to :class:`dict`.
            :param 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``.
            :param uuid_representation: The BSON representation to use when encoding
                and decoding instances of :class:`~uuid.UUID`. Defaults to
                :data:`~bson.binary.UuidRepresentation.UNSPECIFIED`. New
                applications should consider setting this to
                :data:`~bson.binary.UuidRepresentation.STANDARD` for cross language
                compatibility. See :ref:`handling-uuid-data-example` for details.
            :param 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', 'backslashreplace', 'surrogateescape', and
                'ignore'. Defaults to 'strict'.
            :param tzinfo: A :class:`~datetime.tzinfo` subclass that specifies the
                timezone to/from which :class:`~datetime.datetime` objects should be
                encoded/decoded.
            :param type_registry: Instance of :class:`TypeRegistry` used to customize
                encoding and decoding behavior.
            :param datetime_conversion: Specifies how UTC datetimes should be decoded
                within BSON. Valid options include 'datetime_ms' to return as a
                DatetimeMS, 'datetime' to return as a datetime.datetime and
                raising a ValueError for out-of-range values, 'datetime_auto' to
                return DatetimeMS objects when the underlying datetime is
                out-of-range and 'datetime_clamp' to clamp to the minimum and
                maximum possible datetimes. Defaults to 'datetime'.

            .. versionchanged:: 4.0
               The default for `uuid_representation` was changed from
               :const:`~bson.binary.UuidRepresentation.PYTHON_LEGACY` to
               :const:`~bson.binary.UuidRepresentation.UNSPECIFIED`.

            .. 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.
            N)superrH   )r#   argsry   rR   r   r   rH      s   RzCodecOptions.__init__NFstrictrq   Type[CodecOptions]r   !Optional[Type[Mapping[str, Any]]]rd   r   rf   rp   rg   rP   ri   rh   rj   rt   rl   rk   r   c           
   
   C  s  |pt }d}	zt|t}	W n ty!   t|drt|jt}	Y nw |	s,t|s,tdt|ts8td| |t	vr@t
dt|tsNt
dt| |d urgt|tjsatdt| |sgt
d|pkt }t|tsztd	t| t| |||||||fS )
NF
__origin__zydocument_class must be dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a subclass of collections.abc.MutableMappingz.tz_aware must be True or False, was: tz_aware=zGuuid_representation must be a value from bson.binary.UuidRepresentationz3unicode_decode_error_handler must be a string, not z3tzinfo must be an instance of datetime.tzinfo, not z8cannot specify tzinfo without also setting tz_aware=Truez7type_registry must be an instance of TypeRegistry, not )dictrM   _MutableMappingrC   hasattrr   r   rD   r   r   
ValueErrorrP   rV   datetimeri   r7   tuplerw   )
rq   r   rd   rf   rg   ri   rj   rl   	doc_class
is_mappingr   r   r   rw   t  s\   





rx   c              	   C  sH   | j tu rdnt| j }t| j| j}d|| j|| j| j	| j
| jS )z;Representation of the arguments used to create this object.r   zdocument_class={}, tz_aware={!r}, uuid_representation={}, unicode_decode_error_handler={!r}, tzinfo={!r}, type_registry={!r}, datetime_conversion={!s})r   r   reprr   getrf   rQ   rd   rg   ri   rj   rl   )r#   document_class_repruuid_rep_reprr   r   r   r     s    r   r   c                 C  s"   | j | j| j| j| j| j| jdS )z7Dictionary of the arguments used to create this object.r   rd   rf   rg   ri   rj   rl   r   r"   r   r   r   r     s   r   c                 C  s   | j j d|   dS )N(rK   )rR   r+   r   r"   r   r   r   rS     s   zCodecOptions.__repr__ry   r   c                 K  s    |   }|| tdi |S )a  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
            Nr   )r   updatern   )r#   ry   optsr   r   r   r|     s   
r~   )rq   r   r   r   rd   r   rf   rp   rg   rP   ri   rh   rj   rt   rl   rk   r   rn   rY   r   )ry   r   r   rn   )r+   r,   r-   r.   rH   r   UNSPECIFIEDrZ   r_   rw   r   r   rS   r|   __classcell__r   r   r   r   rn     s    V
?

zCodecOptions[dict[str, Any]]DEFAULT_CODEC_OPTIONSoptionsrz   c                 C  sJ   i }t | h d@ D ]}|dkr| | |d< q
| | ||< q
tdi |S )zParse BSON codec options.>   ri   rd   rj   r   uuidrepresentationrl   rg   r   rf   Nr   )setrn   )r   ry   kr   r   r   _parse_codec_options  s   	r   )r   r   r   r   )r   r   r   rz   )-r.   
__future__r   r/   r   enumcollections.abcr   r   typingr   r   r   r   r   r	   r
   r   r   r   r   r   bson.binaryr   r   r   bson.typingsr   r   r   ABCr    r3   r6   rI   	_Fallbackr7   re   EnumrZ   rc   rn   r   rm   r   r   r   r   r   <module>   s2   8
R#
/ P