
    +h"                        d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlmZ d dlZd dlmZ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 d dlmZ ddlm Z m!Z!m"Z" ddl#m$Z$ ddl#m%Z% ddl&m'Z' 	 d dl(m)Z) d dl(m*Z* 	 d dl-m.Z/ dZ2ejf                  dk(  r)ejh                  dk\  rejj                  Z6nejn                  Z6nej
                  Z6 e       Z8e8js                  d      Z:e8js                  d      Z;d Z<d Z=d Z>d Z?d Z@d ZA G d  d!eB      ZCd" ZD G d# d$e      ZE G d% d&eF      ZG G d' d(eF      ZHd) ZI G d* d+eF      ZJ G d, d-ej                        ZL G d. d/eF      ZMd0 ZN G d1 d2eF      ZOd3 ZP G d4 d5eF      ZQ G d6 d7eF      ZR G d8 d9e$      ZS G d: d;eT      ZU ej                  d<eU       y# e+$ r d dl,m)Z) d dl,m*Z* Y Jw xY w# e+$ r 	 d dlm0Z/ n# e+$ r	 d dl1m0Z/ Y nw xY wY hw xY w)=    )absolute_importN)ceil)
itemgetter)Lock)_app_ctx_stackabortcurrent_apprequest)	Namespace)eventinspectorm)make_url)UnmappedClassError)Session   )
itervaluesstring_typesxrange)DefaultMeta)Model)utils)declarative_base)DeclarativeMeta)
getcurrent)	get_identz2.5.1win32)   r   zmodels-committedzbefore-models-committedc                     	  | j                   di |} | S # t        $ r) |j                         D ]  \  }}t        | ||        Y | S w xY w)N )setAttributeErroritemssetattr)urlkwargskeyvalues       L/var/www/html/venv/lib/python3.12/site-packages/flask_sqlalchemy/__init__.py_sa_url_setr*   =   s^    %cgg J  % ,,. 	%JCCe$	% J%s    .AAc                     t        | j                        }|j                         D ]  \  }}|j                  ||        t	        | |      S )N)query)dictr,   r#   
setdefaultr*   )r%   r&   r,   r'   r(   s        r)   _sa_url_query_setdefaultr/   H   sG    OElln %
Ue$% s%((    c                       fd}|S )Nc                     t        |       dkD  r0t        | d   j                        r| d   j                  f| dd  z   } |j	                  dd       xs i }|j                  dd        ||d<   t        j                  | i |S )Nr   r   infobind_key)len
isinstanceColumnmetadatapopr.   
sqlalchemyTable)argsr&   r3   dbs      r)   _make_tablez _make_table.<locals>._make_tableR   s~    t9q=ZQ;GR[[)DH4Dzz&$'-2
D)v000r0   r    )r=   r>   s   ` r)   r>   r>   Q   s    1 r0   c                     d| vr|| d<   y y )Nquery_classr    )dclss     r)   _set_default_query_classrC   \   s    A- r0   c                 F     t        j                          fd       }|S )Nc                      t        |       d|v r(|d   }t        |t              r|i f}t        |d           | i |S )Nbackrefr   )rC   r6   r   )r<   r&   rF   rB   fns      r)   newfnz-_wrap_with_default_query_class.<locals>.newfnb   sP     -Y'G'<0"B-$WQZ54"6""r0   )	functoolswraps)rG   rB   rH   s   `` r)   _wrap_with_default_query_classrK   a   s%    __R# # Lr0   c           
      |   t         t         j                  fD ]7  }|j                  D ]&  }t        | |      rt	        | |t        ||             ( 9 t        |       | _        t        | j                  |      | _	        t        | j                  |      | _
        t        | j                  |      | _        t        | _        y N)r:   r   __all__hasattrr$   getattrr>   r;   rK   relationshiprelationdynamic_loaderr   )objrB   moduler'   s       r)   _include_sqlalchemyrV   n   s    jnn, 8>> 	8C3$S'&#"67	88
 C CI5c6F6FLC1#,,DCL78J8JCPCCIr0   c                       e Zd Z e ed            Z e ed            Z e ed            Z e ed            Z e ed            Z	ed        Z
d Zy)	_DebugQueryTupler   r      r      c                 4    | j                   | j                  z
  S rM   )end_time
start_timeselfs    r)   durationz_DebugQueryTuple.duration   s    }}t..r0   c                 N    d| j                   | j                  | j                  fz  S )Nz3<query statement="%s" parameters=%r duration=%.03f>)	statement
parametersr`   r^   s    r)   __repr__z_DebugQueryTuple.__repr__   s*    DNNOOMMH
 
 	
r0   N)__name__
__module____qualname__propertyr   rb   rc   r]   r\   contextr`   rd   r    r0   r)   rX   rX   {   s_    A'I*Q-(J*Q-(J
1&Hz!}%G/ /
r0   rX   c                 b   t        j                  d      }|j                  |j                  j	                  d      }|rX|| k(  s|j                  | dz         r?|j                  j                  }|j                  j                  d|j                  d|dS |j                  }|j                  y)Nr   re   .:z ()z	<unknown>)
sys	_getframef_back	f_globalsget
startswithf_codeco_nameco_filenamef_lineno)app_pathfrmnamefuncnames       r)   _calling_contextr|      s    
--
C
**
 }}  ,TX%C)Hzz))H

&& 
 jj **
  r0   c                        e Zd ZdZddZddZy)SignallingSessiona  The signalling session is the default session that Flask-SQLAlchemy
    uses.  It extends the default session system with bind selection and
    modification tracking.

    If you want to use a different session you can override the
    :meth:`SQLAlchemy.create_session` function.

    .. versionadded:: 2.0

    .. versionadded:: 2.1
        The `binds` option was added, which allows a session to be joined
        to an external transaction.
    c                 :   |j                         x| _        }|j                  d   }|j                  dd       xs |j                  }|j                  d|j                  |            }||rt        j                  |        t        j                  | f||||d| y )NSQLALCHEMY_TRACK_MODIFICATIONSbindbinds)
autocommit	autoflushr   r   )
get_appappconfigr9   engine	get_binds_SessionSignalEventsregisterSessionBase__init__)	r_   r=   r   r   optionsr   track_modificationsr   r   s	            r)   r   zSignallingSession.__init__   s    %3!jj)IJ{{64(5BIIGR\\#%67&*= ))$/	
'9U	
&-	
r0   Nc                 <   |i	 |j                   }t        |di       }|j	                  d      }|<t        | j                        }|j                  j                  | j                  |      S t        j                  | ||      S # t        $ r |j                  }Y w xY w)zuReturn the engine or connection for a given model or
        table, using the ``__bind_key__`` if it is set.
        r3   r4   )r   )persist_selectabler"   mapped_tablerP   rr   	get_stater   r=   
get_enginer   get_bind)r_   mapperclauser   r3   r4   states          r)   r   zSignallingSession.get_bind   s    
 9%+%>%>"
 -vr:Dxx
+H#!$((+xx**488(*CC##D&&99 " 9%+%8%8"9s   B BB)FTNN)re   rf   rg   __doc__r   r   r    r0   r)   r~   r~      s    
:r0   r~   c                   n    e Zd Zed        Zed        Zedd       Zed        Zed        Z	ed        Z
y)	r   c                 t   t        |d      si |_        t        j                  |d| j                         t        j                  |d| j                         t        j                  |d| j
                         t        j                  |d| j                         t        j                  |d| j                         y N_model_changesbefore_flushbefore_commitafter_commitafter_rollback)rO   r   r   listen
record_opsr   r   r   rB   sessions     r)   r   z_SessionSignalEvents.register   s    w 01%'G"Wncnn=Wos~~>Wos/@/@AWnc.>.>?W.0B0BCr0   c                 j   t        |d      r|`t        j                  |d| j                         t        j                  |d| j                         t        j                  |d| j
                         t        j                  |d| j                         t        j                  |d| j                         y r   )rO   r   r   remover   r   r   r   r   s     r)   
