
    h'h                         d dl Z d dlZd dlZd dlmZmZ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Z G d d	      Z G d
 de      Z G d de      Z G d de      Zy)    N)SONDBRefObjectId)UPDATE_OPERATORS)BaseDictBaseListEmbeddedDocumentList_import_class)DeprecatedErrorValidationError)	BaseFieldComplexBaseFieldObjectIdFieldGeoJsonBaseFieldc                       e Zd ZdZdZdZdZdZdZdZ		 	 	 	 	 	 	 	 	 	 ddZ
d Zd	 Zdd
Zd Zd ZddZd ZddZd Zd Zed        Zd Zej0                  d        Zy)r   zA base class for fields in a MongoDB document. Instances of this class
    may be added to subclasses of `Document` to define a document's schema.
    NFTr   c                    |s|nd| _         |xs || _        || _        t        |xs |      | _        || _        || _        || _        || _        |	| _	        |
| _
        d| _        | j                   %t        | j                   t              st        d      t        | j                   t              rBd| j                   v s)d| j                   v s| j                   j                  d      rt!        d      t#        t%        |             t#        |      z  }|r3t        | j&                  j(                  dd	j+                  |            | j,                  j/                  |       | j                   dk(  r/t0        j2                  | _        t0        xj2                  d
z  c_        yt0        j4                  | _        t0        xj4                  d
z  c_        y)a  
        :param db_field: The database field to store this field in
            (defaults to the name of the field)
        :param required: If the field is required. Whether it has to have a
            value or not. Defaults to False.
        :param default: (optional) The default value for this field if no value
            has been set, if the value is set to None or has been unset. It can be a
            callable.
        :param unique: Is the field value unique or not (Creates an index).  Defaults to False.
        :param unique_with: (optional) The other field this field should be
            unique with (Creates an index).
        :param primary_key: Mark this field as the primary key ((Creates an index)). Defaults to False.
        :param validation: (optional) A callable to validate the value of the
            field.  The callable takes the value as parameter and should raise
            a ValidationError if validation fails
        :param choices: (optional) The valid choices
        :param null: (optional) If the field value can be null when a default exist. If not set, the default value
        will be used in case a field with a default value is set to None. Defaults to False.
        :param sparse: (optional) `sparse=True` combined with `unique=True` and `required=False`
            means that uniqueness won't be enforced for `None` values (Creates an index). Defaults to False.
        :param **kwargs: (optional) Arbitrary indirection-free metadata for
            this field can be supplied as additional keyword arguments and
            accessed as attributes of the field. Must not conflict with any
            existing attributes. Common metadata includes `verbose_name` and
            `help_text`.
        _idNzdb_field should be a string.. $zrfield names cannot contain dots (".") or null characters ("\0"), and they must not start with a dollar sign ("$").z already has attribute(s): ,    )db_fieldrequireddefaultbooluniqueunique_withprimary_key
validationchoicesnullsparse_owner_document
isinstancestr	TypeError
startswith
ValueErrorsetdir	__class____name__join__dict__updater   auto_creation_countercreation_counter)selfr   r   r   r   r    r!   r"   r#   r$   r%   kwargs	conflictss                U/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/mongoengine/base/fields.py__init__zBaseField.__init__#   s   P )4 /K60[1&&$	# ==$Zs-K:;; dmmS)4== t}}$}}'',M  D	NS[0	>>**DIIi,@B  	V$ ==E!$-$C$CD!++q0+$-$>$>D!&&!+&    c                 T    || S |j                   j                  | j                        S )z=Descriptor for retrieving a value from a field in a document.)_datagetname)r5   instanceowners      r8   __get__zBaseField.__get__{   s(    K ~~!!$)),,r:   c                    |9| j                   rd}n*| j                  | j                  }t        |      r |       }|j                  rT	 | j                  |j
                  vxs |j
                  | j                     |k7  }|r|j                  | j                         t        d      }t        ||      rt        j                  |      |_        nDt        |t        t        f      r.|D ])  }t        ||      st        j                  |      |_        + ||j
                  | j                  <   y# t        $ r |j                  | j                         Y w xY w)z:Descriptor for assigning a value to a field in a document.NEmbeddedDocument)r$   r   callable_initialisedr>   r<   _mark_as_changed	Exceptionr   r'   weakrefproxy	_instancelisttuple)r5   r?   valuevalue_has_changedrC   vs         r8   __set__zBaseField.__set__   s$    =yy)E?!GE  5IIX^^3 :~~dii0E9 " %--dii8 ));<e-.%mmH5EOe}- :a!12")--"9AK: %*tyy!  5 ))$))4	5s   	AD, ,$EEc                 >    |r|n| j                   }t        |||      )zRaise a ValidationError.)errors
