
    W
h/                     H   S SK r S SKrS SKJr  S SKJr  S SKJr  S SKJ	r	J
r
JrJrJrJrJr  S SKJr  S SKJrJr  S SKJrJrJr  S S	KJrJrJr  S S
KJr  S SKJ r J!r!J"r"J#r#  Sr$S r% " S S\&5      r' " S S\
\S9r( " S S\
\S9r) " S S\)\S9r* " S S\(\S9r+ " S S5      r,g)    N)DBRef)ReadPreference)signals)BaseDictBaseDocumentBaseListDocumentMetaclassEmbeddedDocumentListTopLevelDocumentMetaclassget_document_import_class)DEFAULT_CONNECTION_NAMEget_db)set_write_concernswitch_collection	switch_db)InvalidDocumentErrorInvalidQueryErrorSaveConditionError)list_collection_names)NotUniqueErrorOperationErrorQuerySet	transform)DocumentEmbeddedDocumentDynamicDocumentDynamicEmbeddedDocumentr   InvalidCollectionErrorr   MapReduceDocumentc                     Sn[        U 5      (       a[  [        U S   [        5      (       a
  U S   nUS:H  $ [        U S   [        [        45      (       a  [        U S   5      (       a  U S   S   nUS:H  $ )z8Helper function used for ensuring and comparing indexes.Nr   _cls)len
isinstancestrlisttuple)fieldsfirst_fields     \C:\Users\julio\Documents\inmuebles-mzt\backend\env\Lib\site-packages\mongoengine/document.pyincludes_clsr,   1   sr    K
6{{fQi%% )K &   q	D%=11c&)nn )A,K&      c                       \ rS rSrSrg)r    <    N)__name__
__module____qualname____firstlineno____static_attributes__r0   r-   r+   r    r    <   s    r-   r    c                   h   ^  \ rS rSrSrSr\rSrU 4S jr	S r
S rU 4S jrU 4S	 jrU 4S
 jrSrU =r$ )r   @   ay  A :class:`~mongoengine.Document` that isn't stored in its own
collection.  :class:`~mongoengine.EmbeddedDocument`\ s should be used as
fields on :class:`~mongoengine.Document`\ s through the
:class:`~mongoengine.EmbeddedDocumentField` field type.

A :class:`~mongoengine.EmbeddedDocument` subclass may be itself subclassed,
to create a specialised version of the embedded document that will be
stored in the same collection. To facilitate this behaviour a `_cls`
field is added to documents (hidden though the MongoEngine interface).
To enable this behaviour set :attr:`allow_inheritance` to ``True`` in the
:attr:`meta` dictionary.
)	_instanceNc                 B   > [         TU ]  " U0 UD6  S U l        / U l        g N)super__init__r8   _changed_fields)selfargskwargs	__class__s      r+   r<   EmbeddedDocument.__init__Y   s$    $)&)!r-   c                 j    [        XR                  5      (       a  U R                  UR                  :H  $ g)NF)r%   rA   _datar>   others     r+   __eq__EmbeddedDocument.__eq__^   s'    e^^,,::,,r-   c                 .    U R                  U5      (       + $ r:   )rG   rE   s     r+   __ne__EmbeddedDocument.__ne__c   s    ;;u%%%r-   c                 .   > [         TU ]  5       nS US'   U$ Nr8   )r;   __getstate__)r>   datarA   s     r+   rN   EmbeddedDocument.__getstate__f   s    w#% [r-   c                 8   > [         TU ]  U5        US   U l        g rM   )r;   __setstate__r8   )r>   staterA   s     r+   rR   EmbeddedDocument.__setstate__k   s    U#{+r-   c                 F   > [         TU ]  " U0 UD6nSU;   a	  US   c  US	 U$ )N_id)r;   to_mongor>   r?   r@   rO   rA   s       r+   rW   EmbeddedDocument.to_mongoo   s5    w00 D=T%[0Ur-   )r=   r8   )r1   r2   r3   r4   __doc__	__slots__r	   my_metaclass__hash__r<   rG   rJ   rN   rR   rW   r5   __classcell__rA   s   @r+   r   r   @   s@     I %L H"

&
, r-   r   )	metaclassc                     ^  \ rS rSrSr\rSr\S 5       r	\	R                  S 5       r	U 4S jr\S 5       r\S 5       r\S	 5       r\S
 5       r\S 5       rU 4S jrS%S jr         S&S jrS rS rS rS rS r\S 5       r\S 5       rS rS%S jrS'S jrS'S jrS(S jr S r!S r"S r#\S 5       r$\S 5       r%\S)S  j5       r&\S! 5       r'\S" 5       r(\S# 5       r)S$r*U =r+$ )*r   y   aD
  The base class used for defining the structure and properties of
collections of documents stored in MongoDB. Inherit from this class, and
add fields as class attributes to define a document's structure.
Individual documents may then be created by making instances of the
:class:`~mongoengine.Document` subclass.

By default, the MongoDB collection used to store documents created using a
:class:`~mongoengine.Document` subclass will be the name of the subclass
converted to snake_case. A different collection may be specified by
providing :attr:`collection` to the :attr:`meta` dictionary in the class
definition.

A :class:`~mongoengine.Document` subclass may be itself subclassed, to
create a specialised version of the document that will be stored in the
same collection. To facilitate this behaviour a `_cls`
field is added to documents (hidden though the MongoEngine interface).
To enable this behaviour set :attr:`allow_inheritance` to ``True`` in the
:attr:`meta` dictionary.

A :class:`~mongoengine.Document` may use a **Capped Collection** by
specifying :attr:`max_documents` and :attr:`max_size` in the :attr:`meta`
dictionary. :attr:`max_documents` is the maximum number of documents that
is allowed to be stored in the collection, and :attr:`max_size` is the
maximum size of the collection in bytes. :attr:`max_size` is rounded up
to the next multiple of 256 by MongoDB internally and mongoengine before.
Use also a multiple of 256 to avoid confusions.  If :attr:`max_size` is not
specified and :attr:`max_documents` is, :attr:`max_size` defaults to
10485760 bytes (10MB).

Indexes may be created by specifying :attr:`indexes` in the :attr:`meta`
dictionary. The value should be a list of field names or tuples of field
names. Index direction may be specified by prefixing the field names with
a **+** or **-** sign.

Automatic index creation can be disabled by specifying
:attr:`auto_create_index` in the :attr:`meta` dictionary. If this is set to
False then indexes will not be created by MongoEngine.  This is useful in
production systems where index creation is performed as part of a
deployment system.

By default, _cls will be added to the start of every index (that
doesn't contain a list) if allow_inheritance is True. This can be
disabled by either setting cls to False on the specific index or
by setting index_cls to False on the meta dictionary for the document.

By default, any extra attribute existing in stored data but not declared
in your model will raise a :class:`~mongoengine.FieldDoesNotExist` error.
This can be disabled by setting :attr:`strict` to ``False``
in the :attr:`meta` dictionary.
)	__objectsc                 T    SU R                   ;  a  g[        X R                   S   5      $ )zGet the primary key.id_fieldN)_metagetattr)r>   s    r+   pkDocument.pk   s'     TZZ'tZZ
344r-   c                 4    [        X R                  S   U5      $ )zSet the primary key.re   )setattrrf   )r>   values     r+   rh   ri      s     tZZ
3U;;r-   c                 l   > U R                   c  [        [        U ]  5       $ [	        U R                   5      $ )zReturn the hash based on the PK of this document. If it's new
and doesn't have a PK yet, return the default object hash instead.
)rh   r;   r   r]   hash)r>   rA   s    r+   r]   Document.__hash__   s,     77?t577DGG}r-   c                 T    [        U R                  R                  S[        5      5      $ )zSome Model using other db_aliasdb_alias)r   rf   getr   clss    r+   _get_dbDocument._get_db   s     ciimmJ0GHIIr-   c                     SU l         g)z?Detach the Document class from the (cached) database collectionN)_collectionrs   s    r+   _disconnectDocument._disconnect   s     r-   c                 z   [        U S5      (       a  U R                  Gc  U R                  R                  S5      (       d   U R                  R                  S5      (       a  U R	                  5       U l        O_U R                  R                  S5      (       a  U R                  5       U l        O)U R                  5       nU R                  5       nX   U l        U R                  5       nU R                  R                  SS5      (       a+  UR                  R                  (       a  U R                  5         U R                  $ )a5  Return the PyMongo collection corresponding to this document.

Upon first call, this method:
1. Initializes a :class:`~pymongo.collection.Collection` corresponding
   to this document.
2. Creates indexes defined in this document's :attr:`meta` dictionary.
   This happens only if `auto_create_index` is True.
rx   max_sizemax_documents
timeseriesauto_create_indexT)hasattrrx   rf   rr   _get_capped_collection_get_timeseries_collectionru   _get_collection_nameclient
is_primaryensure_indexes)rt   dbcollection_names      r+   _get_collectionDocument._get_collection   s     sM**coo.Eyy}}Z((CIIMM/,J,J"%"<"<">|,,"%"@"@"B[[]"%":":"<"$"5 Byy}}0$77BII<P<P""$r-   c                    U R                  5       nU R                  5       nU R                  R                  S5      =(       d    SnU R                  R                  S5      nUS-  (       a  US-  S-   S-  nU[	        USS9;   ad  X   nUR                  5       nUR                  S5      U:w  d  UR                  S	5      U:w  a$  [        S
R                  U R                  5      5      eU$ SUS.nU(       a  XGS'   UR                  " U40 UD6$ )z:Create a new or get an existing capped PyMongo collection.r|   i   r}         Tinclude_system_collectionsmaxsizezICannot create collection "{}" as a capped collection as it already exists)cappedr   )
ru   r   rf   rr   r   optionsr    formatrx   create_collection)rt   r   r   r|   r}   
collectionr   optss           r+   r   Document._get_capped_collection   s    [[]224 99==,:
		o6
 c> C!+s2H 34
 
 ,J ((*G{{5!]2gkk&6IX6U,66<fS__6M 
  1'K##O<t<<r-   c                    U R                  5       nU R                  5       nU R                  R                  S5      nU[	        USS9;   a  X   nUR                  5         U$ SUR                  SS5      0nUR                  " SUUS.UD6$ )z>Create a new or get an existing timeseries PyMongo collection.r~   Tr   expireAfterSecondsN)namer~   r0   )ru   r   rf   rr   r   r   popr   )rt   r   r   timeseries_optsr   r   s         r+   r   #Document._get_timeseries_collection  s     [[]224))--534
 
 ,J $o&9&9:NPT&UV## 
 &
 
 	
r-   c                    > [         TU ]  " U0 UD6nUS   c3  U R                  R                  S5      c  US	 U$ U R                  S   US'   U$ )NrV   id)r;   rW   rD   rr   rX   s       r+   rW   Document.to_mongo)  s]    w00 ;zz~~d#+K  #jj.Ur-   c           
      B   Uc  0 nU R                   c  [        S5      eU R                  S   n[        U[        5      (       a  UR                  5       OUR                  U 5      nX1;  a  U R                   X'   OX   U R                   :w  a  [        S5      eUR                  U R                  5        U R                  " S0 UD6R                  " SSS0UD6nUc  gU R                   H!  n[        XU R                  XTU   5      5        M#     UR                  U l        SU l        g)a  Perform an atomic update of the document in the database and reload
the document object using updated version.

Returns True if the document has been updated or False if the document
in the database doesn't match the query.

.. note:: All unsaved changes that have been made to the document are
    rejected if the method returns True.

:param query: the update will be performed only if the document in the
    database matches the query
:param update: Django-style update keyword arguments
z)The document does not have a primary key.re   zAInvalid document modify query: it must modify only this document.newTFr0   )rh   r   rf   r%   dictcopyto_queryr   update_object_key_qsmodify_fields_orderedrk   _reloadr=   _created)r>   queryr   re   updatedfields         r+   r   Document.modify6  s    =E77?&'RSS::j) *5$ 7 7

U^^D=Q "ggEO_'#S 
 	T%%&((#U#**>t>v>?))EDeU^!DE *  '66r-   c
                 *   U	=(       d    0 n	U R                   R                  S5      (       a  [        S5      e[        R                  R
                  " U R                  4SU 0U	D6  U(       a  U R                  US9  Uc  0 nU R                  U R                   S   /S9nSU;  =(       d    U R                  =(       d    Un[        R                  R
                  " U R                  4XS	.U	D6  U R                  5       nU R                  c  U R                  5       nO1U R                   R                  S
S5      (       a  U R                  5          U(       a  U R                  XUS9nOU R                  XU5      u  pUc'  U R                   R                  SS5      =(       d    USLnU(       a5  UUUUS.n
U(       a  U
R!                  U5        XzS'   U R"                  " S0 U
D6  U R                   S   nU(       d   UU R                   R                  S/ 5      ;  a!  U R6                  U   R9                  U5      U U'   [        R:                  R
                  " U R                  4XS	.U	D6  U R=                  5         SU l	        U $ ! [$        R&                  R(                   a  nSn[+        UU-  5      eSnAf[$        R&                  R,                   aJ  nSn[.        R0                  " S[3        U5      5      (       a  Sn[+        UU-  5      e[5        UU-  5      eSnAff = f)a  Save the :class:`~mongoengine.Document` to the database. If the
document already exists, it will be updated, otherwise it will be
created. Returns the saved object instance.

:param force_insert: only try to create a new document, don't allow
    updates of existing documents.
:param validate: validates the document; set to ``False`` to skip.
:param clean: call the document clean method, requires `validate` to be
    True.
:param write_concern: Extra keyword arguments are passed down to
    :meth:`~pymongo.collection.Collection.save` OR
    :meth:`~pymongo.collection.Collection.insert`
    which will be used as options for the resultant
    ``getLastError`` command.  For example,
    ``save(..., write_concern={w: 2, fsync: True}, ...)`` will
    wait until at least two servers have recorded the write and
    will force an fsync on the primary server.
:param cascade: Sets the flag for cascading saves.  You can set a
    default by setting "cascade" in the document __meta__
:param cascade_kwargs: (optional) kwargs dictionary to be passed throw
    to cascading saves.  Implies ``cascade=True``.
:param _refs: A list of processed references used in cascading saves
:param save_condition: only perform save if matching record in db
    satisfies condition(s) (e.g. version number).
    Raises :class:`OperationError` if the conditions are not satisfied
:param signal_kwargs: (optional) kwargs dictionary to be passed to
    the signal calls.

.. versionchanged:: 0.5
    In existing documents it only saves changed fields using
    set / unset.  Saves are cascaded and any
    :class:`~bson.dbref.DBRef` objects that have changes are
    saved as well.
.. versionchanged:: 0.6
    Added cascading saves
.. versionchanged:: 0.8
    Cascade saves are optional and default to False.  If you want
    fine grain control then you can turn off using document
    meta['cascade'] = True.  Also you can pass different kwargs to
    the cascade save using cascade_kwargs which overwrites the
    existing kwargs with custom values.
.. versionchanged:: 0.26
   save() no longer calls :meth:`~mongoengine.Document.ensure_indexes`
   unless ``meta['auto_create_index_on_save']`` is set to True.

abstractz!Cannot save an abstract document.document)cleanNre   )r)   rV   )r   createdauto_create_index_on_saveF)docforce_insertwrite_concerncascade)r   validater   r   _refsz(Tried to save duplicate unique keys (%s)zCould not save document (%s)z^E1100[01] duplicate key	shard_keyr0   )rf   rr   r   r   pre_savesendrA   r   rW   r   pre_save_post_validationrx   r   r   _save_create_save_updater   cascade_savepymongoerrorsDuplicateKeyErrorr   OperationFailurerematchr&   r   _fields	to_python	post_save_clear_changed_fields)r>   r   r   r   r   r   cascade_kwargsr   save_conditionsignal_kwargsr@   doc_idr   r   _	object_iderrmessagere   s                      r+   saveDocument.savec  s   v &+::>>*%%&'JKKdnnMtM}MMMM& Mtzz*'=&>?v%FF,((--NN	
%)	
>K	
 mmo
 #$$&AZZ^^7??!$	0 --m . 	 &*%6%6&"	 **..E:XnTX>X$0 (%2&	 "MM.1"'w!!+F+ ::j)hdjjnn["&EE!\\(3==iHDNNN	
%)	
>K	
 	""$1 ~~// 	0@G 3//~~.. 	04Gxx2CH== E$Ws]33 3//	0s&   
BI9 9LJ''!LALLc                    U R                  5       n[        XC5       nU(       a$  UR                  U5      R                  sSSS5        $ SU;   a>  SUS   0nU R	                  X5      nUR                  Xa5      nU(       a  US   sSSS5        $ UR                  U5      R                  nSSS5        U$ ! , (       d  f       W$ = f)zHSave a new document.

Helper method, should only be used inside save().
NrV   )r   r   
insert_oneinserted_id_integrate_shard_keyfind_one_and_replace)	r>   r   r   r   r   wc_collectionselect_dict
raw_objectr   s	            r+   r   Document._save_create  s    
 ))+
z9]$//4@@ :9
 |$c%j1"77I*??Q
u: :9 &005AAI :  :9 s   "B1:B1B11
C c                 Z    U R                  5       u  p0 nU(       a  XS'   U(       a  X#S'   U$ )zReturn a dict containing all the $set and $unset operations
that should be sent to MongoDB based on the changes made to this
Document.
z$setz$unset)_delta)r>   updatesremovals
update_docs       r+   _get_update_docDocument._get_update_doc  s3    
 !KKM
!(v#+x r-   c                 $   U R                   R                  S[        5       5      nU H`  nU R                  UR	                  S5      5      nU Vs/ s H  ofR
                  PM     nnUnU H  n	X   nM	     XSR                  U5      '   Mb     U$ s  snf )zIntegrates the collection's shard key to the `select_dict`, which will be used for the query.
The value from the shard key is taken from the `doc` and finally the select_dict is returned.
r   .)rf   rr   r(   _lookup_fieldsplitdb_fieldjoin)
r>   r   r   r   kpathp
actual_keyvalaks
             r+   r   Document._integrate_shard_key  s     JJNN;8	A%%aggcl3D.23d**dJ3C g !03,-   4s   Bc                    U R                  5       nUS   nSn0 nUb!  [        R                  " U R                  40 UD6nXWS'   U R	                  X5      nU R                  5       nU(       ah  USL n	[        XC5       n
U
R                  XxU	S9R                  nSSS5        U	(       d  WS   S:X  a  [        S5      eWb  UR                  S5      nUSL a  S	nXV4$ ! , (       d  f       NG= f)
zPUpdate an existing document.

Helper method, should only be used inside save().
rV   FN)upsertnr   z2Race condition preventing document update detectedupdatedExistingT)r   r   r   rA   r   r   r   
update_one
raw_resultr   rr   )r>   r   r   r   r   r   r   r   r   r   r   
last_errorupdated_existings                r+   r   Document._save_update'  s    
 ))+
J	%#//$..KNKK&E//A))+
#t+F":=*55F 6 *  > jo2(H  %#->>2C#D #u,"G
 !!! >=s   9C
C#c                 D   UR                  S5      =(       d    / n[        S5      n[        S5      nU R                  R                  5        H  u  pV[	        XcU45      (       d  M  U R
                  R                  U5      nU(       a  [	        U[        5      (       a  MR  [        USS5      (       d  Mf  UR                  R                   S[        UR
                  5       3nU(       d  M  X;  d  M  UR                  U5        X!S'   UR                  " S0 UD6  / Ul        M     g)	zHRecursively save any references and generic references on the
document.
r   ReferenceFieldGenericReferenceFieldr=   T,Nr0   )rr   r   r   itemsr%   rD   r   rg   rA   r1   r&   appendr   r=   )	r>   r@   r   r   r  r   rt   refref_ids	            r+   r   Document.cascade_saveM  s     

7#)r&'78 -.E F++-IDc4I#JKK**..&C*S%003 1488../qSYY0@AFsv*V$"'w"6"&(#! .r-   c                     [        U S5      (       dF  U R                  R                  S[        5      nU" U R                  U R                  5       5      U l        U R                  $ )z;Return the default queryset corresponding to this document.rc   queryset_class)r   rf   rr   r   rA   r   _Document__objects)r>   r	  s     r+   r   Document._qsh  sK     t[))!ZZ^^,<hGN+DNND<P<P<RSDN~~r-   c                    SU R                   0nU R                  R                  R                  S[	        5       5      nU H=  nU nUR                  S5      nU H  n[        XF5      nM     XASR                  U5      '   M?     U$ )a  Return a query dict that can be used to fetch this document.

Most of the time the dict is a simple PK lookup, but in case of
a sharded collection with a compound shard key, it can contain a more
complex query.

Note that the dict returned by this method uses MongoEngine field
names instead of PyMongo field names (e.g. "pk" instead of "_id",
"some__nested__field" instead of "some.nested.field", etc.).
rh   r   r   __)rh   rA   rf   rr   r(   r   rg   r   )r>   r   r   r   r   field_partsparts          r+   r   Document._object_keyp  sx     TWWoNN((,,[%'B	AC''#,K#c( $25		+./  r-   c                 V   U R                   cg  UR                  SS5      (       aE  U R                  5       nSU;   a  US	 U R                  R                  " S0 UD6R
                  " S0 UD6$ [        S5      eU R                  R                  " S0 U R                  D6R
                  " S0 UD6$ )zPerforms an update on the :class:`~mongoengine.Document`
A convenience wrapper to :meth:`~mongoengine.QuerySet.update`.

Raises :class:`OperationError` if called on an object that has not yet
been saved.
r   Fr#   z*attempt to update a document not yet savedr0   )rh   rr   rW   r   filterr   r   r   )r>   r@   r   s      r+   r   Document.update  s     77?zz(E**U?fxx//::DVDD$%QRR xx2!1!12==GGGr-   c                 j   U=(       d    0 n[         R                  R                  " U R                  4SU 0UD6  [	        S5      nU R
                  R                  5        H0  u  pE[        XS5      (       d  M  [        X5      R                  5         M2      U R                  R                  " S0 U R                  D6R                  USS9  [         R$                  R                  " U R                  4SU 0UD6  g! [        R                  R                   a  nSUR                   -  n[#        U5      eSnAff = f)a  Delete the :class:`~mongoengine.Document` from the database. This
will only take effect if the document has been previously saved.

:param signal_kwargs: (optional) kwargs dictionary to be passed to
    the signal calls.
:param write_concern: Extra keyword arguments are passed down which
    will be used as options for the resultant ``getLastError`` command.
    For example, ``save(..., w: 2, fsync: True)`` will
    wait until at least two servers have recorded the write and
    will force an fsync on the primary server.
r   	FileFieldT)r   _from_doc_deletezCould not delete document (%s)Nr0   )r   
pre_deleter   rA   r   r   r  r%   rg   deleter   r  r   r   r   r   r?   r   post_delete)r>   r   r   r  r   r   r   r   s           r+   r  Document.delete  s     &+OOO "+.	<<--/KD%++#**, 0	*HHOO/d../66+d 7  	  P$P-P ~~.. 	*6AG ))	*s   4C5 5D2D--D2c                 \  ^^ [        U R                  U5       nUR                  5       mUR                  5       mSSS5        U4S jU l        U4S jU l        TU l        U(       d  SOU R
                  U l        U R                  U l        TU R                  l        U $ ! , (       d  f       Ni= f)a  
Temporarily switch the database for a document instance.

Only really useful for archiving off data and calling `save()`::

    user = User.objects.get(id=user_id)
    user.switch_db('archive-db')
    user.save()

:param str db_alias: The database alias to use for saving the document

:param bool keep_created: keep self._created value after switching db, else is reset to True


.. seealso::
    Use :class:`~mongoengine.context_managers.switch_collection`
    if you need to read from another collection
Nc                     > T $ r:   r0   r   s   r+   <lambda>$Document.switch_db.<locals>.<lambda>      zr-   c                     > T $ r:   r0   )r   s   r+   r  r    s    rr-   T)	r   rA   r   ru   rx   r   r   r
  _collection_obj)r>   rq   keep_createdrt   r   r   s       @@r+   r   Document.switch_db  s    & t~~x0C,,.JB 1  2!%$0dmm)3& 10s   !B
B+c                 $  ^ [        U R                  U5       nUR                  5       mSSS5        U4S jU l        TU l        U(       d  SOU R                  U l        U R
                  U l        TU R                  l        U $ ! , (       d  f       N^= f)a  
Temporarily switch the collection for a document instance.

Only really useful for archiving off data and calling `save()`::

    user = User.objects.get(id=user_id)
    user.switch_collection('old-users')
    user.save()

:param str collection_name: The database alias to use for saving the
    document

:param bool keep_created: keep self._created value after switching collection, else is reset to True


.. seealso::
    Use :class:`~mongoengine.context_managers.switch_db`
    if you need to read from another database
Nc                     > T $ r:   r0   r  s   r+   r  ,Document.switch_collection.<locals>.<lambda>  r   r-   T)r   rA   r   rx   r   r   r
  r"  )r>   r   r#  rt   r   s       @r+   r   Document.switch_collection  sn    ( t~~?3,,.J @1%$0dmm)3& @?s   B
Bc                 @    [        S5      nU" 5       " U /US-   5        U $ )zHandles dereferencing of :class:`~bson.dbref.DBRef` objects to
a maximum depth in order to cut down the number queries to mongodb.
DeReferencer   r   )r>   	max_depthr*  s      r+   select_relatedDocument.select_related  s%     $M2tfi!m,r-   c                    SnU(       a#  [        US   [        5      (       a  US   nUSS nOSU;   a  US   nU R                  c  U R                  S5      eU R                  R                  [        R                  5      R                  " S0 U R                  D6R                  " U6 R                  S5      R                  US9nU(       a  US   nOU R                  S5      eUR                   H0  nU(       a  XQ;   d  M   [        XU R                  XTU   5      5        M2     U(       a*  [)        [+        U R,                  5      [+        U5      -
  5      OUR,                  U l        SU l        U $ ! [         ["        4 aV     [        XU R                  XTR                  R%                  U5      5      5         M  ! [          a    ['        X5          M  f = ff = f)	zReloads all attributes from the database.

:param fields: (optional) args list of fields to reload
:param max_depth: (optional) depth of dereferencing to follow
r   r   Nr+  zDocument does not exist)r+  Fr0   )r%   intrh   DoesNotExistr   read_preferencer   PRIMARYr  r   onlylimitr,  rD   rk   r   KeyErrorAttributeErrorrr   delattrr'   setr=   r   )r>   r)   r@   r+  objr   s         r+   reloadDocument.reload  s    	jC00q	IABZFF"{+I77?##$=>> HH$$^%;%;<V (&&(T U1X^i^0 	 a&C##$=>>YYEU_-DeZ)HI "  T))*S[89$$ 	
 # !.1 	--  T\\%uAU-VW# -  ,,	-	-s*   >E++G<4F33GGGGc           	      2   [        U[        5      (       aB  UR                  5        VVs/ s H  u  p4X0R                  X45      4PM     nnn[        X U5      nU$ [        U[        5      (       a.  U Vs/ s H  o@R                  X5      PM     nn[	        X U5      nU$ [        U[
        5      (       a.  U Vs/ s H  o@R                  X5      PM     nn[        X U5      nU$ [        U[        [        45      (       a  SUl        / Ul	        U$ s  snnf s  snf s  snf )z_Used by :meth:`~mongoengine.Document.reload` to ensure the
correct instance is linked to self.
N)
r%   r   r  r   r
   r   r   r   r8   r=   )r>   keyrl   r   vs        r+   r   Document._reload-  s    eX&&9>Gaa+,EGU#.E  3443895a\\#)5E9(c:E  x((3895a\\#)5E9U#.E   02IJKK"EO$&E! H : :s   D	1D4Dc                     U R                   c  Sn[        U5      e[        U R                  R	                  5       U R                   5      $ )zNReturns an instance of :class:`~bson.dbref.DBRef` useful in
`__raw__` queries.z+Only saved documents can have a valid dbref)rh   r   r   rA   r   )r>   msgs     r+   to_dbrefDocument.to_dbref?  s;     77??C %%T^^88:DGGDDr-   c                    U R                    Vs/ s H  nX@R                  :w  d  M  [        U5      PM!     snU /-   nUR                    Vs/ s H  nXAR                  :w  d  M  [        U5      PM!     snU/-   nU HC  nU H:  nUR                  R	                  S5      =(       d    0 nX8X4'   XR                  S'   M<     ME     gs  snf s  snf )zKThis method registers the delete rules to apply when removing this
object.
delete_rulesN)_subclassesr1   r   rf   rr   )	rt   document_cls
field_namerule
class_nameclasses	documentsklassrE  s	            r+   register_delete_ruleDocument.register_delete_ruleG  s     "oo
-
\\) %L$-
 E	 +66
6
222 %L$6
 N		 E )${{~>D";?l78.:N+ !* 


s   CC
C!Cc                     U R                  5       nU(       d  [        SU -  5      eSU l        U R                  5       nUR	                  U5        g)zDrops the entire collection associated with this
:class:`~mongoengine.Document` type from the database.

Raises :class:`OperationError` if the document has no collection set
(i.g. if it is `abstract`)
z8Document %s has no collection defined (is it abstract ?)N)r   r   rx   ru   drop_collection)rt   	coll_namer   s      r+   rQ  Document.drop_collection]  sL     ,,.	 JSP  [[]
9%r-   c                     U R                  U5      nUR                  5       nUR                  S5      nX$S'   UR                  U5        U R	                  5       R
                  " U40 UD6$ )a  Creates the given indexes if required.

:param keys: a single index key or a list of index keys (to
    construct a multi-field index); keys may be prefixed with a **+**
    or a **-** to determine the index ordering
:param background: Allows index creation in the background
r)   
background)_build_index_specr   r   r   r   create_index)rt   keysrU  r@   
index_specr)   s         r+   rW  Document.create_indexn  sc     **40
__&
)#-< &!""$11&GJGGr-   c                    U R                   R                  SS5      nU R                   R                  S5      =(       d    0 nU R                   R                  SS5      nU R                  5       nSnU R                   S   (       a  U R                   S   nU Hw  nUR                  5       nUR	                  S5      nU=(       d    [        U5      nUR                  5       n	U	R                  U5        SU	;   a  U	S	 UR                  " U4S	U0U	D6  My     U(       aG  U(       d?  U R                   R                  S
5      (       a  SU;   a  US	 UR                  " SS	U0UD6  gggg)a  Checks the document meta data and ensures all the indexes exist.

Global defaults can be set in the meta - see :doc:`guide/defining-documents`

By default, this will get called automatically upon first interaction with the
Document collection (query, save, etc) so unless you disabled `auto_create_index`, you
shouldn't have to call this manually.

This also gets called upon every call to Document.save if `auto_create_index_on_save` is set to True

If called multiple times, MongoDB will not re-recreate indexes if they exist already

.. note:: You can disable automatic index creation by setting
          `auto_create_index` to False in the documents meta data
index_backgroundF
index_opts	index_clsTindex_specsr)   rt   rU  allow_inheritanceN)r#   )rf   rr   r   r   r   r,   r   rW  )
rt   rU  r]  r^  r   cls_indexedrY  specr)   r   s
             r+   r   Document.ensure_indexes  s3   " YY]]#5u=
YY]]<06B
IIMM+t4	((*
  99]#=1J"yy{(+)A\&-A!(D! D=U''N:NN #  [SYY]];N-O-O 
"u%##PzPZP .P[9r-   c                   ^^ U R                   R                  S5      (       a  / $ / mUU4S jmT" U 5        S n/ nT H*  nU" U5       H  nXB;  d  M
  UR                  U5        M     M,     S/U;  a  UR                  S/5        U R                   R                  SS5      (       a2  U R                   R                  S5      (       a  UR                  S/5        U$ )	zLists all indexes that should be created for the Document collection.
It includes all the indexes from super- and sub-classes.

Note that it will only return the indexes' fields, not the indexes' options
r   c                   > U T;  a&  [        U [        5      (       a  TR                  U 5        U R                   H  n[        U[        5      (       d  M  U[        :w  d  M&  UR
                  R                  S5      (       a  MH  UR                  5       R                  U R                  5       R                  :X  d  M  UT;  d  M  TR                  U5        T" U5        M     U R                  5        Hs  n[        W[        5      (       d  M  UR                  5       R                  U R                  5       R                  :X  d  MR  UT;  d  MZ  TR                  U5        T" U5        Mu     g )Nr   )
r%   r   r  	__bases__r   rf   rr   r   	full_name__subclasses__)rt   base_clssubclassrK  get_classess      r+   rk  *Document.list_indexes.<locals>.get_classes  s
   '!j6O&P&Ps#MMx)BCC H,$NN..z:: 002<<**,667 /NN8,) *  ..0x)BCC 002<<**,667 /NN8,) 1r-   c                     / nU R                   S   (       aJ  U R                   S   nU H5  nUR                  5       nUR                  S5      nUR                  U5        M7     U$ )Nr_  r)   )rf   r   r   r  )rt   indexesrY  rb  r)   s        r+   get_indexes_spec/Document.list_indexes.<locals>.get_indexes_spec  sW    Gyy' YY}5
&D99;D!XXh/FNN6* ' Nr-   )rV   r   r^  Tr`  r#   r   )rf   rr   r  )rt   ro  rn  rM  indexrK  rk  s        @@r+   list_indexesDocument.list_indexes  s     99==$$I 	*2 	C		 E)%0'NN5) 1  <w&NNJ<(99==d++		>Q0R0RNNK=)r-   c                    U R                  5       n/ nU R                  5       nUR                  5       R                  5        Hr  nSUS   S   ;   aO  US   S   S   nUR	                  S5      R                  5       nUR                  U Vs/ s H  owU4PM     sn5        M^  UR                  US   5        Mt     U Vs/ s H  oU;  d  M
  UPM     n	nU Vs/ s H  oU;  d  M
  UPM     n
nS/U	;   a?  SnU H  n[        U5      (       d  M  X;  d  M  Sn  O   U(       a  U	R                  S/5        XS	.$ s  snf s  snf s  snf )
zwCompares the indexes defined in MongoEngine with the ones
existing in the database. Returns any missing/extra indexes.
_ftsr=  r   r   weightsrq  FT)missingextra)	rs  r   index_informationvaluesrr   rX  r  r,   remove)rt   requiredexistingr   info
index_typetext_index_fieldsr=  rr  rx  ry  cls_obsoletes               r+   compare_indexesDocument.compare_indexes  s>    ##%((*
00299;DeQ'!%[^A.
$(HHY$7$<$<$>!>O P>Osz!2>O PQU, < '/HhUx2G5hH$,FH5X0EHF =G# L!&&5+=#'L " }-"33! !Q IFs   	D3
;	D8D8	D=!D=)rc   r=   rx   r   r   ru   r:   )	FTTNNNNNN)T)r   )F),r1   r2   r3   r4   rZ   r   r\   r[   propertyrh   setterr]   classmethodru   ry   r   r   r   rW   r   r   r   r   r   r   r   r   r   r   r  r   r   r,  r:  r   rB  rN  rQ  rW  r   rs  r  r5   r^   r_   s   @r+   r   r   y   s   1h -LI5 5 YY< < J J    8 #= #=J 
 
(+^ L\,"$"L)6    *H&Q<<:1f$E ; ;* & &  H H  5Q 5Qn ? ?B 4 4r-   r   c                   4   ^  \ rS rSrSr\rSrU 4S jrSr	U =r
$ )r   i  a  A Dynamic Document class allowing flexible, expandable and uncontrolled
schemas.  As a :class:`~mongoengine.Document` subclass, acts in the same
way as an ordinary document but has expanded style properties.  Any data
passed or set against the :class:`~mongoengine.DynamicDocument` that is
not a field is automatically converted into a
:class:`~mongoengine.fields.DynamicField` and data can be attributed to that
field.

.. note::

    There is one caveat on Dynamic Documents: undeclared fields cannot start with `_`
Tc                    > US   nX0R                   ;   a!  [        XS5        SU R                   U   l        g[        TU ]  " U0 UD6  g)IDelete the attribute by setting to None and allowing _delta
to unset it.
r   NF)_dynamic_fieldsrk   nullr;   __delattr__)r>   r?   r@   rH  rA   s       r+   r  DynamicDocument.__delattr__.  sI     !W
---Dd+49D  ,1G00r-   r0   )r1   r2   r3   r4   rZ   r   r\   _dynamicr  r5   r^   r_   s   @r+   r   r     s     -LH	1 	1r-   r   c                   &    \ rS rSrSr\rSrS rSr	g)r   i:  zA Dynamic Embedded Document class allowing flexible, expandable and
uncontrolled schemas. See :class:`~mongoengine.DynamicDocument` for more
information about dynamic documents.
Tc                     US   nX0R                   ;   a=  U R                   U   R                  n[        U5      (       a  U" 5       n[        XU5        g[        XS5        g)r  r   N)r   defaultcallablerk   )r>   r?   r@   rH  r  s        r+   r  #DynamicEmbeddedDocument.__delattr__E  sQ     !W
%ll:.66G  !)Dg.Dd+r-   r0   N)
r1   r2   r3   r4   rZ   r	   r\   r  r  r5   r0   r-   r+   r   r   :  s     %LH,r-   r   c                   .    \ rS rSrSrS r\S 5       rSrg)r!   iS  a  A document returned from a map/reduce query.

:param collection: An instance of :class:`~pymongo.Collection`
:param key: Document/result key, often an instance of
            :class:`~bson.objectid.ObjectId`. If supplied as
            an ``ObjectId`` found in the given ``collection``,
            the object can be accessed via the ``object`` property.
:param value: The result(s) for this key.
c                 4    Xl         X l        X0l        X@l        g r:   )	_documentrx   r=  rl   )r>   r   r   r=  rl   s        r+   r<   MapReduceDocument.__init__^  s    !%
r-   c                    U R                  5       R                  S   n[        U5      n[        U R                  U5      (       d   U" U R                  5      U l        [        U S5      (       d@  U R                   R                  R                  U R                  5      U l
        U R                  $ U R                  $ ! [
         a    [        SUR                  -  5      ef = f)z]Lazy-load the object referenced by ``self.key``. ``self.key``
should be the ``primary_key``.
re   zCould not cast key as %s_key_object)r  rf   typer%   r=  	Exceptionr1   r   objectswith_idr  )r>   re   id_field_types      r+   objectMapReduceDocument.objectd  s    
 >>#))*5X$((M22U(2 t]++#~~55==dhhGD###  U :]=S=S STTUs   B9 9#C)rx   r  r  r=  rl   N)	r1   r2   r3   r4   rZ   r<   r  r  r5   r0   r-   r+   r!   r!   S  s         r-   r!   )-r   r   
bson.dbrefr   pymongo.read_preferencesr   mongoenginer   mongoengine.baser   r   r   r	   r
   r   r   mongoengine.commonr   mongoengine.connectionr   r   mongoengine.context_managersr   r   r   mongoengine.errorsr   r   r   mongoengine.pymongo_supportr   mongoengine.querysetr   r   r   r   __all__r,   r  r    r   r   r   r   r!   r0   r-   r+   <module>r     s    	   3    - B 
 
 > 	!	Y 	6|/@ 6r_4|'@ _4D1h*C 1>,.:K ,2"  " r-   