unregisterz_SessionSignalEvents.unregister   s~    7,-&Wncnn=Wos~~>Wos/@/@AWnc.>.>?W.0B0BCr0   Nc                    	 | j                   }| j                  df| j                  df| j                  dffD ]A  \  }}|D ]7  }t        |      }|j                  r|j                  n
t        |      }||f||<   9 C y # t        $ r Y y w xY w)Ninsertupdatedelete)	r   r"   newdirtydeletedr   has_identityidentity_keyid)	r   flush_context	instancesrA   targets	operationtargetr   r'   s	            r)   r   z_SessionSignalEvents.record_ops   s    	&&A %,KK#:W]]H<UX_XgXgiqWr"s 	-GY! -,1,>,>e((BvJ ),#-	-  		s   A< <	BBc                     	 | j                   }|r9t        j                  | j                  t        |j                                      y y # t        $ r Y y w xY wN)changes)r   r"   before_models_committedsendr   listvaluesr   rA   s     r)   r   z"_SessionSignalEvents.before_commit   sR    	&&A #((d188:>N(O   		s   A
 
	AAc                     	 | j                   }|rIt        j                  | j                  t        |j                                      |j                          y y # t        $ r Y y w xY wr   )r   r"   models_committedr   r   r   r   clearr   s     r)   r   z!_SessionSignalEvents.after_commit   s[    	&&A !!'++tAHHJ7G!HGGI   		s   A 	A&%A&c                 \    	 | j                   }|j                          y # t        $ r Y y w xY wrM   )r   r"   r   r   s     r)   r   z#_SessionSignalEvents.after_rollback	  s1    	&&A 	
	  		s    	++r   )re   rf   rg   classmethodr   r   staticmethodr   r   r   r   r    r0   r)   r   r      s~    D D D D 
- 
- P P    r0   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)_EngineDebuggingSignalEventszTSets up handlers for two events that let us track the execution time of
    queries.c                      || _         || _        y rM   )r   app_package)r_   r   import_names      r)   r   z%_EngineDebuggingSignalEvents.__init__  s    &r0   c                     t        j                  | j                  d| j                         t        j                  | j                  d| j                         y )Nbefore_cursor_executeafter_cursor_execute)r   r   r   r   r   r^   s    r)   r   z%_EngineDebuggingSignalEvents.register  s@    KK0$2L2L	
 	KK/1J1J	