field_name)r>   r   )r5   messagerR   rS   s       r8   errorzBaseField.error   s    #-Z499
gfLLr:   c                     |S )3Convert a MongoDB-compatible type to a Python type. r5   rM   s     r8   	to_pythonzBaseField.to_python   s    r:   c                 $    | j                  |      S )3Convert a Python type to a MongoDB-compatible type.)rZ   rY   s     r8   to_mongozBaseField.to_mongo   s    ~~e$$r:   c                     | j                   j                  j                  }i }d|v r||d<   d|v r||d<    | j                   |fi |S )z2Helper method to call to_mongo with proper inputs.fieldsuse_db_field)r]   __code__co_varnames)r5   rM   r`   r_   f_inputsex_varss         r8   _to_mongo_safe_callzBaseField._to_mongo_safe_call   sV    ==))55x &GHX%&2GN#t}}U.g..r:   c                 8    |t         v r| j                  |       |S )z:Prepare a value that is being used in a query for PyMongo.)r   validater5   oprM   s      r8   prepare_query_valuezBaseField.prepare_query_value   s    !!MM% r:   c                      y)zPerform validation on a value.NrX   )r5   rM   cleans      r8   rg   zBaseField.validate   s    r:   c                    t        d      }t        d      }| j                  }t        t        t	        |            t
        t        f      r|D cg c]  \  }}|	 }}}t        ||f      r*t        fd|D              s| j                  d|z         y y t        t
        t        f      rng}t        t        |      t        |      z
        r| j                  dt        |      z         y y c c}}w )NDocumentrC   c              3   6   K   | ]  }t        |        y wN)r'   ).0crM   s     r8   	<genexpr>z.BaseField._validate_choices.<locals>.<genexpr>   s     Az%+As   zValue must be an instance of %szValue must be one of %s)r   r#   r'   nextiterrK   rL   anyrU   lenr,   r(   )r5   rM   rn   rC   choice_listk_valuess    `      r8   _validate_choiceszBaseField._validate_choices   s     ,();<lld4,-e}=)45A15K5 eh(89:A[AA

<LM B )u>UUGF3v;[!112

4s;7GGH 3 6s   C2c                    | j                   r| j                  |       | j                  Zt        | j                        r-	 | j                  |      }|t	        d| j
                  z        nt        d| j
                  z         | j                  |fi | y # t        $ r$}| j                  t        |             Y d }~<d }~ww xY w)Nzlvalidation argument for `%s` must not return anything, it should raise a ValidationError if validation failsz2validation argument for `"%s"` must be a callable.)r#   r|   r"   rD   r   r>   r   rU   r(   r+   rg   )r5   rM   r6   retexs        r8   	_validatezBaseField._validate   s    <<""5) ??&(( //%0C-T"ii(  ' !KdiiW  	e&v& ' (JJs2w''(s    +B 	C!C  Cc                     | j                   S rp   r&   )r5   s    r8   owner_documentzBaseField.owner_document   s    ###r:   c                     || _         y rp   r   r5   r   s     r8   _set_owner_documentzBaseField._set_owner_document   s
    -r:   c                 &    | j                  |       y rp   )r   r   s     r8   r   zBaseField.owner_document  s      0r:   )