r0   c                 0    t         rt               |_        y y rM   )r	   _timer_query_start_time)r_   conncursorrb   rc   ri   executemanys          r)   r   z2_EngineDebuggingSignalEvents.before_cursor_execute#  s     (.G% r0   c                    t         r`	 t        j                  j                  }|j                  t        |||j                  t               t        | j                        f             y y # t        $ r g x}t        j                  _        Y hw xY wrM   )r	   r   topsqlalchemy_queriesr"   appendrX   r   r   r|   r   )r_   r   r   rb   rc   ri   r   queriess           r)   r   z1_EngineDebuggingSignalEvents.after_cursor_execute)  s     E(,,?? NN+:w'@'@&( !1!12-    " EBDD.,,?Es   A( ( B
BN)re   rf   rg   r   r   r   r   r   r    r0   r)   r   r     s    '
1r0   r   c                  8    t        t        j                  dg       S )a  In debug mode Flask-SQLAlchemy will log all the SQL queries sent
    to the database.  This information is available until the end of request
    which makes it possible to easily ensure that the SQL generated is the
    one expected on errors or in unittesting.  If you don't want to enable
    the DEBUG mode for your unittests you can also enable the query
    recording by setting the ``'SQLALCHEMY_RECORD_QUERIES'`` config variable
    to `True`.  This is automatically enabled if Flask is in testing mode.

    The value returned will be a list of named tuples with the following
    attributes:

    `statement`
        The SQL statement issued

    `parameters`
        The parameters for the SQL statement

    `start_time` / `end_time`
        Time the query started / the results arrived.  Please keep in mind
        that the timer function used depends on your platform. These
        values are only useful for sorting or comparing.  They do not
        necessarily represent an absolute timestamp.

    `duration`
        Time the query took in seconds

    `context`
        A string giving a rough estimation of where in your application
        query was issued.  The exact format is undefined so don't try
        to reconstruct filename or function name.
    r   )rP   r   r   r    r0   r)   get_debug_queriesr   8  s    @ >%%';R@@r0   c                       e Zd ZdZd Zed        ZddZed        Zed        Z	ddZ
ed        Zed	        Z	 	 dd
Zy)
Paginationa>  Internal helper class returned by :meth:`BaseQuery.paginate`.  You
    can also construct it from any other SQLAlchemy query object if you are
    working with other libraries.  Additionally it is possible to pass `None`
    as query object in which case the :meth:`prev` and :meth:`next` will
    no longer work.
    c                 J    || _         || _        || _        || _        || _        y rM   )r,   pageper_pagetotalr#   )r_   r,   r   r   r   r#   s         r)   r   zPagination.__init__c  s'     
	 

r0   c                     | j                   dk(  rd}|S t        t        | j                  t	        | j                         z              }|S )zThe total number of pagesr   )r   intr   r   float)r_   pagess     r)   r   zPagination.pagesp  sD     ==AE  TZZ%*>>?@Er0   c                     | j                   J d       | j                   j                  | j                  dz
  | j                  |      S )z;Returns a :class:`Pagination` object for the previous page.2a query object is required for this method to workr   r,   paginater   r   r_   	error_outs     r)   prevzPagination.prevy  F    zz% 	A (A 	A%zz""499q=$--KKr0   c                 :    | j                   sy| j                  dz
  S )zNumber of the previous page.Nr   )has_prevr   r^   s    r)   prev_numzPagination.prev_num       }}yy1}r0   c                      | j                   dkD  S )zTrue if a previous page existsr   )r   r^   s    r)   r   zPagination.has_prev  s     yy1}r0   c                     | j                   J d       | j                   j                  | j                  dz   | j                  |      S )z7Returns a :class:`Pagination` object for the next page.r   r   r   r   s     r)   nextzPagination.next  r   r0   c                 4    | j                   | j                  k  S )zTrue if a next page exists.)r   r   r^   s    r)   has_nextzPagination.has_next  s     yy4::%%r0   c                 :    | j                   sy| j                  dz   S )zNumber of the next pageNr   )r   r   r^   s    r)   next_numzPagination.next_num  r   r0   c              #      K   d}t        d| j                  dz         D ]S  }||k  s:|| j                  |z
  dz
  kD  r|| j                  |z   k  s|| j                  |z
  kD  sB|dz   |k7  rd | |}U yw)u  Iterates over the page numbers in the pagination.  The four
        parameters control the thresholds how many numbers should be produced
        from the sides.  Skipped page numbers are represented as `None`.
        This is how you could render such a pagination in the templates:

        .. sourcecode:: html+jinja

            {% macro render_pagination(pagination, endpoint) %}
              <div class=pagination>
              {%- for page in pagination.iter_pages() %}
                {% if page %}
                  {% if page != pagination.page %}
                    <a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a>
                  {% else %}
                    <strong>{{ page }}</strong>
                  {% endif %}
                {% else %}
                  <span class=ellipsis>…</span>
                {% endif %}
              {%- endfor %}
              </div>
            {% endmacro %}
        r   r   N)r   r   r   )r_   	left_edgeleft_currentright_current