NFNFNFNNFF) NNTNT)r/   
__module____qualname____doc__r>   
_geo_index	_auto_gen_auto_dereferencer4   r3   r9   rA   rP   rU   rZ   r]   re   rj   rg   r|   r   propertyr   r   setterrX   r:   r8   r   r      s     DJI
  V,p-"*HM
%
/I&'8 $ $. 1 1r:   r   c                   n     e Zd ZdZd fd	Zed        Z fdZ fdZd Z	ddZ
d Zd	 Zd
 Zd Z xZS )r   a  Handles complex fields, such as lists / dictionaries.

    Allows for nesting of embedded documents inside complex types.
    Handles the lazy dereferencing of a queryset by lazily dereferencing all
    items in a list / dict rather than one at a time.
    c                 2    || _         t        |   di | y )NrX   )fieldsuperr9   )r5   r   r6   r.   s      r8   r9   zComplexBaseField.__init__  s    
"6"r:   c                >     t        d             } |||| |      }|S )NDeReference)	max_depthr?   r>   r
   )r?   r>   
ref_valuesr   _dereference	documentss         r8   _lazy_load_refsz ComplexBaseField._lazy_load_refs  s/    3}]35 	
	 r:   c                    t        d      }| j                  rt        | j                  |      rt        |t        t        f      r)|D cg c]  }| j                  j                  |       }}nLt        |t              r<|j                         D ci c]!  \  }}|| j                  j                  |      # }}}t        | %  ||      S c c}w c c}}w )N	EnumField)
r   r   r'   rK   rL   rZ   dictitemsr   rP   )r5   r?   rM   r   sub_valkeysubr.   s          r8   rP   zComplexBaseField.__set__  s     "+.	::*TZZ;%$/FKL7--g6LLE4(HMVHCdjj22377VVwx//	 MVs   	"C
&Cc                    || S t        d      }t        d      }t        d      }|j                  | j                     j                  }|xr( | j                  du xs t        | j                  ||f      }|j                  r|r|j                  j                  | j                        rt        |j                  | j                     dd      s|j                  j                  | j                        }| j                  ||| j                  d      |j                  | j                  <   t        |j                  | j                     d      rd	|j                  | j                     _        t        
| 9  ||      }	t        |	t        t         f      r~t#        t%        |       |      r(t        |	t&              st'        |	|| j                        }	n't        |	t(              st)        |	|| j                        }	|	|j                  | j                  <   nPt        |	t*              r@t        |	t,              s0t-        |	|| j                        }	|	|j                  | j                  <   |rm|j                  rat        |	t(        t,        f      rK|	j                  s?| j                  |	|| j                  d      }	d	|	_        |	|j                  | j                  <   |	S )
z3Descriptor to automatically dereference references.NReferenceFieldGenericReferenceFieldEmbeddedDocumentListField_dereferencedFr   )r   r?   r>   r   T)r   _fieldsr>   r   r   r'   rE   r<   r=   getattrr   hasattrr   r   rA   rK   rL   
issubclasstyper	   r   r   r   )r5   r?   r@   r   r   r   auto_dereferencedereferencer   rM   r.   s             r8   rA   zComplexBaseField.__get__)  sQ   K&'78 -.E F$12M$N!#++DII6HH& 
JJ$ O$**'<n&MN 	 !!""499-HNN4995N!++DII6J(,(<(<%tyyTU )= )HNN499% x~~dii0/B:>tyy)7%0 edE]+$t*&?@+J -UHdiiHx0 $))<(-HNN499%t$Zx-HUHdii8E(-HNN499% %%58X"67''(( 8$))q ) E #'E(-HNN499%r:   c                    t        |t              r|S t        |d      r|j                         S t	        d      }t        ||      r|S d}t        |d      s!	 d}t        |      D ci c]  \  }}||
 }}}| j                  rX| j                  | j                  _        |j                         D ci c]!  \  }}|| j                  j                  |      # }}}nt	        d      }	i }|j                         D ]  \  }
}t        ||	      rG|j                  | j                  d       |j                         }t        ||j                        ||
<   Yt        |d      r|j                         ||
<   y| j                  |      ||
<    |rAt        |j                         t        j                   d      	      D cg c]  \  }}|	 c}}S |S c c}}w # t        $ r |cY S w xY wc c}}w c c}}w )
rW   rZ   BaseDocumentFr   Trn   JYou can only reference documents once they have been saved to the databaser   r   )r'   r(   r   rZ   r   	enumerater)   r   r   r   pkrU   _get_collection_namer   sortedoperator
itemgetter)r5   rM   r   is_listidxrO   r   item
value_dictrn   ry   
collectionrz   s                r8   rZ   zComplexBaseField.to_pythond  s   eS!L5+&??$$$^4e\*Lug&.7.>?FCa?? ::+/+A+ADJJ(AF4=CTZZ))$//J  %Z0HJ 61a*tt|