right_edgelastnums          r)   
iter_pageszPagination.iter_pages  s     2 !TZZ!^, 	Cidii,.22dii-//TZZ*,,!8s?J		s   AA5 A5NF)rY   rY      rY   )re   rf   rg   r   r   rh   r   r   r   r   r   r   r   r   r    r0   r)   r   r   [  s      L    L & &   45/0"r0   r   c                   (    e Zd ZdZddZddZddZy)	BaseQueryaZ  SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with convenience methods for querying in a web application.

    This is the default :attr:`~Model.query` object used for models, and exposed as :attr:`~SQLAlchemy.Query`.
    Override the query class for an individual model by subclassing this and setting :attr:`~Model.query_class`.
    Nc                 F    | j                  |      }|t        d|       |S )zPLike :meth:`get` but aborts with 404 if not found instead of returning ``None``.  description)rr   r   )r_   identr  rvs       r)   
get_or_404zBaseQuery.get_or_404  s%     XXe_:#;/	r0   c                 D    | j                         }|t        d|       |S )zRLike :meth:`first` but aborts with 404 if not found instead of returning ``None``.r  r  )firstr   )r_   r  r
  s      r)   first_or_404zBaseQuery.first_or_404  s#     ZZ\:#;/	r0   c                    t         rY|*	 t        t         j                  j                  dd            }|3	 t        t         j                  j                  dd            }n|d}|d}|t        ||      }|dk  r|rt        d       nd}|dk  r|rt        d       nd}| j                  |      j                  |dz
  |z        j                         }|s|dk7  r|rt        d       | j                  d      j                         }t        | ||||      S # t        t
        f$ r |rt        d       d}Y w xY w# t        t
        f$ r |rt        d       d}Y w xY w)a  Returns ``per_page`` items from page ``page``.

        If ``page`` or ``per_page`` are ``None``, they will be retrieved from
        the request query. If ``max_per_page`` is specified, ``per_page`` will
        be limited to that value. If there is no request or they aren't in the
        query, they default to 1 and 20 respectively.

        When ``error_out`` is ``True`` (default), the following rules will
        cause a 404 response:

        * No items are found and ``page`` is not 1.
        * ``page`` is less than 1, or ``per_page`` is negative.
        * ``page`` or ``per_page`` are not ints.

        When ``error_out`` is ``False``, ``page`` and ``per_page`` default to
        1 and 20 respectively.

        Returns a :class:`Pagination` object.
        Nr   r   r  r      r   )r
   r   r<   rr   	TypeError
ValueErrorr   minlimitoffsetallorder_bycountr   )r_   r   r   r   max_per_pager#   r   s          r)   r   zBaseQuery.paginate  sZ   * |w||//:;D ""7<<#3#3J#CDH |#8\2H!8c
a<c


8$++TAX,ABFFHy#Jd#))+$hu==W ":.  c
D	 ":. " c
!H	"s"   )D )D; D87D8;EErM   )NNTN)re   rf   rg   r   r  r  r   r    r0   r)   r  r    s    D>r0   r  c                       e Zd Zd Zd Zy)_QueryPropertyc                     || _         y rM   )sa)r_   r  s     r)   r   z_QueryProperty.__init__!  s	    r0   c                     	 t        j                  |      }|r+|j                  || j                  j	                               S y # t
        $ r Y y w xY w)N)r   )r   class_mapperr@   r  r   r   )r_   rT   typer   s       r)   __get__z_QueryProperty.__get__$  sR    	%%d+F''8I'JJ ! 		s   AA 	AAN)re   rf   rg   r   r!  r    r0   r)   r  r     s    r0   r  c                     | j                   ry| j                  d   }||S t        | j                  j                  d            S )NTSQLALCHEMY_RECORD_QUERIESTESTING)debugr   boolrr   )r   rqs     r)   _record_queriesr(  -  s=    
yy	/	0B	~	

y)**r0   c                   &    e Zd ZddZd Zd Zd Zy)_EngineConnectorNc                 h    || _         || _        d | _        d | _        || _        t               | _        y rM   )_sa_app_engine_connected_for_bindr   _lock)r_   r  r   r   s       r)   r   z_EngineConnector.__init__8  s/    	"
V
r0   c                     | j                   | j                  j                  d   S | j                  j                  j                  d      xs d}| j                   |v sJ d| j                   z         || j                      S )NSQLALCHEMY_DATABASE_URISQLALCHEMY_BINDSr    zPBind %r is not specified.  Set it in the SQLALCHEMY_BINDS configuration variable)r0  r-  r   rr   )r_   r   s     r)   get_uriz_EngineConnector.get_uri@  s}    ::99##$=>>		  $$%78>BzzU" 	2%'+zz2	2" TZZ  r0   c                    | j                   5  | j                         }| j                  j                  d   }||f| j                  k(  r| j
                  cd d d        S t        |      }| j                  ||      \  }}| j                  j                  ||      x| _        }t        | j                        r8t        | j
                  | j                  j                        j                          ||f| _        |cd d d        S # 1 sw Y   y xY w)NSQLALCHEMY_ECHO)r1  r5  r-  r   r/  r.  r   get_optionsr,  create_enginer(  r   r   r   )r_   uriechosa_urlr   r
  s         r)   r   z_EngineConnector.get_engineI  s    ZZ 	,,.C99##$56DT{d111||		 	 c]F"..vt<OFG $ 6 6vw GGDL2tyy),T\\-1YY-B-BDDLHJ#&+D!	 	 	s   ADBDD