? "#!7!7!9J$)*add$;JqMQ,$%KKMJqM$(NN1$5JqM6 $Z%5%5%7X=P=PQR=STa  ? @ 
,s0   G 'G4G 1&G#:G)G G G c           
         t        d      }t        d      }t        d      }t        |t              r|S t        |d      r]t        ||      r |       j	                  |      S |j
                  }|j	                  ||      }t        ||      r|j                  |d<   |S d}	t        |d      s!	 d}	t        |      D 
ci c]  \  }
}|
|
 }}
}| j                  r@|j                         D ci c]#  \  }}|| j                  j                  |||      % }}}n
i }|j                         D ]  \  }
}t        ||      r|j                  | j                  d	       t        |d
i       }|j                  d      }|s |       j	                  |      ||
<   i|j!                         }t#        ||j                        ||
<   t        |d      rA|j
                  }|j	                  ||      }t        |||f      r|j                  |d<   |||
<   | j	                  |||      ||
<    |	rAt%        |j                         t'        j(                  d            D cg c]  \  }}|	 c}}S |S c c}}
w # t        $ r |cY S w xY wc c}}w c c}}w )r\   rn   rC   r   r]   _clsFr   Tr   _metaallow_inheritancer   r   )r   r'   r(   r   r]   r.   r/   r   r)   r   r   re   r   rU   r   r=   r   r   r   r   r   )r5   rM   r`   r_   rn   rC   r   clsvalr   ry   rO   r   r   r   metar   r   rz   s                      r8   r]   zComplexBaseField.to_mongo  s~    ,();< -.E FeS!L5*%%*,.77>>//C..v6C%!12!llFJug&*3E*:;$!QA;; :: "'C TZZ33D,OOJ 
 J K1a*tt|

? #1gr2D(,1D(E%,(=(?(H(H(K
1%&%;%;%=
(-j!$$(?
1Q
+++C**\6:C!!h0@%AB&)llF$'JqM$(MM!\6$JJqM7K: $Z%5%5%7X=P=PQR=STa  Y < Hs0   ,I- <I'	I- +(I>J'I- -I;:I;c                     i }| j                   rt        |d      r|j                         }nt        |      }|D ]!  \  }}	 | j                   j	                  |       # |r:| j                   j                  j                  }| j                  d| d| d|       | j                  r|s| j                  d       yyy# t
        $ r}|j                  xs |||<   Y d}~d}~wt        t        f$ r}|||<   Y d}~d}~ww xY w)z/If field is provided ensure the value is valid.r   NzInvalid z item ())rR   z%Field is required and cannot be empty)r   r   r   r   r   r   rR   r+   AssertionErrorr.   r/   rU   r   )r5   rM   rR   sequencery   rO   rU   field_classs           r8   rg   zComplexBaseField.validate  s    ::ug& ;;=$U+  &1&JJ((+& "jj22;;

Xk]'%B6
R==JJ>? "'= ' 6 % 5F1I"N3 & %F1I&s$    B;;	C=CC=.C88C=c                 $    | j                  |      S rp   r]   rh   s      r8   rj   z$ComplexBaseField.prepare_query_value  s    }}U##r:   c                 R    | j                   r| j                   j                  |      S y rp   )r   lookup_member)r5   member_names     r8   r   zComplexBaseField.lookup_member  s!    ::::++K88r:   c                 L    | j                   r|| j                   _        || _        y rp   )r   r   r&   r   s     r8   r   z$ComplexBaseField._set_owner_document  s    ::(6DJJ%-r:   rp   r   )r/   r   r   r   r9   staticmethodr   rP   rA   rZ   r]   rg   rj   r   r   __classcell__r.   s   @r8   r   r     sN    #  
09v0dCJ@.$
.r:   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)r   z+A field wrapper around MongoDB's ObjectIds.c                 ^    	 t        |t              st        |      }|S # t        $ r Y |S w xY wrp   )r'   r   rG   rY   s     r8   rZ   zObjectIdField.to_python  s:    	eX.    		s    	,,c                     t        |t              r|S 	 t        t        |            S # t        $ r$}| j	                  t        |             Y d }~y d }~ww xY wrp   )r'   r   r(   rG   rU   )r5   rM   es      r8   r]   zObjectIdField.to_mongo  sH    eX&L	CJ'' 	JJs1v	s   ( 	AAAc                 ,    ||S | j                  |      S rp   r   rh   s      r8   rj   z!ObjectIdField.prepare_query_value  s    =L}}U##r:   c                 n    	 t        t        |             y # t        $ r | j                  d       Y y w xY w)NzInvalid ObjectID)r   r(   rG   rU   rY   s     r8   rg   zObjectIdField.validate  s/    	+SZ  	+JJ)*	+s    44N)r/   r   r   r   rZ   r]   rj   rg   rX   r:   r8   r   r      s    5$
+r:   r   c                   v     e Zd ZdZej
                  ZdZd fd	Zd Z	ddZ
ddZd Zd Zdd	Zd
 Zd Z xZS )r   z0A geo json field storing a geojson style object.GeoBasec                 ^    d| j                   z  | _        |sd| _        t        |   |i | y)zq
        :param bool auto_index: Automatically create a '2dsphere' index.            Defaults to `True`.
        z%sFieldFN)_type_namer   r   r9   )r5   
auto_indexargsr6   r.   s       r8   r9   zGeoJsonBaseField.__init__&  s1    
 +
#DO$)&)r:   c                 0   t        |t              rt        |j                               ddhk(  rQ|d   | j                  k7  r+| j                  | j                   d| j                   d       | j                  |d         S | j                  d| j                  z         yt        |t        t        f      s| j                  d| j                  z         yt        | d| j                  j                         z        } ||      }|r| j                  |       yy)	z.Validate the GeoJson object based on its type.r   coordinatesz type must be ""z@%s can only accept a valid GeoJson dictionary or lists of (x, y)Nz"%s can only accept lists of [x, y]z_validate_%s)r'   r   r,   keysr   rU   r   rg   rK   rL   r   lower)r5   rM   rg   rU   s       r8   rg   zGeoJsonBaseField.validate0  s    eT"5::< V]$;;=DJJ.JJ$**_TZZLJK}}U=%9::