c                 V   i }| j                   j                  | j                  |      }| j                   j                  | j                  ||      \  }}|r||d<   |j	                  | j                  j
                  d          |j	                  | j                   j                         ||fS )Nr;  SQLALCHEMY_ENGINE_OPTIONS)r,  apply_pool_defaultsr-  apply_driver_hacksr   r   _engine_options)r_   r<  r;  r   s       r)   r8  z_EngineConnector.get_options\  s    ((..tyy'B((55diiQ"GFO 	tyy''(CDE 	txx//0wr0   rM   )re   rf   rg   r   r5  r   r8  r    r0   r)   r*  r*  6  s    !&r0   r*  c                 J    d| j                   v sJ d       | j                   d   S )z"Gets the state for the applicationr:   zsThe sqlalchemy extension was not registered to the current application.  Please make sure to call init_app() first.)
extensions)r   s    r)   r   r   o  s4    3>>) C	CC) >>,''r0   c                       e Zd ZdZd Zy)_SQLAlchemyStatez0Remembers configuration for the (db, app) tuple.c                      || _         i | _        y rM   )r=   
connectors)r_   r=   s     r)   r   z_SQLAlchemyState.__init__z  s    r0   N)re   rf   rg   r   r   r    r0   r)   rE  rE  w  s
    :r0   rE  c                       e Zd ZdZdZddddeedfdZed        Z	ddZ
d ZddZd	 Zd
 Zd Zed        ZddZddZd ZddZddZddZddZddZddZddZd Zy)
SQLAlchemyap  This class is used to control the SQLAlchemy integration to one
    or more Flask applications.  Depending on how you initialize the
    object it is usable right away or will attach as needed to a
    Flask application.

    There are two usage modes which work very similarly.  One is binding
    the instance to a very specific Flask application::

        app = Flask(__name__)
        db = SQLAlchemy(app)

    The second possibility is to create the object once and configure the
    application later to support it::

        db = SQLAlchemy()

        def create_app():
            app = Flask(__name__)
            db.init_app(app)
            return app

    The difference between the two is that in the first case methods like
    :meth:`create_all` and :meth:`drop_all` will work all the time but in
    the second case a :meth:`flask.Flask.app_context` has to exist.

    By default Flask-SQLAlchemy will apply some backend-specific settings
    to improve your experience with them.

    As of SQLAlchemy 0.6 SQLAlchemy
    will probe the library for native unicode support.  If it detects
    unicode it will let the library handle that, otherwise do that itself.
    Sometimes this detection can fail in which case you might want to set
    ``use_native_unicode`` (or the ``SQLALCHEMY_NATIVE_UNICODE`` configuration
    key) to ``False``.  Note that the configuration key overrides the
    value you pass to the constructor.  Direct support for ``use_native_unicode``
    and SQLALCHEMY_NATIVE_UNICODE are deprecated as of v2.4 and will be removed
    in v3.0.  ``engine_options`` and ``SQLALCHEMY_ENGINE_OPTIONS`` may be used
    instead.

    This class also provides access to all the SQLAlchemy functions and classes
    from the :mod:`sqlalchemy` and :mod:`sqlalchemy.orm` modules.  So you can
    declare models like this::

        class User(db.Model):
            username = db.Column(db.String(80), unique=True)
            pw_hash = db.Column(db.String(80))

    You can still use :mod:`sqlalchemy` and :mod:`sqlalchemy.orm` directly, but
    note that Flask-SQLAlchemy customizations are available only through an
    instance of this :class:`SQLAlchemy` class.  Query classes default to
    :class:`BaseQuery` for `db.Query`, `db.Model.query_class`, and the default
    query_class for `db.relationship` and `db.backref`.  If you use these
    interfaces through :mod:`sqlalchemy` and :mod:`sqlalchemy.orm` directly,
    the default query class will be that of :mod:`sqlalchemy`.

    .. admonition:: Check types carefully

       Don't perform type or `isinstance` checks against `db.Table`, which
       emulates `Table` behavior but is not a class. `db.Table` exposes the
       `Table` interface, but is a function which allows omission of metadata.

    The ``session_options`` parameter, if provided, is a dict of parameters
    to be passed to the session constructor.  See :class:`~sqlalchemy.orm.session.Session`
    for the standard options.

    The ``engine_options`` parameter, if provided, is a dict of parameters
    to be passed to create engine.  See :func:`~sqlalchemy.create_engine`
    for the standard options.  The values given here will be merged with and
    override anything set in the ``'SQLALCHEMY_ENGINE_OPTIONS'`` config
    variable or othewise set by this library.

    .. versionadded:: 0.10
       The `session_options` parameter was added.

    .. versionadded:: 0.16
       `scopefunc` is now accepted on `session_options`. It allows specifying
        a custom function which will define the SQLAlchemy session's scoping.

    .. versionadded:: 2.1
       The `metadata` parameter was added. This allows for setting custom
       naming conventions among other, non-trivial things.

       The `query_class` parameter was added, to allow customisation
       of the query class, in place of the default of :class:`BaseQuery`.

       The `model_class` parameter was added, which allows a custom model
       class to be used in place of :class:`Model`.

    .. versionchanged:: 2.1
       Utilise the same query class across `session`, `Model.query` and `Query`.

    .. versionadded:: 2.4
       The `engine_options` parameter was added.

    .. versionchanged:: 2.4
       The `use_native_unicode` parameter was deprecated.

    .. versionchanged:: 2.4.3
        ``COMMIT_ON_TEARDOWN`` is deprecated and will be removed in
        version 3.1. Call ``db.session.commit()`` directly instead.
    NTc                     || _         || _        | j                  |      | _        | j	                  ||      | _        t               | _        || _        |xs i | _	        t        | |       || j                  |       y y rM   )use_native_unicodeQuerycreate_scoped_sessionr   make_declarative_baser   r   _engine_lockr   rA  rV   init_app)r_   r   rK  session_optionsr8   r@   model_classengine_optionss           r)   r   zSQLAlchemy.__init__  sw     #5 