*,0JJ7 ED%=1JJ;djjHI4$**2B2B2D!DEJJu r:   c                 R   t        |t        t        f      sy	 |d   d   d    g }|D ]<  }| j                  |d      }|s|d   |d   k7  rd}|s'||vs,|j                  |       > |r*|rddj                  |      z  S d	dj                  |      z  S y # t        t        f$ r Y yw xY w)
Nz)Polygons must contain list of linestringsr   z:Invalid Polygon must contain at least one valid linestringFr   z0LineStrings must start and end at the same pointzInvalid Polygon:
%sr   %sr'   rK   rL   r)   
IndexError_validate_linestringappendr0   r5   rM   	top_levelrR   r   rU   s         r8   _validate_polygonz"GeoJsonBaseField._validate_polygonF  s    %$/>	P!HQKN  	%C--c59ESVs2w.Jf,e$	% -		&0AAAdii///	  :& 	PO	Ps   B B&%B&c                 ,   t        |t        t        f      sy	 |d   d    g }|D ],  }| j                  |      }|s||vs|j                  |       . |r*|rddj                  |      z  S ddj                  |      z  S y# t        t        f$ r Y yw xY w)zValidate a linestring.z1LineStrings must contain list of coordinate pairsr   z8Invalid LineString must contain at least one valid pointzInvalid LineString:
%sr   r   Nr'   rK   rL   r)   r   _validate_pointr   r0   r   s         r8   r   z%GeoJsonBaseField._validate_linestring]  s    %$/F	N!HQK  	%C((-Ef,e$	% 0499V3DDDdii///	  :& 	NM	Ns   B BBc                     t        |t        t        f      syt        |      dk(  sdt	        |      z  S t        |d   t
        t        f      rt        |d   t
        t        f      sdt	        |      z  S y)zValidate each set of coordsz)Points must be a list of coordinate pairs   z*Value (%s) must be a two-dimensional pointr   r   z.Both values (%s) in point must be float or intN)r'   rK   rL   rw   reprfloatintrY   s     r8   r   z GeoJsonBaseField._validate_points  sj    %$/>Uq?$u+MME!Hucl3:!Hucl<
 Dd5kQQ<
r:   c                     t        |t        t        f      sy	 |d   d    g }|D ],  }| j                  |      }|s||vs|j                  |       . |rddj                  |      z  S y # t        t        f$ r Y yw xY w)Nz"MultiPoint must be a list of Pointr   z8Invalid MultiPoint must contain at least one valid pointr   r   r   )r5   rM   rR   pointrU   s        r8   _validate_multipointz%GeoJsonBaseField._validate_multipoint~  s    %$/7	N!HQK  	%E((/Ef,e$	%
 $))F+++  :& 	NM	Ns   A+ +A=<A=c                 4   t        |t        t        f      sy	 |d   d   d    g }|D ]-  }| j                  |d      }|s||vs|j                  |       / |r*|rddj                  |      z  S ddj                  |      z  S y # t        t        f$ r Y yw xY w)Nz,MultiLineString must be a list of LineStringr   zBInvalid MultiLineString must contain at least one valid linestringFzInvalid MultiLineString:
%sr   r   r   )r5   rM   r   rR   
linestringrU   s         r8   _validate_multilinestringz*GeoJsonBaseField._validate_multilinestring  s    %$/A	X!HQKN  	%J--j%@Ef,e$	%
 5		&8IIIdii///	  :& 	XW	Xs   B BBc                    t        |t        t        f      sy	 |d   d   d   d    g }|D ]-  }| j                  |d      }|s||vs|j                  |       / |rddj                  |      z  S y # t        t        f$ r Y yw xY w)Nz&MultiPolygon must be a list of Polygonr   z<Invalid MultiPolygon must contain at least one valid PolygonFzInvalid MultiPolygon:
%sr   )r'   rK   rL   r)   r   r   r   r0   )r5   rM   rR   polygonrU   s        r8   _validate_multipolygonz'GeoJsonBaseField._validate_multipolygon  s    %$/;	R!HQKN1  	%G**7E:Ef,e$	%
 .61BBB  :& 	RQ	Rs   A2 2BBc                 \    t        |t              r|S t        d| j                  fd|fg      S )Nr   r   )r'   r   r   r   rY   s     r8   r]   zGeoJsonBaseField.to_mongo  s/    eT"LVTZZ(=%*@ABBr:   r   )r/   r   r   r   pymongo	GEOSPHEREr   r   r9   rg   r   r   r   r   r   r   r]   r   r   s   @r8   r   r      sF    :""JE*,0.0,	R,&0,C&Cr:   r   )r   rH   r  bsonr   r   r   mongoengine.base.commonr   mongoengine.base.datastructuresr   r   r	   mongoengine.commonr   mongoengine.errorsr   r   __all__r   r   r   r   rX   r:   r8   <module>r
     sg       % % 4 
 - ?
Pp1 p1fw.y w.t+I +@]Cy ]Cr:   