11/B//XF
 F-3D+.?MM# r0   c                 .    | j                   j                  S )z*The metadata associated with ``db.Model``.)r   r8   r^   s    r)   r8   zSQLAlchemy.metadata  s     zz"""r0   c                     |i }|j                  dt              }|j                  d| j                         t	        j
                  | j                  |      |      S )a-  Create a :class:`~sqlalchemy.orm.scoping.scoped_session`
        on the factory from :meth:`create_session`.

        An extra key ``'scopefunc'`` can be set on the ``options`` dict to
        specify a custom scope function.  If it's not provided, Flask's app
        context stack identity is used. This will ensure that sessions are
        created and removed with the request/response cycle, and should be fine
        in most cases.

        :param options: dict of keyword arguments passed to session class  in
            ``create_session``
        	scopefunc	query_cls)rV  )r9   _ident_funcr.   rL  r   scoped_sessioncreate_session)r_   r   rV  s      r)   rM  z SQLAlchemy.create_scoped_session  sU     ?GKK[9	;

3!!(I
 	
r0   c                 :    t        j                  dt        | d|S )a  Create the session factory used by :meth:`create_scoped_session`.

        The factory **must** return an object that SQLAlchemy recognizes as a session,
        or registering session events may raise an exception.

        Valid factories include a :class:`~sqlalchemy.orm.session.Session`
        class or a :class:`~sqlalchemy.orm.session.sessionmaker`.

        The default implementation creates a ``sessionmaker`` for :class:`SignallingSession`.

        :param options: dict of keyword arguments passed to session class
        )class_r=   r    )r   sessionmakerr~   )r_   r   s     r)   rZ  zSQLAlchemy.create_session  s      M'8TMWMMr0   c                     t        |t              st        |d|t              }||j                  |ur||_        t        |dd      s| j                  |_        t        |       |_	        |S )a|  Creates the declarative base that all models will inherit from.

        :param model: base model class (or a tuple of base classes) to pass
            to :func:`~sqlalchemy.ext.declarative.declarative_base`. Or a class
            returned from ``declarative_base``, in which case a new base class
            is not created.
        :param metadata: :class:`~sqlalchemy.MetaData` instance to use, or
            none to use SQLAlchemy's default.

        .. versionchanged 2.3.0::
            ``model`` can be an existing declarative base in order to support
            complex customization such as changing the metaclass.
        r   )rB   rz   r8   	metaclassNr@   )
r6   r   r   r   r8   rP   rL  r@   r  r,   )r_   modelr8   s      r)   rN  z SQLAlchemy.make_declarative_base(  sg     %1$!%	E ENN($B%ENumT2 $

E$T*r0   c                     dj                   vr#dj                   vrt        j                  d       j                   j                  dd       j                   j                  dd       j                   j                  dd       j                   j                  dd       j                   j                  d	d       j                   j                  d
d       j                   j                  dd       j                   j                  dd       j                   j                  dd       j                   j                  dd       j                   j                  dd      }j                   j                  di        |t        j                  t	        d             t        j                  j                   dd
d       t        j                  j                   ddd       t        j                  j                   ddd       t        j                  j                   ddd       t               j                  d<   j                   fd       }y)zThis callback can be used to initialize an application for the
        use with this database setup.  Never use a database in the context
        of an application not initialized that way or connections will
        leak.
        r3  r4  zxNeither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".zsqlite:///:memory:NSQLALCHEMY_NATIVE_UNICODEr7  Fr#  SQLALCHEMY_POOL_SIZESQLALCHEMY_POOL_TIMEOUTSQLALCHEMY_POOL_RECYCLESQLALCHEMY_MAX_OVERFLOWSQLALCHEMY_COMMIT_ON_TEARDOWNr   r>  zSQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.z3.0	pool_sizepool_timeoutpool_recyclemax_overflowr:   c                     j                   d   r6t        j                  dt               | j                  j                          j                  j                          | S )Nrg  zt'COMMIT_ON_TEARDOWN' is deprecated and will be removed in version 3.1. Call 'db.session.commit()'` directly instead.)r   warningswarnDeprecationWarningr   commitr   )response_or_excr   r_   s    r)   shutdown_sessionz-SQLAlchemy.init_app.<locals>.shutdown_sessionv  sU    zz9:@ '	 #*LL'')LL!""r0   )
r   rm  rn  r.   FSADeprecationWarningr   engine_config_warningrE  rC  teardown_appcontext)r_   r   r   rr  s   ``  r)   rP  zSQLAlchemy.init_appI  s    &SZZ7cjj0MMN
 	

79MN

0$7

94@

/7

94@

4d;

7>

7>

7>

=uE!jj33,d
 	

92>&MM/5  	##CJJ7M{[##CJJ7PR`a##CJJ7PR`a##CJJ7PR`a'7'=|$		 	 	# 
!	#r0   c                 ^    fd} |dd        |dd        |dd        |dd	       S )
z
        .. versionchanged:: 2.5
            Returns the ``options`` dict, for consistency with
            :meth:`apply_driver_hacks`.
        c                 4    j                   |   }||| <   y y rM   )r   )	optionkey	configkeyr(   r   r   s      r)   _setdefaultz3SQLAlchemy.apply_pool_defaults.<locals>._setdefault  s&    JJy)E %*	" !r0   rh  rc  ri  rd  rj  re  rk  rf  r    )r_   r   r   rz  s    `` r)   r?  zSQLAlchemy.apply_pool_defaults  s;    	+ 	K!78N$=>N$=>N$=>r0   c                     |j                   j                  d      rAt        |d      }|j                   dk7  r|j                  dd       |j                  dd       n|j                   d	k(  r|j	                  d      }d
}|j
                  dv r.d}ddlm} ||d<   d|vri |d<   d
|d   d<   |dk(  rt        d      |sddlm	} ||d<   |s?t        |t        j                  j                  |j                  |j
                              }|j                  d   }|| j                   }|sd
|d<   |j                  d   t#        j$                  dt&               | j                   st#        j$                  dt&               ||fS )a  This method is called before engine creation and used to inject
        driver specific hacks into the options.  The `options` parameter is
        a dictionary of keyword arguments that will then be used to call
        the :func:`sqlalchemy.create_engine` function.

        The default implementation provides some saner defaults for things
        like pool sizes for MySQL and sqlite.  Also it injects the setting of
        `SQLALCHEMY_NATIVE_UNICODE`.

        .. versionchanged:: 2.5
            Returns ``(sa_url, options)``. SQLAlchemy 1.4 made the URL
            immutable, so any changes to it must now be passed back up
            to the original caller.
        mysqlutf8)charsetzmysql+gaerdbmsrh  
   rj  i   sqliteF)N z:memory:Tr   )
StaticPool	poolclassconnect_argscheck_same_threadzLSQLite in memory database with an empty queue not possible due to data loss.)NullPool)databaserb  rK  zThe 'SQLALCHEMY_NATIVE_UNICODE' config option is deprecated and will be removed in v3.0.  Use 'SQLALCHEMY_ENGINE_OPTIONS' instead.zl'use_native_unicode' is deprecated and will be removed in v3.0.  Use the 'engine_options' parameter instead.)
drivernamers   r/   r.   rr   r  sqlalchemy.poolr  RuntimeErrorr  r*   ospathjoin	root_pathr   rK  rm  rn  ro  )	r_   r   r<  r   rh  detected_in_memoryr  r  unus	            r)   r@  zSQLAlchemy.apply_driver_hacks  s    ''0-ffEF  $44"";3"">48(*K0I!&"88%)"6'1$!0.0GN+?D'(;< >& (/ 0 0 4'/$ &$RWW\\#--%Q jj45;))C,1G()::12>MMC"
 &&MM@" wr0   c                 "    | j                         S )aU  Gives access to the engine.  If the database configuration is bound
        to a specific application (initialized with an application) this will
        always return a database connection.  If however the current application
        is used this might raise a :exc:`RuntimeError` if no application is
        active at the moment.
        )r   r^   s    r)   r   zSQLAlchemy.engine  s       r0   c                 :    t        | | j                  |      |      S )z1Creates the connector for a given state and bind.)r*  r   )r_   r   r   s      r)   make_connectorzSQLAlchemy.make_connector  s    dll3&7>>r0   c                    | j                  |      }t        |      }| j                  5  |j                  j	                  |      }|!| j                  ||      }||j                  |<   |j                         cddd       S # 1 sw Y   yxY w)zReturns a specific engine.N)r   r   rO  rG  rr   r  r   )r_   r   r   r   	connectors        r)   r   zSQLAlchemy.get_engine  s     ll3# 	*((,,T2I  //T:	)2  &'')	* 	* 	*s   ABB
c                 .    t        j                  |fi |S )a  
            Override this method to have final say over how the SQLAlchemy engine
            is created.

            In most cases, you will want to use ``'SQLALCHEMY_ENGINE_OPTIONS'``
            config variable or set ``engine_options`` for :func:`SQLAlchemy`.
        )r:   r9  )r_   r<  engine_optss      r)   r9  zSQLAlchemy.create_engine  s     ''>+>>r0   c                     ||S t         rt        j                         S | j                  | j                  S t        d      )zJHelper method that implements the logic to look up an
        application.zNo application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.)r	   _get_current_objectr   r  )r_   reference_apps     r)   r   zSQLAlchemy.get_app  sG     $  22448888O<
 	
r0   c                     g }t        | j                  j                  j                        D ]2  }|j                  j                  d      |k(  s"|j                  |       4 |S )z1Returns a list of all tables relevant for a bind.r4   )r   r   r8   tablesr3   rr   r   )r_   r   resulttables       r)   get_tables_for_bindzSQLAlchemy.get_tables_for_bind  sS    

 3 3 : :; 	%Ezz~~j)T1e$	% r0   c                     | j                  |      }dgt        |j                  j                  d      xs d      z   }i }|D ]H  }| j	                  ||      | j                  |      }|j                  t        fd|D                     J |S )zReturns a dictionary with a table->engine mapping.

        This is suitable for use of sessionmaker(binds=db.get_binds(app)).
        Nr4  r    c              3   &   K   | ]  }|f 
 y wrM   r    ).0r  r   s     r)   	<genexpr>z'SQLAlchemy.get_binds.<locals>.<genexpr>+  s     C5vCs   )r   r   r   rr   r   r  r   r-   )r_   r   r   retvalr   r  r   s         @r)   r   zSQLAlchemy.get_binds   s    
 ll3cjjnn-?@FBGG 	ED__S$/F--d3FMM$CFCCD	E r0   c           	      p   | j                  |      }|dk(  r-d gt        |j                  j                  d      xs d      z   }nt	        |t
              s||g}n|}|D ]V  }i }|s| j                  |      }||d<   t        | j                  j                  |      } |dd| j                  ||      i| X y )NrN   r4  r    r  r   )r   r   r   rr   r6   r   r  rP   r   r8   r   )	r_   r   r   r   skip_tablesr   extrar  ops	            r)   _execute_for_all_tablesz"SQLAlchemy._execute_for_all_tables.  s    ll39FT#**..1C"D"JKKEl+t|FEE 	9DE11$7"(h,,i8B8DOOC.8%8	9r0   c                 *    | j                  ||d       y)z_Creates all tables.

        .. versionchanged:: 0.12
           Parameters were added
        
create_allNr  r_   r   r   s      r)   r  zSQLAlchemy.create_all@  s     	$$S$=r0   c                 *    | j                  ||d       y)z]Drops all tables.

        .. versionchanged:: 0.12
           Parameters were added
        drop_allNr  r  s      r)   r  zSQLAlchemy.drop_allH  s     	$$S$
;r0   c                 .    | j                  ||dd       y)znReflects tables from the database.

        .. versionchanged:: 0.12
           Parameters were added
        reflectT)r  Nr  r  s      r)   r  zSQLAlchemy.reflectP  s     	$$S$	t$Lr0   c                     d| j                   j                  d| j                  st        r| j                  j
                  dS d dS )N<z engine=>)	__class__re   r   r	   r   r%   r^   s    r)   rd   zSQLAlchemy.__repr__X  s?    NN###xx;DKKOO@
 	
<@@
 	
r0   rM   r   r  )rN   N)re   rf   rg   r   rL  r  r   r   rh   r8   rM  rZ  rN  rP  r?  r@  r   r  r   r9  r   r  r   r  r  r  r  rd   r    r0   r)   rI  rI    s    dR ED$I5 $  # #

.N B;#z FP ! !?*?
&9$><M
r0   rI  c                        e Zd Z fdZ xZS )_BoundDeclarativeMetac                 p    t        j                  t        d      d       t        t        |   |||       y )Nz_"_BoundDeclarativeMeta" has been renamed to "DefaultMeta". The old name will be removed in 3.0.r   )
stacklevel)rm  rn  rs  superr  r   )rB   rz   basesrA   r  s       r)   r   z_BoundDeclarativeMeta.__init__`  s7    +0
 	 	#S24Br0   )re   rf   rg   r   __classcell__)r  s   @r)   r  r  _  s    C Cr0   r  c                       e Zd Zy)rs  N)re   rf   rg   r    r0   r)   rs  rs  h  s    r0   rs  always)W
__future__r   rI   r  rn   timerm  mathr   operatorr   	threadingr   r:   flaskr   r   r	   r
   flask.signalsr   r   r   r   sqlalchemy.engine.urlr   sqlalchemy.orm.excr   sqlalchemy.orm.sessionr   r   _compatr   r   r   r`  r   r   r  r   sqlalchemy.ormr   r   ImportErrorsqlalchemy.ext.declarativegreenletr   rX  r   thread__version__platformversion_infoperf_counterr   clock_signalssignalr   r   r*   r/   r>   rC   rK   rV   tuplerX   r|   r~   objectr   r   r   r   rL  r  r  r(  r*  r   rE  rI  r  ro  rs  simplefilterr    r0   r)   <module>r     s   &  	 
       = = # * * * 1 9 5 5   ;/.42  <<7
6!""YYF;??#56 "//*CD )



u 
&0: 0:f@6 @F"6 "J AFd dN[>		 [>|
V 
+6v 6r(v ]
 ]
@CK C	. 	   h 5 6_"  ;;::;  446 4344sH   <F> 	G >GGG8G#"G8#G1.G80G11G87G8