o
    [h                    @   s  d 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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 eg dZedejZedejZdd eddD dgZedejZedejZedejZedejZedejZddddddZi ejd ej d!ej!d"ej"d#ej#d$ej$d%ej%d&ej&d%ej'd'ej(d(ej)d)ej*d*ej+d+ej,d,ej-d-ej.d.ej/d/i ej0d0ej1d1ej2d2ej3d3ej4d4ej5d5ej6d6ej7d7ej8d8ej9d9ej:d:ej;d;ej<d<ej=d=ej>d>ej?d?ej@d@ejAdAejBdBejCdCiZDejEdDejFdEejGdFejHdGejIdHejJdIejKdJejLdKejMdLejNdMejOdNejPdOejQdPejRdQiZSdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`daZTe
jUjVdbe
jUjWdce
jUjXdde
jUjYdee
jUjZdfe
jUj[dgiZ\G dhdi die]Z^G djdk dke_ej`e]ZaG dldm dmejbZcG dndo doedZeG dpdq dqe^ZfG drds dsefZgG dtdu due^ZhG dvdw dweaZiG dxdy dyeiZjG dzd{ d{e]ZkdS )|a]  Base SQL and DDL compiler implementations.

Classes provided include:

:class:`.compiler.SQLCompiler` - renders SQL
strings

:class:`.compiler.DDLCompiler` - renders DDL
(data definition language) strings

:class:`.compiler.GenericTypeCompiler` - renders
type specification strings.

To generate user-defined SQL strings, see
:doc:`/ext/compiler`.

    N   )crud)elements)	functions)	operators)schema)
selectable)sqltypes)visitors   )exc)util)^allZanalyseZanalyzeandanyarrayasascZ
asymmetricauthorizationZbetweenbinaryZbothcasecastcheckcollatecolumn
constraintcreatecrosscurrent_dateZcurrent_rolecurrent_timecurrent_timestampcurrent_userdefault
deferrableZdescZdistinctdoelseendexceptfalseforZforeignfreezefromfullZgrantgroupZhavingZilikein	initiallyinnerZ	intersectZintoisZisnulljoinleadingleftlikelimit	localtimelocaltimestampZnaturalnewnotZnotnullnulloffoffsetoldononlyororderouteroverlapsZplacingprimaryZ
referencesrightselectsession_usersetZsimilarZsome	symmetrictableZthentoZtrailingtrueunionuniqueuserusingverbosewhenwherez^[A-Z0-9_$]+$z^[A-Z0-9_ $]+$c                 C   s   h | ]}t |qS  )str).0xrU   rU   ~/home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/sqlalchemy/sql/compiler.py	<setcomp>       rZ   
   $z5^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$z^(?:DEFERRED|IMMEDIATE)$z%(?<![:\w\$\x5c]):([\w\$]+)(?![:\w\$])z\x5c(:[\w\$]*)(?![:\w\$])z%%(%(name)s)s?z%%sz:[_POSITION]z	:%(name)s)pyformatZqmarkformatnumericnamedz AND z OR z + z * z - z /  % -z < z <= z != z > z >= z = z IS DISTINCT FROM z IS NOT DISTINCT FROM z || z MATCH z NOT MATCH z IN z NOT IN , z FROM  AS z IS z IS NOT z	 COLLATE zEXISTS 	DISTINCT zNOT zANY zALL z DESCz ASCz NULLS FIRSTz NULLS LASTcoalesceZCURRENT_DATEZCURRENT_TIMEZCURRENT_TIMESTAMPZCURRENT_USERZ	LOCALTIMEZLOCALTIMESTAMPrandomsysdateZSESSION_USERUSERZCUBEZROLLUPzGROUPING SETSmonthdayyearsecondhourdoyminutequarterdowweekepochmillisecondsmicrosecondstimezone_hourtimezone_minute)rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   UNIONz	UNION ALLEXCEPTz
EXCEPT ALL	INTERSECTzINTERSECT ALLc                   @   s   e Zd ZdZdZdZe Z	 dde fddZ	e
dddd Zd	d
 Zedd Zdd Zdd ZdddZedd Zdd Zdd ZdS )Compileda  Represent a compiled SQL or DDL expression.

    The ``__str__`` method of the ``Compiled`` object should produce
    the actual text of the statement.  ``Compiled`` objects are
    specific to their underlying database dialect, and also may
    or may not be specific to the columns referenced within a
    particular set of bind parameters.  In no case should the
    ``Compiled`` object be dependent on the actual values of those
    bind parameters, even though it may reference those values as
    defaults.
    Nc                 C   sp   || _ || _| j j| _|| _|r| j|| _|dur6|| _|j| _| jr)|j	| _
| j| jfi || _dS dS )a|  Construct a new :class:`.Compiled` object.

        :param dialect: :class:`.Dialect` to compile against.

        :param statement: :class:`_expression.ClauseElement` to be compiled.

        :param bind: Optional Engine or Connection to compile this
          statement against.

        :param schema_translate_map: dictionary of schema names to be
         translated when forming the resultant SQL

         .. versionadded:: 1.1

         .. seealso::

            :ref:`schema_translating`

        :param compile_kwargs: additional kwargs that will be
         passed to the initial call to :meth:`.Compiled.process`.


        N)dialectbindZidentifier_preparerpreparerschema_translate_map_with_schema_translate	statementZsupports_executioncan_execute_execution_optionsexecution_optionsprocessstring)selfr   r   r   r   compile_kwargsrU   rU   rY   __init__  s    
zCompiled.__init__z0.7zThe :meth:`.Compiled.compile` method is deprecated and will be removed in a future release.   The :class:`.Compiled` object now runs its compilation within the constructor, and this method does nothing.c                 C      dS )z;Produce the internal string representation of this element.NrU   r   rU   rU   rY   compileD  s   	zCompiled.compilec                 C   s    | j r
|| ||S t| jN)r   _execute_compiledr   ZObjectNotExecutableErrorr   )r   
connectionmultiparamsparamsrU   rU   rY   _execute_on_connectionO  s   zCompiled._execute_on_connectionc                 C      t  )zReturn a Compiled that is capable of processing SQL expressions.

        If this compiler is one, it would likely just return 'self'.

        NotImplementedErrorr   rU   rU   rY   sql_compilerU     zCompiled.sql_compilerc                 K      |j | fi |S r   _compiler_dispatch)r   objkwargsrU   rU   rY   r   _     zCompiled.processc                 C   s
   | j pdS )z3Return the string text of the generated SQL or DDL. )r   r   rU   rU   rY   __str__b     
zCompiled.__str__c                 C   r   )zReturn the bind params for this compiled object.

        :param params: a dict of string/object pairs whose values will
                       override bind values compiled in to the
                       statement.
        r   r   r   rU   rU   rY   construct_paramsg  r   zCompiled.construct_paramsc                 C   s   |   S )z0Return the bind params for this compiled object.r   r   rU   rU   rY   r   q  s   zCompiled.paramsc                 O   s*   | j }|du rtjddd|| ||S )zExecute this compiled object.Nz>This Compiled object is not bound to any Engine or Connection.Z2aficode)r   r   ZUnboundExecutionErrorr   )r   r   r   erU   rU   rY   executev  s   zCompiled.executec                 O   s   | j |i | S )zJExecute this compiled object and return the result's
        scalar value.)r   scalar)r   r   r   rU   rU   rY   r     s   zCompiled.scalarr   )__name__
__module____qualname____doc__Z_cached_metadatar   r   immutabledictr   r   
deprecatedr   r   propertyr   r   r   r   r   r   r   rU   rU   rU   rY   r~      s2    	
0

	


r~   c                   @   s$   e Zd ZdZdZdd Zdd ZdS )TypeCompilerz2Produces DDL specification for TypeEngine objects.z	visit_\w+c                 C   s
   || _ d S r   )r   )r   r   rU   rU   rY   r        
zTypeCompiler.__init__c                 K   r   r   r   r   type_kwrU   rU   rY   r     r   zTypeCompiler.processN)r   r   r   r   Zensure_kwargr   r   rU   rU   rU   rY   r     s
    r   c                   @   sB   e Zd ZdZdZdZdddZedd Zed	d
 Z	dd Z
dS )_CompileLabelz;lightweight label object which acts as an expression.Label.label)elementnamerU   c                 C   s   || _ || _|f| | _d S r   )r   r   
_alt_names)r   colr   	alt_namesrU   rU   rY   r     s   z_CompileLabel.__init__c                 C      | j jS r   )r   	proxy_setr   rU   rU   rY   r        z_CompileLabel.proxy_setc                 C   r   r   )r   typer   rU   rU   rY   r     r   z_CompileLabel.typec                 K      | S r   rU   )r   r   rU   rU   rY   
self_group     z_CompileLabel.self_groupN)rU   )r   r   r   r   __visit_name__	__slots__r   r   r   r   r   rU   rU   rU   rY   r     s    


r   c                   @   s   e Zd ZdZdd ZdS )prefix_anon_mapac  A map that creates new keys for missing key access.
    Considers keys of the form "<ident> <name>" to produce
    new symbols "<name>_<index>", where "index" is an incrementing integer
    corresponding to <name>.
    Inlines the approach taken by :class:`sqlalchemy.util.PopulateDict` which
    is otherwise usually used for this type of operation.
    c                 C   sD   | dd\}}| |d}|d | |< |d t| }|| |< |S )N r   _)splitgetrV   )r   keyidentZderivedZanonymous_countervaluerU   rU   rY   __missing__  s   zprefix_anon_map.__missing__N)r   r   r   r   r   rU   rU   rU   rY   r     s    r   c                   @   s\  e Zd ZdZeZeZd Z Z	Z
	 dZdZ	 dZ	 dZ	 dZ	 dZ	 dZ	 dZ	 dZ	 dZ	 d ZZ	dddZedd	 Zed
d Zejdd Zejdd Z dd Z!ej"dd Z#dd Z$edd Z%dddZ&edd Z'e(ddd Z)dd  Z*dd!d"Z+	dd#d$Z,	dd%d&Z-				dd'd(Z.d)d* Z/	dd+d,Z0d-d. Z1d/d0 Z2d1d2 Z3d3d4 Z4d5d6 Z5d7d8 Z6d9d: Z7	d	d;d<Z8d=d> Z9d?d@ Z:dAdB Z;dCdD Z<dEdF Z=dGdH Z>dIdJ Z?dKdL Z@dMdN ZAdOdP ZBdQdR ZCdSdT ZDd
dUdVZEdWdX ZFdYdZ ZGd[d\ ZH	]dd^d_ZId`da ZJdbdc ZKddde ZLdfdg ZMdhdi ZNdjdk ZOdldm ZPdndo ZQdpdq ZR	ddrdsZSdtdu ZTdvdw ZUdxdy ZVdzd{ ZWd|d} ZX	dd~dZYdd ZZdd Z[ej"dd Z\dd Z]dd Z^dd Z_dd Z`dd Zadd Zbdd Zcdd Zddd Zedd Zfdd Zgdd Zh			dddZidd Zjdd Zkdd Zldd Zmdd Zn	dddZo				dddZp				dddZqdd ZrdddZsdd Ztdd Zu			dddZvdd Zwdd Zxdd Zydd ZzddÄ Z{ddń Z|ddǄ Z}e~de fde fgZddd˄Z				]			ddd̈́Zddτ Zddф Zddӄ ZddՄ Zddׄ Zddل Zddۄ Zdd݄ Zdd߄ Zdd Zdd Zdd Z					dddZdddZdd ZdddZdd Zdd Zdd ZdddZej"dd Zdd Zdd ZdddZdd Zd d Zdd ZdS (  SQLCompilerz~Default implementation of :class:`.Compiled`.

    Compiles :class:`_expression.ClauseElement` objects into SQL strings.

    FNTrU   c                 K   s   || _ |p
t|dd| _i | _t | _g | _g | _|j	| _	| j	r*g | _
|jdk| _t|j | _d| _|jp8|j| _t | _i | _tj| ||fi | | jsU| jsU| jr\|jr\|j| _| j	rh| jrj|   dS dS dS )a  Construct a new :class:`.SQLCompiler` object.

        :param dialect: :class:`.Dialect` to be used

        :param statement: :class:`_expression.ClauseElement` to be compiled

        :param column_keys:  a list of column names to be compiled into an
         INSERT or UPDATE statement.

        :param inline: whether to generate INSERT statements as "inline", e.g.
         not formatted to return any generated defaults

        :param kwargs: additional keyword arguments to be consumed by the
         superclass.

        inlineFra   N)column_keysgetattrr   bindsr   Zcolumn_dict
bind_namesstack_result_columns
positionalpositiontup
paramstyle_numeric_bindsBIND_TEMPLATESbindtemplatecteslabel_lengthmax_identifier_lengthr   anon_maptruncated_namesr~   r   isinsertisupdateisdelete
_returning	returning_apply_numbered_params)r   r   r   r   r   r   rU   rU   rY   r     s:   

zSQLCompiler.__init__c              
   C   sJ   z| j d d W S  ty$ } ztjtd|d W Y d}~dS d}~ww )a  Return the current 'executable' that is being compiled.

        This is currently the :class:`_sql.Select`, :class:`_sql.Insert`,
        :class:`_sql.Update`, :class:`_sql.Delete`,
        :class:`_sql.CompoundSelect` object that is being compiled.
        Specifically it's assigned to the ``self.stack`` list of elements.

        When a statement like the above is being compiled, it normally
        is also assigned to the ``.statement`` attribute of the
        :class:`_sql.Compiler` object.   However, all SQL constructs are
        ultimately nestable, and this attribute should never be consulted
        by a ``visit_`` method, as it is not guaranteed to be assigned
        nor guaranteed to correspond to the current statement being compiled.

        .. versionadded:: 1.3.21

            For compatibility with previous versions, use the following
            recipe::

                statement = getattr(self, "current_executable", False)
                if statement is False:
                    statement = self.stack[-1]["selectable"]

            For versions 1.4 and above, ensure only .current_executable
            is used; the format of "self.stack" may change.


        r   z$Compiler does not have a stack entryZreplace_contextN)r   
IndexErrorr   raise_)r   ZierU   rU   rY   current_executableZ  s   zSQLCompiler.current_executablec                 C   s   t | j| j S r   )listinsert_prefetchupdate_prefetchr   rU   rU   rY   prefetch     zSQLCompiler.prefetchc                 C   s*   t  | _i | _d| _| jri | _dS dS )zInitialize collections related to CTEs only if
        a CTE is located, to save on the overhead of
        these collections otherwise.

        FN)r   OrderedDictr   ctes_by_namectes_recursiver   cte_positionalr   rU   rU   rY   _init_cte_state  s   

zSQLCompiler._init_cte_statec              	   c   s    | j | j}}g d| _ | _z'| jr| jd }d|d< nd}| j | jfV  W |r.|d ||| _ | _dS |r>|d ||| _ | _w )z;special API to support the use case of 'nested result sets'Fr   Tneed_result_map_for_nestedN)r   _ordered_columnsr   pop)r   Zresult_columnsZordered_columnsentryrU   rU   rY   _nested_result  s*   



zSQLCompiler._nested_resultc                    s(   t d td fdd| j| _d S )Nr   z\[_POSITION\]c                    s   t t S r   )rV   r   nextmZposcountrU   rY   <lambda>  s    z4SQLCompiler._apply_numbered_params.<locals>.<lambda>)	itertoolscountresubr   r   rU   r  rY   r     s   

z"SQLCompiler._apply_numbered_paramsc                    s"   t dd  fdd jD D S )Nc                 s   s$    | ]\}}|d ur||fV  qd S r   rU   )rW   r   r   rU   rU   rY   	<genexpr>  s    z/SQLCompiler._bind_processors.<locals>.<genexpr>c                 3   s(    | ]} j | |j jfV  qd S r   )r   r   Z_cached_bind_processorr   )rW   	bindparamr   rU   rY   r    s    
)dictr   r   rU   r   rY   _bind_processors  s
   
zSQLCompiler._bind_processorsc                 C   s   t | jdkS Nr   )lenr   r   rU   rU   rY   is_subquery     zSQLCompiler.is_subqueryc                 C   r   r   rU   r   rU   rU   rY   r        zSQLCompiler.sql_compilerc                 C   s  |rTi }| j D ]J}| j | }|j|v r||j ||< q||v r&|| ||< q|rC|jrC|r9tjd|j|f ddtjd|j dd|jrL|j||< q|j||< q|S i }| j D ]3}|rx|jrx|rntjd|j|f ddtjd|j dd|jr|j|| j | < qY|j|| j | < qY|S )z5return a dictionary of bind parameter keys and valuesz@A value is required for bind parameter %r, in parameter group %dZcd3xr   z)A value is required for bind parameter %r)r   r   requiredr   ZInvalidRequestErrorcallableeffective_valuer   )r   r   Z_group_number_checkpdr  r   rU   rU   rY   r     s\   





zSQLCompiler.construct_paramsc                 C   s   | j ddS )zoReturn the bind param dictionary embedded into this
        compiled object, for those values that are present.F)r  r   r   rU   rU   rY   r     s   zSQLCompiler.paramszsqlalchemy.engine.resultc                 C   s   |j | jS )z(utility method used for unit tests only.)ZResultMetaData_create_result_mapr   )r   resultrU   rU   rY   r    s   zSQLCompiler._create_result_mapc                 C   r   )zCalled when a SELECT statement has no froms, and no FROM clause is
        to be appended.

        Gives Oracle a chance to tack on a ``FROM DUAL`` to the string output.

        r   rU   r   rU   rU   rY   default_from  s   zSQLCompiler.default_fromc                 K   s   d|j j| fi | d S )N()r   r   )r   groupingasfromr   rU   rU   rY   visit_grouping  s   zSQLCompiler.visit_groupingc           
      K   s   | j r6| jjr6| j d d }|j\}}}|r|}n|}|jj}	|	d ur6|	j|v r6|	||	j r6|jj|d< | j|jfd|i|S )Nr   r   render_label_as_labelwithin_columns_clause)	r   r   Zsupports_simple_order_by_label_label_resolve_dictr   Z_order_by_label_elementr   Zshares_lineager   )
r   r   r  r   r   	with_cols
only_froms	only_colsZresolve_dictZorder_by_elemrU   rU   rY   visit_label_reference  s0   
z!SQLCompiler.visit_label_referencec           
   
   K   s   | j s	| |jS | j d d }|j\}}}z|r||j }n||j }W n tyC }	 ztj|jtj	d|	d W Y d }	~	d S d }	~	ww ||d< | j|fd|i|S )Nr   r   zECan't resolve label reference for ORDER BY / GROUP BY / DISTINCT etc.)errr  r  )
r   r   Z_text_clauser   r   KeyErrorr   Z_no_text_coercionr   CompileError)
r   r   r  r   r   r!  r"  r#  r   ZkerU   rU   rY   visit_textual_label_reference6  s4   
	z)SQLCompiler.visit_textual_label_referencec           
      K   s   |o| }||u }|s|rt |jtjr| d|j}	n|j}	|rL|d ur3||	|j||	f|j |j |jj| fddd|t	t
j  | j||	 S |rU| j||	S |jj| fddi|S )NcolidentT)r  within_label_clauser  F)
isinstancer   r   _truncated_label_truncated_identifierr   r   r   r   	OPERATORSr   as_r   format_label)
r   r   add_to_result_mapr*  r  r  r   Zrender_label_with_asZrender_label_onlyZ	labelnamerU   rU   rY   visit_labelR  sJ   
zSQLCompiler.visit_labelc                 C   
   t d)Nz:Cannot compile Column object until its 'name' is assigned.r   r'  r   r   rU   rU   rY   _fallback_column_name     z!SQLCompiler._fallback_column_namec                 K   s   |j  }}|d u r| |}|j}|st|tjr| d|}|d ur/||||||jf|j |r7| 	|}n| j
|}|j}|d u sI|rI|jsK|S | j
|}	|	r\| j
|	d }
nd}
|j }t|tjrm| d|}|
| j
| d | S )Nr)  .r   alias)r   r6  
is_literalr+  r   r,  r-  r   r   escape_literal_columnr   quoterK   Znamed_with_columnschema_for_objectquote_schema)r   r   r1  include_tabler   r   Z	orig_namer:  rK   effective_schemaZschema_prefixZ	tablenamerU   rU   rY   visit_column  s2   

zSQLCompiler.visit_columnc                 K   s   | j |jS r   )r   format_collation	collation)r   r   r   rU   rU   rY   visit_collation  r  zSQLCompiler.visit_collationc                 K      |j S r   r   )r   Z
fromclauser   rU   rU   rY   visit_fromclause     zSQLCompiler.visit_fromclausec                 K   rE  r   rF  )r   indexr   rU   rU   rY   visit_index  rH  zSQLCompiler.visit_indexc                 K   s    ||d< | j jj|jfi |S )Ntype_expression)r   type_compilerr   r   )r   
typeclauser   rU   rU   rY   visit_typeclause  s   zSQLCompiler.visit_typeclausec                 C      | j jr
|dd}|S N%%%r   _double_percentsreplacer   textrU   rU   rY   post_process_text     zSQLCompiler.post_process_textc                 C   rO  rP  rS  rV  rU   rU   rY   r;    rY  z!SQLCompiler.escape_literal_columnc              	      s<    fdd}j sd_tdd t|jS )Nc                    s>   |  d}|jv rjj| fi  S j|fi  S r  )r-   Z_bindparamsr   bindparam_string)r   r   r   r   
textclauserU   rY   do_bindparam  s   

z2SQLCompiler.visit_textclause.<locals>.do_bindparamTc                 S   s
   |  dS r  )r-   r   rU   rU   rY   r    s   
 z.SQLCompiler.visit_textclause.<locals>.<lambda>)r   isplaintextBIND_PARAMS_ESCr  BIND_PARAMSrX  rW  )r   r\  r   r]  rU   r[  rY   visit_textclause  s   zSQLCompiler.visit_textclausec                 K   s   | j  }|r	| jn| j d }|p|dko|ddp|dd}|r8|j | _| _|jD ]}	| j|	d| jd q,| j|j	fi |}
|rJ|rJd|
 }
|
S )	Nr   r   need_result_map_for_compoundFr   Tr  r1  (%s))
r   _default_stack_entryr   r   r   _textual_ordered_columnsZcolumn_argsr   _add_to_result_mapr   )r   Ztafcompound_indexr  parensr   toplevelr   populate_result_mapcrW  rU   rU   rY   visit_text_as_from  s,   

	
zSQLCompiler.visit_text_as_fromc                 K   r   )NZNULLrU   r   exprr   rU   rU   rY   
visit_null  r   zSQLCompiler.visit_nullc                 K      | j jrdS dS )NrM   1r   supports_native_booleanrn  rU   rU   rY   
visit_true     zSQLCompiler.visit_truec                 K   rq  )Nr(   0rs  rn  rU   rU   rY   visit_false  rv  zSQLCompiler.visit_falsec                    s^   |j }|d u r
d}nt|j  }|dd  fdd|jD D }|jr-jjr-d| }|S )Nr   c                 s   s    | ]}|r|V  qd S r   rU   rW   srU   rU   rY   r    s    
z/SQLCompiler.visit_clauselist.<locals>.<genexpr>c                 3   s"    | ]}|j fi  V  qd S r   r   rW   rl  r   r   rU   rY   r    s    
zVALUES )operatorr.  r2   clausesZ_tuple_valuesr   Ztuple_in_values)r   Z
clauselistr   seprW  rU   r|  rY   visit_clauselist	  s   

zSQLCompiler.visit_clauselistc                 K   s   d}|j d ur||j j| fi |d 7 }|jD ]\}}|d|j| fi | d |j| fi | d 7 }q|jd urL|d|jj| fi | d 7 }|d7 }|S )NzCASE r   zWHEN z THEN zELSE END)r   r   ZwhensZelse_)r   clauser   rX   Zcondr  rU   rU   rY   
visit_case  s*   

zSQLCompiler.visit_casec                 K      |j j| fi |S r   )Ztyped_expressionr   )r   Ztype_coercer   rU   rU   rY   visit_type_coerce.     zSQLCompiler.visit_type_coercec                 K   ,   d|j j| fi ||jj| fi |f S )NzCAST(%s AS %s))r  r   rM  )r   r   r   rU   rU   rY   
visit_cast1     zSQLCompiler.visit_castc              	   K   s   d|d t ju r
dn2|d t ju rdn)|d dk r,d| jt t|d fi |f nd| jt |d fi |f |d t ju rGdf S |d t ju rRdf S |d dk rmd| jt t|d fi |f f S d| jt |d fi |f f S )	Nz	%s AND %sr   zUNBOUNDED PRECEDINGzCURRENT ROWz%s PRECEDINGz%s FOLLOWINGr   zUNBOUNDED FOLLOWING)r   ZRANGE_UNBOUNDEDZRANGE_CURRENTr   literalabs)r   range_r   rU   rU   rY   _format_frame_clause7  s6     z SQLCompiler._format_frame_clausec                    s   |j rdj|j fi   }n|jr dj|jfi   }nd }d|jjfi  d fddd|jfd|jffD |rD|gng  f S )	NzRANGE BETWEEN %szROWS BETWEEN %sz%s OVER (%s)r   c                    s:   g | ]\}}|d urt |rd||jfi  f qS )Nz%s BY %s)r  r   )rW   wordr  r   r   rU   rY   
<listcomp>]  s    z*SQLCompiler.visit_over.<locals>.<listcomp>Z	PARTITIONZORDER)r  r  rowsr   r   r2   Zpartition_byorder_by)r   Zoverr   r  rU   r  rY   
visit_overN  s2   

	zSQLCompiler.visit_overc                 K   r  )Nz%s WITHIN GROUP (ORDER BY %s))r   r   r  )r   Zwithingroupr   rU   rU   rY   visit_withingroupj  r  zSQLCompiler.visit_withingroupc                 K   r  )Nz%s FILTER (WHERE %s))funcr   	criterion)r   Z
funcfilterr   rU   rU   rY   visit_funcfilterp  r  zSQLCompiler.visit_funcfilterc                 K   s.   | j |j|j}d||jj| fi |f S )NzEXTRACT(%s FROM %s))extract_mapr   fieldro  r   )r   extractr   r  rU   rU   rY   visit_extractv  s
   zSQLCompiler.visit_extractc                    s   |d ur||j |j d|j td|j   d }|r#||fi |S t|jd   r4|jr3 d7  n|j  j	 sCt
 tjrIj n   d  d fdd|jD  g dj|fi |i S )NrU   zvisit_%s_funcz%(expr)sr8  c                    s4   g | ]}j |st tjrj |n|qS rU   )r   _requires_quotes_illegal_charsr+  r   quoted_namer<  )rW   tokr   r   rU   rY   r    s    

z.SQLCompiler.visit_function.<locals>.<listcomp>ro  )r   r   r   lower	FUNCTIONSr   	__class__Z	_has_argsr   r  r+  r   r  r<  r2   Zpackagenamesfunction_argspec)r   r  r1  r   disprU   r  rY   visit_function}  s6   

	zSQLCompiler.visit_functionc                 K   s   |  |jS r   )visit_sequencesequence)r   Z
next_valuer   rU   rU   rY   visit_next_value_func     z!SQLCompiler.visit_next_value_funcc                 K      t d| jj )Nz2Dialect '%s' does not support sequence increments.r   r   r   )r   r  r   rU   rU   rY   r    
   zSQLCompiler.visit_sequencec                 K   r  r   )Zclause_exprr   )r   r  r   rU   rU   rY   r    r  zSQLCompiler.function_argspecr   c                    s,  j  }|r	jnj d }|p|dko|dd}j |d |d ||d j|j}	d|	 d  fd	d
t|jD }
|
j	|fi t
dd i7 }
|
j|fi 7 }
|
|jd usm|jd urvj|fi pwd7 }
jr|r |
 }
j d  r|rd|
 d S |
S )Nr   r   rb  Fcorrelate_fromsasfrom_froms)r  r  r   rb  r   c                 3   s.    | ]\}}|j f d |dV  qdS )F)r  ri  rh  Nr   )rW   irl  r  r   r   rU   rY   r    s    
z4SQLCompiler.visit_compound_select.<locals>.<genexpr>r  r   r  r  rU   )r   re  r   appendcompound_keywordskeywordr2   	enumerateselectsgroup_by_clauser	  order_by_clause_limit_clause_offset_clauselimit_clauser   _render_cte_clauser   )r   csr  ri  rh  r   rj  r   Zneed_result_mapr  rW  rU   r  rY   visit_compound_select  sB   
	$
z!SQLCompiler.visit_compound_selectc                 C   s(   d|j ||r
d| ndf }t| |d S )Nzvisit_%s_%s%sr   r   )r   r   )r   	operator_Z
qualifier1Z
qualifier2attrnamerU   rU   rY   _get_operator_dispatch  s   z"SQLCompiler._get_operator_dispatchc                 K   s   |j r,|jrtd| |j dd}|r|||j fi |S | j|t|j  fi |S |jrP| |jdd}|rC|||jfi |S | j|t|j fi |S td)NzFUnary expression does not support operator and modifier simultaneouslyunaryr}  modifierz,Unary expression has no operator or modifier)r}  r  r   r'  r   _generate_generic_unary_operatorr.   _generate_generic_unary_modifier)r   r  r   r  rU   rU   rY   visit_unary  s:   

zSQLCompiler.visit_unaryc                 K   s:   |j s| jjr| j|jfi |S d| j|jfi | S )Nz%s = 1Z_is_implicitly_booleanr   rt  r   r   r   r   r}  r   rU   rU   rY   visit_istrue_unary_operator  s   z'SQLCompiler.visit_istrue_unary_operatorc                 K   s>   |j s| jjrd| j|jfi | S d| j|jfi | S )NNOT %sz%s = 0r  r  rU   rU   rY   visit_isfalse_unary_operator  s   z(SQLCompiler.visit_isfalse_unary_operatorc                 K   s   d| j |tjd S )Nr  )override_operator)visit_binaryr   match_opr   r   r}  r   rU   rU   rY   visit_notmatch_op_binary  s   z$SQLCompiler.visit_notmatch_op_binaryc                 C   s   t d d S )NzThe IN-predicate was invoked with an empty sequence. This results in a contradiction, which nonetheless can be expensive to evaluate.  Consider alternative strategies for improved performance.)r   warnr   rU   rU   rY   _emit_empty_in_warning  s   z"SQLCompiler._emit_empty_in_warningc                 K   s.   | j jrdS | j jr|   | |j|jkS )Nz1 != 1r   Z_use_static_inZ_warn_on_empty_inr  r   r4   r  rU   rU   rY   visit_empty_in_op_binary%  
   z$SQLCompiler.visit_empty_in_op_binaryc                 K   s.   | j jrdS | j jr|   | |j|jkS )Nz1 = 1r  r  rU   rU   rY   visit_empty_notin_op_binary-  r  z'SQLCompiler.visit_empty_notin_op_binaryc                 C   r  )Nz3Dialect '%s' does not support empty set expression.r  )r   Zelement_typesrU   rU   rY   visit_empty_set_expr5  r  z SQLCompiler.visit_empty_set_exprc           	   
   K   s   | j rt|jtjrt|jtjrd|d< |p|j}| |dd }|r,|||fi |S zt| }W n t	yP } zt
jt| ||d W Y d }~d S d }~ww | j||fi |S )NTliteral_bindsr   r   )ansi_bind_rulesr+  r4   r   ZBindParameterrF   r}  r  r.  r&  r   r   r   ZUnsupportedCompilationError_generate_generic_binary)	r   r   r  eager_groupingr   r  r  opstringr%  rU   rU   rY   r  ;  s*   

zSQLCompiler.visit_binaryc                 K   s   | j |jfi |S r   )r   Zsql_functionr  rU   rU   rY   &visit_function_as_comparison_op_binaryV  r  z2SQLCompiler.visit_function_as_comparison_op_binaryc                 K   s`   | j jr| j|jfi |d | j|jfi | S | j|jfi |d | j|jfi | S )Nz %% rc   )r   rT  r   r4   rF   r  rU   rU   rY   visit_mod_binaryY  s   zSQLCompiler.visit_mod_binaryc                 K   s(   |j |d< | j|d|j d fi |S )Nr  r   )r  r  r  r  rU   rU   rY   visit_custom_op_binaryg  s   
z"SQLCompiler.visit_custom_op_binaryc                 K   s   | j ||jd fi |S Nr   )r  r  r  rU   rU   rY   visit_custom_op_unary_operatorm  
   
z*SQLCompiler.visit_custom_op_unary_operatorc                 K   s   | j |d|j fi |S r  )r  r  r  rU   rU   rY   visit_custom_op_unary_modifierr  r  z*SQLCompiler.visit_custom_op_unary_modifierc                 K   s\   | dd}d|d< |jj| fd|i|| |jj| fd|i| }|r,|r,d| }|S )N
_in_binaryFTr  rd  )r   r4   r   rF   )r   r   r  r  r   r  rW  rU   rU   rY   r  w  s.   
z$SQLCompiler._generate_generic_binaryc                 K   s   ||j j| fi | S r   r  r   r  r  r   rU   rU   rY   r       z,SQLCompiler._generate_generic_unary_operatorc                 K   s   |j j| fi || S r   r  r  rU   rU   rY   r    r  z,SQLCompiler._generate_generic_unary_modifierc                 C   s   t jdtjdS )Nz'%')r   )r   Zliteral_columnr	   
STRINGTYPEr   rU   rU   rY   _like_percent_literal  r   z!SQLCompiler._like_percent_literalc                 K   6   |  }| j}||j||_| j||fi |S r   _cloner  __add__rF   visit_like_op_binaryr   r   r}  r   percentrU   rU   rY   visit_contains_op_binary     z$SQLCompiler.visit_contains_op_binaryc                 K   r  r   r  r  r  rF   visit_notlike_op_binaryr  rU   rU   rY   visit_notcontains_op_binary  r  z'SQLCompiler.visit_notcontains_op_binaryc                 K   0   |  }| j}||j|_| j||fi |S r   )r  r  __radd__rF   r  r  rU   rU   rY   visit_startswith_op_binary     z&SQLCompiler.visit_startswith_op_binaryc                 K   r  r   )r  r  r  rF   r  r  rU   rU   rY   visit_notstartswith_op_binary  r  z)SQLCompiler.visit_notstartswith_op_binaryc                 K   r  r   r  r  rU   rU   rY   visit_endswith_op_binary  r  z$SQLCompiler.visit_endswith_op_binaryc                 K   r  r   r  r  rU   rU   rY   visit_notendswith_op_binary  r  z'SQLCompiler.visit_notendswith_op_binaryc                 K   V   |j dd }d|jj| fi ||jj| fi |f |r(d| |tj  S d S )Nescapez
%s LIKE %s ESCAPE r   	modifiersr   r4   r   rF   render_literal_valuer	   r  r   r   r}  r   r  rU   rU   rY   r    s   z SQLCompiler.visit_like_op_binaryc                 K   r  )Nr  z%s NOT LIKE %sr  r   r  r  rU   rU   rY   r       z#SQLCompiler.visit_notlike_op_binaryc                 K   r  )Nr  zlower(%s) LIKE lower(%s)r  r   r  r  rU   rU   rY   visit_ilike_op_binary  r  z!SQLCompiler.visit_ilike_op_binaryc                 K   r  )Nr  zlower(%s) NOT LIKE lower(%s)r  r   r  r  rU   rU   rY   visit_notilike_op_binary  r  z$SQLCompiler.visit_notilike_op_binaryc                 K   *   |j dd}| j||rdndfi |S )NrJ   Fz BETWEEN SYMMETRIC z	 BETWEEN r  r   r  r   r   r}  r   rJ   rU   rU   rY   visit_between_op_binary  s   z#SQLCompiler.visit_between_op_binaryc                 K   r  )NrJ   Fz NOT BETWEEN SYMMETRIC z NOT BETWEEN r  r  rU   rU   rY   visit_notbetween_op_binary  s   
z&SQLCompiler.visit_notbetween_op_binaryc           
      K   s$  |s|j | j}|jr||}| j|fd||d|S |s%|rB| jrB|jd u r7|jd u r7t	
d|j | j|fddi|S | |}|| jv r{| j| }	|	|ur{|	js[|jrj|	j|jsjt	
d|j |	jsp|jr{t	
d|j|jf | | j|j< | j|< | j|fd|ji|S )NT)skip_bind_expressionr  r  z@Bind parameter '%s' without a renderable value not allowed here.r  zIBind parameter '%s' conflicts with unique bind parameter of the same namezbindparam() name '%s' is reserved for automatic usage in the VALUES or SET clause of this insert/update statement.   Please use a name other than column name when using bindparam() with insert() or update() (for example, 'b_%s').	expanding)r   dialect_implr   Z_has_bind_expressionbind_expressionr   r  r   r  r   r'  r   render_literal_bindparam_truncate_bindparamr   rO   r   intersectionZ_is_crudrZ  r  )
r   r  r  r  r
  r   implr  r   existingrU   rU   rY   visit_bindparam  sp   	





zSQLCompiler.visit_bindparamc                 K   s   |j }| ||jS r   )r  r   r   )r   r  r   r   rU   rU   rY   r  3  s   z$SQLCompiler.render_literal_bindparamc                 C   s$   | | j}|r||S td| )a  Render the value of a bind parameter as a quoted literal.

        This is used for statement sections that do not accept bind parameters
        on the target driver/database.

        This should be implemented by subclasses using the quoting services
        of the DBAPI.

        z(Don't know how to literal-quote value %r)Z_cached_literal_processorr   r   )r   r   r   	processorrU   rU   rY   r   7  s   z SQLCompiler.render_literal_valuec                 C   s@   || j v r
| j | S |j}t|tjr| d|}|| j |< |S )Nr  )r   r   r+  r   r,  r-  )r   r  Z	bind_namerU   rU   rY   r  J  s   


zSQLCompiler._truncate_bindparamc                 C   s   ||f| j v r| j ||f S || j}t|| jd krB| j |d}|dt| jd d d t|dd   }|d | j |< n|}|| j ||f< |S )N   r   r   r   r   )r   Z	apply_mapr   r  r   r   maxhex)r   Zident_classr   ZanonnameZcounterZ	truncnamerU   rU   rY   r-  W  s   z!SQLCompiler._truncated_identifierc                 C   s
   || j  S r   )r   r   r   rU   rU   rY   
_anonymizej  r   zSQLCompiler._anonymizec                 K   sF   | j r|d ur|| n| j| |rd| _d| S | jd|i S )NTz([EXPANDING_%s])r   )r   r  r   contains_expanding_parametersr   )r   r   positional_namesr  r   rU   rU   rY   rZ  m  s   zSQLCompiler.bindparam_stringc                    s      ||d< t|jtjr d|j}n|j}d}d}	| jv rI j| }
||
u }	||
jv s5||
u r8d}n|
|jv rB j|
= nt	
d| |sM|rj|jd urf|j}|jj}t|tjre d|}n|}d }|r&| j|< d|jjv rd jvr jd|jjd i _| jvr j|fi | |s&| jvr&|jrd _ j||}|jrt|jtjr|j}nt|jtjr|jjd }nJ dd	 t|jD }|d
d fdd|D  7 } jrg  |d<  j|< |d j ||j!fi ||jj" fddi|f 7 }|j#r!|d j ||j#fi | 7 }| j|< |r]|s6|	r6 j||S |rV j||} j$|rM j%|}| &|7 }|S  j||S d S )Nvisiting_cter9  TFz5Multiple, unrelated CTEs found with the same name: %rZ
autocommitr   c                 S      g | ]}|d ur|qS r   rU   r{  rU   rU   rY   r    s
    z)SQLCompiler.visit_cte.<locals>.<listcomp>rd  re   c                 3   s    | ]	} j |V  qd S r   )r   format_column)rW   r   r   rU   rY   r    s
    

z(SQLCompiler.visit_cte.<locals>.<genexpr>r  z	 AS %s
%sr  r   )'r   r+  r   r   r,  r-  r   Z	_restatesr   r   r'  Z
_cte_aliasr   r   r   rN   	visit_cte	recursiver   r   format_aliasoriginalr   SelectCompoundSelectr  r   Zunique_listinner_columnsr2   r   r   _generate_prefixes	_prefixesr   	_suffixes_requires_quotesr<  get_render_as_alias_suffix)r   cter  ashint	fromhintsr  r   Zcte_nameZ
is_new_cteZembedded_in_current_named_cteZexisting_cteZpre_alias_cteZcte_pre_alias_namerW  Z
col_sourceZ
recur_colsrU   r   rY   r  {  s   	










zSQLCompiler.visit_ctec           	      K   s   |s|rt |jtjr| d|j}n|j}|r| j||S |rI|jj| fddi|| 	| j|| }|rG||v rG| 
|||| |}|S |jj| fi |S )Nr9  r  T)r+  r   r   r,  r-  r   r!  r"  r   r*  format_from_hint_text)	r   r9  r  r,  iscrudr-  r   Z
alias_nameretrU   rU   rY   visit_alias  s0   	zSQLCompiler.visit_aliasc                 K   s   d|d< d| j |fi | S )NTlateralz
LATERAL %s)r1  )r   r2  r   rU   rU   rY   visit_lateral  s   zSQLCompiler.visit_lateralc                 K   sZ   d| j |fddi|| j| fi |f }|jd ur+|d|jj| fi | 7 }|S )Nz%s TABLESAMPLE %sr  Tz REPEATABLE (%s))r1  Z_get_methodr   seed)r   Ztablesampler  r   rW  rU   rU   rY   visit_tablesample  s   
zSQLCompiler.visit_tablesamplec                 C   s   d| S )Nrf   rU   )r   Zalias_name_textrU   rU   rY   r*  )     z&SQLCompiler.get_render_as_alias_suffixc                 C   s   | j ||||f d S r   )r   r  )r   keynamer   objectsr   rU   rU   rY   rg  ,  r  zSQLCompiler._add_to_result_mapc	                    s   j j}	|	jr |s|r |	 }
|r fdd}nd}n
 }
|r(j}nd}|s/|
}nt tjrG|
 urDt	|
 j
 jfd}nm|
}nj|durW|rWt	|
| jfd}nZ|r|t tjr| js| jdur|t jtjs|t	|
t j
 jfd}n5t tjst tjr jrt drt tjrt	|
 j}n|
 urt	|
t j
 jfd}n|
}|j||d |jfi |S )z.produce labeled columns present in a select().c                    s    | | f| | d S r   )rg  )r7  r   r8  r   r   r   rU   rY   r1  E  s   z;SQLCompiler._label_select_column.<locals>.add_to_result_mapN)r   r   rc  )r   r  r   Z_has_column_expressionZcolumn_expressionrg  r+  r   Labelr   r   r   
_key_labelZColumnClauser:  rK   r   r#  Z_as_truncatedr   Z
TextClauseZUnaryExpressionZwraps_column_expressionhasattrr   FunctionZ
anon_labelupdater   )r   rG   r   rk  r  column_clause_argsr   r  need_column_expressionsr  Zcol_exprr1  Zresult_exprrU   r9  rY   _label_select_column/  s~   








z SQLCompiler._label_select_columnc                 C   s    |  ||}|r|d| 7 }|S r  )get_from_hint_text)r   sqltextrK   hintr/  hinttextrU   rU   rY   r.    s   z!SQLCompiler.format_from_hint_textc                 C      d S r   rU   )r   ZbyfromsrU   rU   rY   get_select_hint_text  r   z SQLCompiler.get_select_hint_textc                 C   rF  r   rU   r   rK   rW  rU   rU   rY   rB    r   zSQLCompiler.get_from_hint_textc                 C   rF  r   rU   rH  rU   rU   rY   get_crud_hint_text  r   zSQLCompiler.get_crud_hint_textc                 C   s
   d |S r  r2   )r   Z
hint_textsrU   rU   rY   get_statement_hint_text  r   z#SQLCompiler.get_statement_hint_textc                    s"   i  i g fdd|S )zRewrite any "a JOIN (b JOIN c)" expression as
        "a JOIN (select * from b JOIN c) AS anon", to support
        databases that can't parse a parenthesized join correctly
        (i.e. sqlite < 3.7.16).

        c           
         s  | d v rd |  S |  v r |  S |    } | < |jr|jrt|jtjr|  |jfi ||_|jfi |}tj	|j
gdd }|jD ]
}|j|_|j|_qNtt|jj
j|j}|||j
j< |||j
j< |||jj
j< |||jj
j< td  D ]\}}||v r|| d |< qd | ||_|jfi ||_|S |jrd|d< |jddi| |S |jr|jr|dd dk}	|	rՈi  d|d< |jddi| |	rd= |S |jddi| |S )	Nr   T)
use_labelsZselect_containerZtransform_cluecloneZinside_selectrU   )r  Zis_selectableZ_is_joinr+  rF   r   ZFromGroupingZ_reset_exportedr4   r#  r   r9  rl  r   r;  r   Z_labelr	  zipr   itemsr>  onclauseZ_is_from_containerZ_copy_internalsZ
_is_selectr   r  )
r   r   ZnewelemrF   Zselectable_rl  Ztranslate_dictkvZbarrier_selectZclonedZcolumn_translatevisitrU   rY   rT    sj   


z=SQLCompiler._transform_select_for_nested_joins.<locals>.visitrU   )r   rG   rU   rS  rY   "_transform_select_for_nested_joins  s   Qz.SQLCompiler._transform_select_for_nested_joinsc                    sF   t dd |jD t fdd|jD   fdd| jD | _d S )Nc                 s   s    | ]}|j |fV  qd S r   r;  r{  rU   rU   rY   r        

zESQLCompiler._transform_result_map_for_nested_joins.<locals>.<genexpr>c                 3   s    | ]
} |j  |fV  qd S r   rV  r{  )	inner_colrU   rY   r        c                    2   g | ]\}}}}||t  fd d|D |fqS )c                    s   g | ]}  ||qS rU   r   )rW   r   drU   rY   r        zQSQLCompiler._transform_result_map_for_nested_joins.<locals>.<listcomp>.<listcomp>tuple)rW   r   r   Zobjstypr\  rU   rY   r        
zFSQLCompiler._transform_result_map_for_nested_joins.<locals>.<listcomp>)r	  r%  r   )r   rG   transformed_selectrU   )r]  rX  rY   &_transform_result_map_for_nested_joins  s   
z2SQLCompiler._transform_result_map_for_nested_joinsr  r  c           	      C   s^   | j  }|r	| jn| j d }|d }|d }|r&|s&|j||dd}|S |j||d}|S )Nr   r  r  rU   Zexplicit_correlate_fromsZimplicit_correlate_froms)r   re  _get_display_froms
difference)	r   rG   r  r2  rj  r   r  r  fromsrU   rU   rY   _display_froms_for_select  s"   z%SQLCompiler._display_froms_for_selectc	                    sj  j o| oj ojj }
|
r%}j|f |||dd|	}j }|r.jnjd }|p@|ddp@|dd |dkrIdsRd|	v rR|	d= |
r^r\| |S 	| |}|	
 ddd	 d
}jr\}}|r||d 7 }nd }jr|jjfi |	7 }|jfi |	7 }dd  fddjD D }r|d urttdd jD dd |jD fddjD _|||||	}jrfddjD }|r|d| 7 }jr|r | }jr|djjfi |	 7 }jd  s*|r3|r3d| d S |S )NT)r  ri  r-  rh  nested_join_translationr   rb  Fr   r   r1  )r*  r  zSELECT r   c                 S   r  r   rU   r{  rU   rU   rY   r  u  s
    z,SQLCompiler.visit_select.<locals>.<listcomp>c                    s(   g | ]\}}j | |d qS ))r   r@  rA  )rW   r   r   )r  r?  r@  rk  rG   r   rU   rY   r  w  s    
c                 S      g | ]\}}|qS rU   rU   rW   r   r   rU   rU   rY   r    r[   c                 S   rl  rU   rU   rm  rU   rU   rY   r    s    c                    rZ  )c                 3   s    | ]	}  ||V  qd S r   r[  )rW   o	translaterU   rY   r    s    z6SQLCompiler.visit_select.<locals>.<listcomp>.<genexpr>r_  )rW   r   r   r   r   ro  rU   rY   r    rb  c                    s$   g | ]\}}|d  j jfv r|qS *r   r   )rW   dialect_nameZhtr   rU   rY   r    s
    r  r  )rL  r   r   Zsupports_right_nested_joinsrU  visit_selectre  r   rd  _setup_select_stackcopyr>  _hints_setup_select_hintsr'  r&  get_select_precolumnsZ_columns_plus_namesr	  rN  r   _compose_select_bodyZ_statement_hintsrK  r   r  r(  r   )r   rG   r  ri  r-  rh  rj  Zselect_wraps_forr2  r   Zneeds_nested_translationrc  rW  rj  r   rh  	hint_textbyfromr%  Zper_dialectrU   )r  r?  r@  rk  rG   r   rp  rY   ru  %  s   







zSQLCompiler.visit_selectc                    s.   t  fdd|j D } |}||fS )Nc              	      s>   g | ]\\}}}|d  j jfv r||d|j ddi fqS )rr  r   T)r,  r   r   r   )rW   from_r   rE  r   rU   rY   r    s    
z3SQLCompiler._setup_select_hints.<locals>.<listcomp>)r	  rx  rO  rG  )r   rG   r}  r|  rU   r   rY   ry    s   

zSQLCompiler._setup_select_hintsc                 C   sp   |d }|d }|r|s|j ||dd}n|j ||d}ttj| }||}	||	|d}
| j|
 |S )Nr  r  rU   re  )r  r  r   )rf  rg  rI   r   _from_objectsrN   r   r  )r   rG   r   r  r2  r  r  rh  Znew_correlate_fromsZall_correlate_fromsZ	new_entryrU   rU   rY   rv    s*   
zSQLCompiler._setup_select_stackc                    sT  |d |7 }|r1|d7 }|jr!|d  fdd|D 7 }n|d fdd|D 7 }n| 7 }|jd urN|jjfi }|rN|d| 7 }|jjr]|j|fi 7 }|jd urt|jjfi }|rt|d| 7 }|j	jr|j
|fi 7 }|jd us|jd ur|j|fi 7 }|jd ur|j|fi 7 }|S )Nre   z 
FROM c                    s$   g | ]}|j fd  dqS )Tr  r-  r   rW   fr}  r   r   rU   rY   r    s    z4SQLCompiler._compose_select_body.<locals>.<listcomp>c                    s"   g | ]}|j fd di qS )r  Tr   r  r  rU   rY   r    s    z 
WHERE z	 
HAVING )r2   rx  r  _whereclauser   _group_by_clauser~  r  Z_having_order_by_clauser  r  r  r  Z_for_update_argfor_update_clause)r   rW  rG   r%  rh  r}  r   trU   r  rY   r{    sB   	




z SQLCompiler._compose_select_bodyc                    s*   d  fdd|D }|r|d7 }|S )Nr   c                 3   s:    | ]\}}|d u s|j jkr|jfi  V  qd S r   r~  )rW   prefixrt  r|  rU   rY   r  	  s    z1SQLCompiler._generate_prefixes.<locals>.<genexpr>rJ  )r   stmtprefixesr   r  rU   r|  rY   r&  	  s   zSQLCompiler._generate_prefixesc                    sb    j rt fdd jD g  j  _  jd }|ddd  j D 7 }|d7 }|S )Nc                    s   g | ]} j | qS rU   )r   )rW   r+  r   rU   rY   r  $	  s    z2SQLCompiler._render_cte_clause.<locals>.<listcomp>r   , 
c                 S   s   g | ]}|qS rU   rU   )rW   txtrU   rU   rY   r  (	  s    z
 )r   sumr   r   get_cte_preambler   r2   values)r   Zcte_textrU   r   rY   r  !	  s   zSQLCompiler._render_cte_clausec                 C   s   |rdS dS )NzWITH RECURSIVEZWITHrU   )r   r   rU   rU   rY   r  ,	  s   zSQLCompiler.get_cte_preamblec                 K   s   |j rdpdS )zcCalled when building a ``SELECT`` statement, position is just
        before column list.

        rg   r   )Z	_distinctr   rG   r   rU   rU   rY   rz  2	  s   z!SQLCompiler.get_select_precolumnsc                 K   $   |j j| fi |}|rd| S dS )z5allow dialects to customize how GROUP BY is rendered.z
 GROUP BY r   )r  r   )r   rG   r   Zgroup_byrU   rU   rY   r  9	     zSQLCompiler.group_by_clausec                 K   r  )z5allow dialects to customize how ORDER BY is rendered.z
 ORDER BY r   )r  r   )r   rG   r   r  rU   rU   rY   r  B	  r  zSQLCompiler.order_by_clausec                 K   r   )Nz FOR UPDATErU   r  rU   rU   rY   r  K	  r   zSQLCompiler.for_update_clausec                 C   r3  )Nz@RETURNING is not supported by this dialect's statement compiler.r4  )r   r  returning_colsrU   rU   rY   returning_clauseN	  r7  zSQLCompiler.returning_clausec                 K   sf   d}|j d ur|d| j|j fi | 7 }|jd ur1|j d u r#|d7 }|d| j|jfi | 7 }|S )Nr   z
 LIMIT z

 LIMIT -1z OFFSET )r  r   r  )r   rG   r   rW  rU   rU   rY   r  T	  s   


zSQLCompiler.limit_clausec           
      K   sr   |s|r7| j |}|r|r| j |d | j |j }	n| j |j}	|r5||v r5| |	||| |}	|	S dS )Nr8  r   )r   r=  r>  r<  r   r.  )
r   rK   r  r/  r,  r-  
use_schemar   r@  r0  rU   rU   rY   visit_table^	  s    

zSQLCompiler.visit_tablec                 K   sh   |j rd}n|jrd}nd}|jj| fddi|| |jj| fddi| d |jj| fi | S )Nz FULL OUTER JOIN z LEFT OUTER JOIN z JOIN r  Tz ON )r,   Zisouterr4   r   rF   rP  )r   r2   r  r   Z	join_typerU   rU   rY   
visit_join{	  s   zSQLCompiler.visit_joinc                    sF   t  fdd|j D }|j|v r ||j||j d}||fS )Nc                    s,   g | ]\\}}}|d  j jfv r||fqS rq  rs  )rW   rK   r   r|  r   rU   rY   r  	  s
    
z1SQLCompiler._setup_crud_hints.<locals>.<listcomp>T)r	  rx  rO  rK   r.  )r   r  
table_textdialect_hintsrU   r   rY   _setup_crud_hints	  s   

zSQLCompiler._setup_crud_hintsc                    s  | j  }| j t t |d tj| |tjfi |}|s/| jjs/| jjs/t	
d| jj |jrD| jjs?t	
d| jj |d }n|}| j | jj}d}|jr_|| j||jfi |7 }|d7 } |j}	|jrt| ||	\}
}	||	7 }|s||s|dd fd	d
|D  7 }| js|jr| || jp|j}| jr|d| 7 }nd }|jd ur| j| jfi |}| jr|r| jjr|d|  |f 7 }n8|d| 7 }n1|s|r|d7 }n(|jr|dddd |D  7 }nddd
 |D }|d| 7 }|r|| _ |j!d ur| j|j!fi |}|r|d| 7 }|r)| js)|d| 7 }| jr;|r;| jjs;|  | }| j "d |rJd| d S |S )Nr  r  r   zWThe '%s' dialect with current database version settings does not support empty inserts.zcThe '%s' dialect with current database version settings does not support in-place multirow inserts.r   zINSERT zINTO z (%s)re   c                    s   g | ]	}  |d  qS )r   )r  r{  r   rU   rY   r  	  s    z,SQLCompiler.visit_insert.<locals>.<listcomp>r   z %s%sz %sz DEFAULT VALUESz
 VALUES %sc                 s   s(    | ]}d d dd |D  V  qdS )rd  re   c                 s   s    | ]}|d  V  qdS )r   NrU   r{  rU   rU   rY   r  	  s    z5SQLCompiler.visit_insert.<locals>.<genexpr>.<genexpr>NrJ  )rW   Zcrud_param_setrU   rU   rY   r  	  
    
z+SQLCompiler.visit_insert.<locals>.<genexpr>c                 S   s   g | ]}|d  qS )r   rU   r{  rU   rU   rY   r  	  r[   z VALUES (%s)r   r  r  )#r   r  rI   r   _setup_crud_paramsZISINSERTr   supports_default_valuesZsupports_empty_insertr   r'  r   Z_has_multi_parametersZsupports_multivalues_insertr   r'  r&  format_tablerK   rx  r  r2   r   r   r  returning_precedes_valuesrG   r   Z_insert_from_selectr   Zcte_follows_insertr  insert_single_values_exprZ_post_values_clauser   )r   Zinsert_stmtr  r   rj  crud_paramsZcrud_params_singler  rW  r  r   r  Zselect_textr  Zpost_values_clauserU   r  rY   visit_insert	  s   



zSQLCompiler.visit_insertc                 C   r   )z3Provide a hook for MySQL to add LIMIT to the UPDATENrU   )r   update_stmtrU   rU   rY   update_limit_clause
  r  zSQLCompiler.update_limit_clausec                 K   s   d|d< |j | fddi|S )z|Provide a hook to override the initial table clause
        in an UPDATE statement.

        MySQL overrides this.

        Tr  r/  r   )r   r  
from_tableextra_fromsr   rU   rU   rY   update_tables_clause
  s   z SQLCompiler.update_tables_clausec                 K      t d)z~Provide a hook to override the generation of an
        UPDATE..FROM clause.

        MySQL and MSSQL override this.

        zCThis backend does not support multiple-table criteria within UPDATEr   r   r  r  r  
from_hintsr   rU   rU   rY   update_from_clause
  s   	zSQLCompiler.update_from_clausec                    s  j  }|j}t|}|r$tt|jfdd|D }|}ng }|jh}j |||d d}	|j	rF|	j
||j	fi |7 }	j||j|fi |}
tj|tjfi |}|jrj||
\}}
nd }|	|
7 }	|	d7 }	|oxj |	d fdd|D 7 }	js|jrjr|	d	|jp|j 7 }	|rj||j||fi |}|r|	d	| 7 }	|jd ur͈j|jfi |}|r|	d
| 7 }	|}|r|	d	| 7 }	js|jrjs|	d	|jp|j 7 }	jr|r |	 }	j d |rd|	 d S |	S )Nc                    s   g | ]}| vr|qS rU   rU   r  )
main_fromsrU   rY   r  -
  s    z,SQLCompiler.visit_update.<locals>.<listcomp>r  zUPDATE z SET re   c                 3   s.    | ]}|d  j  dd |d  V  qdS )r   )r?  =r   Nr   r{  )r?  r   rU   rY   r  X
  s    
z+SQLCompiler.visit_update.<locals>.<genexpr>r    WHERE r   r  r  )r   _extra_fromsboolrI   r   r  rK   rN   r  r'  r&  r  r   r  ZISUPDATErx  r  'render_table_with_column_in_update_fromr2   r   r   r  r  r  r  r   r  r   r  r   )r   r  r  r   rj  r  Zis_multitableZrender_extra_fromsr  rW  r  r  r  extra_from_textr  r  rU   )r?  r  r   rY   visit_update$
  s   





zSQLCompiler.visit_updatec                 C   s   t | | jS r   )r   _key_getters_for_crud_columnr   r   rU   rU   rY   r  
  s   z(SQLCompiler._key_getters_for_crud_columnc                 K   r  )zProvide a hook to override the generation of an
        DELETE..FROM clause.

        This can be used to implement DELETE..USING for example.

        MySQL and MSSQL override this.

        zCThis backend does not support multiple-table criteria within DELETEr   r  rU   rU   rY   delete_extra_from_clause
  s   z$SQLCompiler.delete_extra_from_clausec                 C   s   |j | dddS )NT)r  r/  r   )r   delete_stmtr  r  rU   rU   rY   delete_table_clause
     zSQLCompiler.delete_table_clausec                 K   s~  | j  }tj| |tjfi | |j}|jh|}| j |||d d}|jr6|| j	||jfi |7 }|d7 }| 
||j|}|jrN| ||\}	}nd }	||7 }|jre| jre|d| ||j 7 }|r|| j||j||	fi |}
|
r||d|
 7 }|jd ur|jj| fi |}|r|d| 7 }|jr| js|d| ||j 7 }| jr|r|  | }| j d |rd| d S |S )	Nr  zDELETE FROM r   r  r   r  r  )r   r   r  ZISDELETEr  rK   rN   r  r'  r&  r  rx  r  r   r  r  r  r  r   r   r  r   )r   r  r  r   rj  r  r  rW  r  r  r  r  rU   rU   rY   visit_delete
  sr   


zSQLCompiler.visit_deletec                 C      d| j | S )NzSAVEPOINT %sr   format_savepointr   Zsavepoint_stmtrU   rU   rY   visit_savepoint
  r  zSQLCompiler.visit_savepointc                 C   r  )NzROLLBACK TO SAVEPOINT %sr  r  rU   rU   rY   visit_rollback_to_savepoint
     z'SQLCompiler.visit_rollback_to_savepointc                 C   r  )NzRELEASE SAVEPOINT %sr  r  rU   rU   rY   visit_release_savepoint
  r  z#SQLCompiler.visit_release_savepoint)NF)NNTF)NFFN)NT)NFTr   )FTr   )FFF)FFNN)FFFNNTF)FTNr   FNF)FFFNT)r   r   r   r   EXTRACT_MAPr  COMPOUND_KEYWORDSr  r   r   r   r^  r   r  r  r  r  rf  r   r   r  r   r   r   r   r   r   r   Zmemoized_instancemethodr   
contextlibcontextmanagerr   r   memoized_propertyr
  r  r   r   r   dependenciesr  r  r  r$  r(  r2  r6  rA  rD  rG  rJ  rN  rX  r;  ra  rm  rp  ru  rx  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r  r   r  r-  r  rZ  r  r1  r3  r5  r*  rg  rA  r.  rG  rB  rI  rK  rU  rd  r   	frozensetre  ri  ru  ry  rv  r{  r&  r  r  rz  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rU   rU   rU   rY   r     s   I
%




8

	#1( "3			
=!
\] 6
		p
f
Jr   c                   @   sX   e Z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d Zdd ZdS )StrSQLCompilera  A :class:`.SQLCompiler` subclass which allows a small selection
    of non-standard SQL features to render into a string value.

    The :class:`.StrSQLCompiler` is invoked whenever a Core expression
    element is directly stringified without calling upon the
    :meth:`_expression.ClauseElement.compile` method.
    It can render a limited set
    of non-standard SQL constructs to assist in basic stringification,
    however for more substantial custom or dialect-specific SQL constructs,
    it will be necessary to make use of
    :meth:`_expression.ClauseElement.compile`
    directly.

    .. seealso::

        :ref:`faq_sql_expression_string`

    c                 C   r   )Nz<name unknown>rU   r5  rU   rU   rY   r6    r   z$StrSQLCompiler._fallback_column_namec                 K   s,   d| j |jfi || j |jfi |f S )Nz%s[%s])r   r4   rF   r  rU   rU   rY   visit_getitem_binary  r  z#StrSQLCompiler.visit_getitem_binaryc                 K      | j ||fi |S r   r  r  rU   rU   rY   visit_json_getitem_op_binary  r  z+StrSQLCompiler.visit_json_getitem_op_binaryc                 K   r  r   r  r  rU   rU   rY   !visit_json_path_getitem_op_binary  r  z0StrSQLCompiler.visit_json_path_getitem_op_binaryc                 K   r  )Nz<next sequence value: %s>)r   format_sequence)r   seqr   rU   rU   rY   r    r  zStrSQLCompiler.visit_sequencec                    s&    fddt |D }dd| S )Nc              	      s   g | ]}  d |ddi qS r  rk  r{  r   rU   rY   r     s    z3StrSQLCompiler.returning_clause.<locals>.<listcomp>z
RETURNING re   )r   Z_select_iterablesr2   )r   r  r  columnsrU   r   rY   r    s   
zStrSQLCompiler.returning_clausec                    s    dd  fdd|D  S )Nr  re   c                 3   (    | ]}|j fd  dV  qdS Tr  Nr   rW   r  r  r   r   rU   rY   r  *  r  z4StrSQLCompiler.update_from_clause.<locals>.<genexpr>rJ  r  rU   r  rY   r  '     
z!StrSQLCompiler.update_from_clausec                    s    dd  fdd|D  S )Nre   c                 3   r  r  r   r  r  rU   rY   r  2  r  z:StrSQLCompiler.delete_extra_from_clause.<locals>.<genexpr>rJ  r  rU   r  rY   r  /  r  z'StrSQLCompiler.delete_extra_from_clausec                 C   s   d| S )Nz[%s]rU   rH  rU   rU   rY   rB  7  r6  z!StrSQLCompiler.get_from_hint_textN)r   r   r   r   r6  r  r  r  r  r  r  r  rB  rU   rU   rU   rY   r  
  s    r  c                   @   sN  e Zd Zejdd Zejdd ZdNddZdd	 Zd
d Z	dd Z
dd ZdOddZ	dNddZdd Zdd Zdd Z	dPddZdd ZdOd d!Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Z d<d= Z!d>d? Z"d@dA Z#dBdC Z$dDdE Z%dFdG Z&dHdI Z'dJdK Z(dLdM Z)dS )QDDLCompilerc                 C   s   | j j| j d | jdS )N)r   )r   Zstatement_compilerr   r   rU   rU   rY   r   <  s   
zDDLCompiler.sql_compilerc                 C   r   r   )r   rL  r   rU   rU   rY   rL  B  r   zDDLCompiler.type_compilerNc                 C   rF  r   rU   r   rU   rU   rY   r   F  r   zDDLCompiler.construct_paramsc                 K   s   |j }t|jtjrD| }| j}||j}t|dkr%|d d}}n	|d |d }}|	d| |	d| |	d|
|j | j|j| S )Nr   r   r   r   rK   r   fullname)contextr+  targetr   Tablerw  r   format_table_seqr  
setdefaultr  r   rX  r   )r   Zddlr   r  r   pathrK   ZschrU   rU   rY   	visit_ddlI  s   zDDLCompiler.visit_ddlc                 C   s   | j |j}d| S )NzCREATE SCHEMA )r   format_schemar   )r   r   r   rU   rU   rY   visit_create_schema\  s   zDDLCompiler.visit_create_schemac                 C   s(   | j |j}d| }|jr|d7 }|S )NzDROP SCHEMA  CASCADE)r   r  r   cascade)r   dropr   rW  rU   rU   rY   visit_drop_schema`  s
   zDDLCompiler.visit_drop_schemac                 C   sN  |j }| j}d}|jr|d|jd 7 }|d|| d 7 }| |}|r-||d 7 }|d7 }d}d}|jD ]Q}|j }	z"| j||	joF| d}
|
d urY||7 }d}|d	|
 7 }|	jr^d
}W q8 t	j
y } ztjt	
td|j|	j|jd f |d W Y d }~q8d }~ww | j||jd}|r||d	 | 7 }|d| | 7 }|S )Nz
CREATE r   zTABLE r  
Ffirst_pkr  	Tz (in table '%s', column '%s'): %sr   )r  ) _include_foreign_key_constraintsz
)%s

)r   r   r'  r2   r  create_table_suffixr  r   primary_keyr   r'  r   r   udescriptionr   argscreate_table_constraintsZinclude_foreign_key_constraintspost_create_table)r   r   rK   r   rW  r  	separatorr  Zcreate_columnr   	processedZceconstrU   rU   rY   visit_create_tableg  sX   

	zDDLCompiler.visit_create_tableFc                    sL   |j }|jrd S  j||d}d fdd|jD }|r$|d| 7 }|S )Nr  r   c                 3   s    | ]}  |V  qd S r   )r   rW   r   r   rU   rY   r    rW  z2DDLCompiler.visit_create_column.<locals>.<genexpr>)r   systemget_column_specificationr2   constraints)r   r   r  r   rW  r  rU   r   rY   visit_create_column  s   zDDLCompiler.visit_create_columnc                    st   g }j r|j  j}|d ur|| nt  | fddjD  ddd fdd|D D S )Nc                    s"   g | ]}|j ur| vr|qS rU   )r  r{  )	omit_fkcsrK   rU   rY   r    s
    z8DDLCompiler.create_table_constraints.<locals>.<listcomp>z, 
	c                 s   s    | ]	}|d ur|V  qd S r   rU   )rW   prU   rU   rY   r    s    z7DDLCompiler.create_table_constraints.<locals>.<genexpr>c                 3   sB    | ]}|j d u s|  r jjrt|dds |V  qd S )NZ	use_alterF)Z_create_ruler   Zsupports_alterr   r   r  r   rU   rY   r    s    

)r  r  Zforeign_key_constraintsrg  rI   extendZ_sorted_constraintsr2   )r   rK   r  r   Zall_fkcsrU   )r  r   rK   rY   r    s"   

z$DDLCompiler.create_table_constraintsc                 C      d| j |j S )Nz
DROP TABLE r   r  r   r   r  rU   rU   rY   visit_drop_table  r   zDDLCompiler.visit_drop_tablec                 C   r  )Nz
DROP VIEW r  r  rU   rU   rY   visit_drop_view  r   zDDLCompiler.visit_drop_viewc                 C   s   |j d u rtd|j d S )Nz,Index '%s' is not associated with any table.)rK   r   r'  r   r   rI  rU   rU   rY   _verify_index_table  s
   
zDDLCompiler._verify_index_tableTc              	      s~   |j } |  j}d}|jr|d7 }|jd u rtd|d j||d|j|j	|dd
 fdd	|jD f 7 }|S )
NzCREATE zUNIQUE z0CREATE INDEX requires that the index have a namezINDEX %s ON %s (%s)include_schemar  re   c                 3   s"    | ]} j j|d ddV  qdS )FTr?  r  N)r   r   )rW   ro  r   rU   rY   r    s    
z1DDLCompiler.visit_create_index.<locals>.<genexpr>)r   r  r   rO   r   r   r'  _prepared_index_namer  rK   r2   Zexpressions)r   r   r  Zinclude_table_schemarI  r   rW  rU   r   rY   visit_create_index  s(   

zDDLCompiler.visit_create_indexc                 C   s,   |j }|jd u rtdd| j|dd S )Nz.DROP INDEX requires that the index have a namez
DROP INDEX Tr  )r   r   r   r'  r  )r   r  rI  rU   rU   rY   visit_drop_index  s   
zDDLCompiler.visit_drop_indexc                 C   sX   |j d ur| j|j }nd }|r|r| j|}nd }| j|}|r*|d | }|S Nr8  )rK   r   r=  r>  format_index)r   rI  r  r@  Zschema_nameZ
index_namerU   rU   rY   r    s   
z DDLCompiler._prepared_index_namec                 C   s    d| j |jj| |jf S )NzALTER TABLE %s ADD %s)r   r  r   rK   r   r   r   rU   rU   rY   visit_add_constraint  s   
z DDLCompiler.visit_add_constraintc                 C   s(   d| j |j| j|jjt f S )NzCOMMENT ON TABLE %s IS %s)r   r  r   r   r   commentr	   Stringr  rU   rU   rY   visit_set_table_comment  s   z#DDLCompiler.visit_set_table_commentc                 C      d| j |j S )NzCOMMENT ON TABLE %s IS NULLr  r  rU   rU   rY   visit_drop_table_comment!  s   z$DDLCompiler.visit_drop_table_commentc                 C   s.   d| j j|jddd| j|jjt f S )NzCOMMENT ON COLUMN %s IS %sT)	use_tabler  )r   r  r   r   r   r  r	   r  r  rU   rU   rY   visit_set_column_comment&  s   z$DDLCompiler.visit_set_column_commentc                 C   s   d| j j|jdd S )NzCOMMENT ON COLUMN %s IS NULLT)r  )r   r  r   r  rU   rU   rY   visit_drop_column_comment0  s   z%DDLCompiler.visit_drop_column_commentc                 C   s   d| j |j }|jjd ur|d|jj 7 }|jjd ur%|d|jj 7 }|jjd ur3|d|jj 7 }|jjd urA|d|jj 7 }|jjd urK|d7 }|jjd urU|d7 }|jj	d urc|d|jj	 7 }|jj
d	u rm|d
7 }|jjd urw|d7 }|S )NzCREATE SEQUENCE %sz INCREMENT BY %dz START WITH %dz MINVALUE %dz MAXVALUE %dz NO MINVALUEz NO MAXVALUEz	 CACHE %dTz ORDERz CYCLE)r   r  r   	incrementstartZminvalueZmaxvalueZ
nominvalueZ
nomaxvaluecacherB   cycle)r   r   rW  rU   rU   rY   visit_create_sequence5  s,   z!DDLCompiler.visit_create_sequencec                 C   r  )NzDROP SEQUENCE %s)r   r  r   r  rU   rU   rY   visit_drop_sequenceM  r   zDDLCompiler.visit_drop_sequencec                 C   s^   |j }|jd ur| j|}nd }|d u rtd|j  d| j|j j||jr+dp,df S )Nz<Can't emit DROP CONSTRAINT for constraint %r; it has no namez#ALTER TABLE %s DROP CONSTRAINT %s%sr  r   )	r   r   r   format_constraintr   r'  r  rK   r  )r   r  r   formatted_namerU   rU   rY   visit_drop_constraintP  s   
z!DDLCompiler.visit_drop_constraintc                 K   sr   | j |d | jjj|j|d }| |}|d ur!|d| 7 }|jd ur0|d| |j 7 }|js7|d7 }|S )Nr   )rK  z	 DEFAULT z	 NOT NULL)	r   r  r   rL  r   r   get_column_default_stringZcomputedZnullable)r   r   r   Zcolspecr"   rU   rU   rY   r  b  s    


z$DDLCompiler.get_column_specificationc                 C   r   Nr   rU   r   rK   rU   rU   rY   r  u  r   zDDLCompiler.create_table_suffixc                 C   r   r)  rU   r*  rU   rU   rY   r  x  r   zDDLCompiler.post_create_tablec                 C   sJ   t |jtjr#t |jjtjr| j|jjt	j
S | jj|jjddS d S )NT)r  )r+  Zserver_defaultr   ZDefaultClauseargr   string_typesr   r   r	   r  r   r5  rU   rU   rY   r(  {  s   
z%DDLCompiler.get_column_default_stringc                 C   \   d}|j d ur| j|}|d ur|d| 7 }|d| jj|jddd 7 }|| |7 }|S Nr   CONSTRAINT %s z
CHECK (%s)FTr  r   r   r%  r   r   rC  define_constraint_deferrabilityr   r   rW  r&  rU   rU   rY   visit_check_constraint     


z"DDLCompiler.visit_check_constraintc                 C   r-  r.  r0  r2  rU   rU   rY   visit_column_check_constraint  r4  z)DDLCompiler.visit_column_check_constraintc                    s   t |dkrdS d}|jd ur j|}|d ur|d| 7 }|d7 }|dd fdd|jr2|jn|jD  7 }| |7 }|S )	Nr   r   r/  zPRIMARY KEY rd  re   c                 3       | ]
} j |jV  qd S r   r   r<  r   r{  r   rU   rY   r    s
    
z;DDLCompiler.visit_primary_key_constraint.<locals>.<genexpr>)	r  r   r   r%  r2   Z_implicit_generatedZcolumns_autoinc_firstr  r1  r2  rU   r   rY   visit_primary_key_constraint  s   
z(DDLCompiler.visit_primary_key_constraintc              	      s   | j  d}|jd ur| j |}|d ur|d| 7 }t|jd jj}|dd fdd|jD | || d fdd|jD f 7 }|| 	|7 }|| 
|7 }|| |7 }|S )	Nr   r/  r   z"FOREIGN KEY(%s) REFERENCES %s (%s)re   c                 3       | ]
}  |jjV  qd S r   )r<  parentr   r  r  rU   rY   r        
z;DDLCompiler.visit_foreign_key_constraint.<locals>.<genexpr>c                 3   r9  r   )r<  r   r   r  r  rU   rY   r    r;  )r   r   r%  r   r   r   rK   r2   define_constraint_remote_tabledefine_constraint_matchdefine_constraint_cascadesr1  )r   r   rW  r&  Zremote_tablerU   r  rY   visit_foreign_key_constraint  s,   
z(DDLCompiler.visit_foreign_key_constraintc                 C   s
   | |S )z=Format the remote table clause of a CREATE CONSTRAINT clause.)r  )r   r   rK   r   rU   rU   rY   r<    r   z*DDLCompiler.define_constraint_remote_tablec                    sp   t |dkrdS d}|jd ur j|}|d ur|d| 7 }|dd fdd|D  7 }| |7 }|S )Nr   r   r/  zUNIQUE (%s)re   c                 3   r6  r   r7  r{  r   rU   rY   r    rY  z6DDLCompiler.visit_unique_constraint.<locals>.<genexpr>)r  r   r   r%  r2   r1  r2  rU   r   rY   visit_unique_constraint  s   
z#DDLCompiler.visit_unique_constraintc                 C   sL   d}|j d ur|d| j|j t 7 }|jd ur$|d| j|jt 7 }|S )Nr   z ON DELETE %sz ON UPDATE %s)Zondeleter   validate_sql_phraseFK_ON_DELETEZonupdateFK_ON_UPDATEr   r   rW  rU   rU   rY   r>    s   



z&DDLCompiler.define_constraint_cascadesc                 C   sL   d}|j d ur|j r|d7 }n|d7 }|jd ur$|d| j|jt 7 }|S )Nr   z DEFERRABLEz NOT DEFERRABLEz INITIALLY %s)r#   r/   r   rA  FK_INITIALLYrD  rU   rU   rY   r1    s   



z+DDLCompiler.define_constraint_deferrabilityc                 C   s    d}|j d ur|d|j  7 }|S )Nr   z	 MATCH %s)matchrD  rU   rU   rY   r=    s   
z#DDLCompiler.define_constraint_matchc                 C   sD   d| j j|jddd }|jdu r|d7 }|S |jdu r |d7 }|S )NzGENERATED ALWAYS AS (%s)FTr  z STOREDz VIRTUAL)r   r   rC  Z	persisted)r   	generatedrW  rU   rU   rY   visit_computed_column  s   

z!DDLCompiler.visit_computed_columnr   r  )FT)*r   r   r   r   r  r   rL  r   r  r  r  r  r  r  r  r	  r  r  r  r  r  r  r  r  r  r#  r$  r'  r  r  r  r(  r3  r5  r8  r?  r<  r@  r>  r1  r=  rH  rU   rU   rU   rY   r  ;  sT    



2
)


r  c                   @   s\  e 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d Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!d?d@ Z"dAdB Z#dCdD Z$dEdF Z%dGdH Z&dIdJ Z'dKdL Z(dMdN Z)dOdP Z*dQdR Z+dSdT Z,dUS )VGenericTypeCompilerc                 K   r   )NFLOATrU   r   rU   rU   rY   visit_FLOAT
  r   zGenericTypeCompiler.visit_FLOATc                 K   r   )NZREALrU   r   rU   rU   rY   
visit_REAL  r   zGenericTypeCompiler.visit_REALc                 K   8   |j d u rdS |jd u rdd|j i S d|j |jd S )NZNUMERICzNUMERIC(%(precision)s)	precisionz!NUMERIC(%(precision)s, %(scale)s)rN  scalerO  r   rU   rU   rY   visit_NUMERIC     

z!GenericTypeCompiler.visit_NUMERICc                 K   rM  )NZDECIMALzDECIMAL(%(precision)s)rN  z!DECIMAL(%(precision)s, %(scale)s)rO  rO  r   rU   rU   rY   visit_DECIMAL  rR  z!GenericTypeCompiler.visit_DECIMALc                 K   r   )NZINTEGERrU   r   rU   rU   rY   visit_INTEGER&  r   z!GenericTypeCompiler.visit_INTEGERc                 K   r   )NZSMALLINTrU   r   rU   rU   rY   visit_SMALLINT)  r   z"GenericTypeCompiler.visit_SMALLINTc                 K   r   )NZBIGINTrU   r   rU   rU   rY   visit_BIGINT,  r   z GenericTypeCompiler.visit_BIGINTc                 K   r   )N	TIMESTAMPrU   r   rU   rU   rY   visit_TIMESTAMP/  r   z#GenericTypeCompiler.visit_TIMESTAMPc                 K   r   )NZDATETIMErU   r   rU   rU   rY   visit_DATETIME2  r   z"GenericTypeCompiler.visit_DATETIMEc                 K   r   )NZDATErU   r   rU   rU   rY   
visit_DATE5  r   zGenericTypeCompiler.visit_DATEc                 K   r   )NZTIMErU   r   rU   rU   rY   
visit_TIME8  r   zGenericTypeCompiler.visit_TIMEc                 K   r   )NZCLOBrU   r   rU   rU   rY   
visit_CLOB;  r   zGenericTypeCompiler.visit_CLOBc                 K   r   )NZNCLOBrU   r   rU   rU   rY   visit_NCLOB>  r   zGenericTypeCompiler.visit_NCLOBc                 C   s0   |}|j r|d|j  7 }|jr|d|j 7 }|S )N(%d)z COLLATE "%s")lengthrC  )r   r   r   rW  rU   rU   rY   _render_string_typeA  s   z'GenericTypeCompiler._render_string_typec                 K      |  |dS )NZCHARr`  r   rU   rU   rY   
visit_CHARJ  r  zGenericTypeCompiler.visit_CHARc                 K   ra  )NZNCHARrb  r   rU   rU   rY   visit_NCHARM  r  zGenericTypeCompiler.visit_NCHARc                 K   ra  )NZVARCHARrb  r   rU   rU   rY   visit_VARCHARP  r  z!GenericTypeCompiler.visit_VARCHARc                 K   ra  )NZNVARCHARrb  r   rU   rU   rY   visit_NVARCHARS  r  z"GenericTypeCompiler.visit_NVARCHARc                 K   ra  )NZTEXTrb  r   rU   rU   rY   
visit_TEXTV  r  zGenericTypeCompiler.visit_TEXTc                 K   r   )NZBLOBrU   r   rU   rU   rY   
visit_BLOBY  r   zGenericTypeCompiler.visit_BLOBc                 K      d|j r	d|j  p
d S )NBINARYr^  r   r_  r   rU   rU   rY   visit_BINARY\  r  z GenericTypeCompiler.visit_BINARYc                 K   ri  )NZ	VARBINARYr^  r   rk  r   rU   rU   rY   visit_VARBINARY_  r  z#GenericTypeCompiler.visit_VARBINARYc                 K   r   )NZBOOLEANrU   r   rU   rU   rY   visit_BOOLEANb  r   z!GenericTypeCompiler.visit_BOOLEANc                 K      | j |fi |S r   )rh  r   rU   rU   rY   visit_large_binarye  r   z&GenericTypeCompiler.visit_large_binaryc                 K   ro  r   )rn  r   rU   rU   rY   visit_booleanh  r   z!GenericTypeCompiler.visit_booleanc                 K   ro  r   )r[  r   rU   rU   rY   
visit_timek  r   zGenericTypeCompiler.visit_timec                 K   ro  r   )rY  r   rU   rU   rY   visit_datetimen  r   z"GenericTypeCompiler.visit_datetimec                 K   ro  r   )rZ  r   rU   rU   rY   
visit_dateq  r   zGenericTypeCompiler.visit_datec                 K   ro  r   )rV  r   rU   rU   rY   visit_big_integert  r   z%GenericTypeCompiler.visit_big_integerc                 K   ro  r   )rU  r   rU   rU   rY   visit_small_integerw  r   z'GenericTypeCompiler.visit_small_integerc                 K   ro  r   )rT  r   rU   rU   rY   visit_integerz  r   z!GenericTypeCompiler.visit_integerc                 K   ro  r   )rL  r   rU   rU   rY   
visit_real}  r   zGenericTypeCompiler.visit_realc                 K   ro  r   )rK  r   rU   rU   rY   visit_float  r   zGenericTypeCompiler.visit_floatc                 K   ro  r   )rQ  r   rU   rU   rY   visit_numeric  r   z!GenericTypeCompiler.visit_numericc                 K   ro  r   re  r   rU   rU   rY   visit_string  r   z GenericTypeCompiler.visit_stringc                 K   ro  r   r{  r   rU   rU   rY   visit_unicode  r   z!GenericTypeCompiler.visit_unicodec                 K   ro  r   rg  r   rU   rU   rY   
visit_text  r   zGenericTypeCompiler.visit_textc                 K   ro  r   r~  r   rU   rU   rY   visit_unicode_text  r   z&GenericTypeCompiler.visit_unicode_textc                 K   ro  r   r{  r   rU   rU   rY   
visit_enum  r   zGenericTypeCompiler.visit_enumc                 K   s   t d| )NzKCan't generate DDL for %r; did you forget to specify a type on this Column?r4  r   rU   rU   rY   rp    s
   zGenericTypeCompiler.visit_nullc                 K   s   | j || jfi |S r   )r   Ztype_enginer   r   rU   rU   rY   visit_type_decorator  s   z(GenericTypeCompiler.visit_type_decoratorc                 K   s   |j di |S )NrU   )Zget_col_specr   rU   rU   rY   visit_user_defined  r  z&GenericTypeCompiler.visit_user_definedN)-r   r   r   rK  rL  rQ  rS  rT  rU  rV  rX  rY  rZ  r[  r\  r]  r`  rc  rd  re  rf  rg  rh  rl  rm  rn  rp  rq  rr  rs  rt  ru  rv  rw  rx  ry  rz  r|  r}  r  r  r  rp  r  r  rU   rU   rU   rY   rI  	  sV    	rI  c                   @   s   e Zd Zdd Zdd ZdS )StrSQLTypeCompilerc                 C   s   | dr| jS t|)Nvisit_)
startswith_visit_unknownAttributeError)r   r   rU   rU   rY   __getattr__  s   
zStrSQLTypeCompiler.__getattr__c                 K   s   d|j j S )Nz%s)r  r   r   rU   rU   rY   r    r  z!StrSQLTypeCompiler._visit_unknownN)r   r   r   r  r  rU   rU   rU   rY   r    s    r  c                   @   s  e Zd ZdZeZeZeZ	e
dZ					d5ddZdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zd6ddZd6ddZdd Zd7ddZd6ddZd6d d!Zd6d"d#Zed$d%d& Zd'd( Zd8d)d*Z d+d, Z!				d9d-d.Z"d7d/d0Z#ej$d1d2 Z%d3d4 Z&dS ):IdentifierPreparerz@Handle quoting and case-folding of identifiers based on options.N"TFc                 C   sN   || _ || _|p
| j| _|| _| jd | _|| _|| _i | _| j jdv | _	dS )as  Construct a new ``IdentifierPreparer`` object.

        initial_quote
          Character that begins a delimited identifier.

        final_quote
          Character that ends a delimited identifier. Defaults to
          `initial_quote`.

        omit_schema
          Prevent prepending schema name. Useful for databases that do
          not support schemae.
        r   )r`   r_   N)
r   initial_quotefinal_quoteescape_quoteescape_to_quoteomit_schemaquote_case_sensitive_collations_stringsr   rT  )r   r   r  r  r  r  r  rU   rU   rY   r     s   zIdentifierPreparer.__init__c                 C   s,   | j | j }|j| j t||_|S r   )r  __new____dict__r>  r   _schema_getterr=  )r   r   preprU   rU   rY   r     s   z)IdentifierPreparer._with_schema_translatec                 C   s&   | | j| j}| jr| dd}|S )zEscape an identifier.

        Subclasses should override this to provide database-dependent
        escaping behavior.
        rQ  rR  )rU  r  r  rT  r   r   rU   rU   rY   _escape_identifier  s   z%IdentifierPreparer._escape_identifierc                 C   s   | | j| jS )zCanonicalize an escaped identifier.

        Subclasses should override this to provide database-dependent
        unescaping behavior that reverses _escape_identifier.
        )rU  r  r  r  rU   rU   rY   _unescape_identifier  s   z'IdentifierPreparer._unescape_identifierc                 C   s*   |dur| |std||jf |S )zkeyword sequence filter.

        a filter for elements that are intended to represent keyword sequences,
        such as "INITIALLY", "INITIALLY DEFERRED", etc.   no special characters
        should be present.

        .. versionadded:: 1.3

        Nz/Unexpected SQL phrase: %r (matching against %r))rF  r   r'  pattern)r   r   regrU   rU   rY   rA    s   z&IdentifierPreparer.validate_sql_phrasec                 C   s   | j | | | j S )z~Quote an identifier.

        Subclasses should override this to provide database-dependent
        quoting behavior.
        )r  r  r  r  rU   rU   rY   quote_identifier  s   z#IdentifierPreparer.quote_identifierc                 C   s<   |  }|| jv p|d | jv p| jt| p||kS )z5Return True if the given identifier requires quoting.r   )r  reserved_wordsillegal_initial_characterslegal_charactersrF  r   	text_type)r   r   Zlc_valuerU   rU   rY   r)    s   
z#IdentifierPreparer._requires_quotesc                 C   s   | j t| S )zjReturn True if the given identifier requires quoting, but
        not taking case convention into account.)r  rF  r   r  r  rU   rU   rY   r  "  s   z1IdentifierPreparer._requires_quotes_illegal_charsc                 C   s   |dur	t d | |S )a  Conditionally quote a schema name.


        The name is quoted if it is a reserved word, contains quote-necessary
        characters, or is an instance of :class:`.quoted_name` which includes
        ``quote`` set to ``True``.

        Subclasses can override this to provide database-dependent
        quoting behavior for schema names.

        :param schema: string schema name
        :param force: unused

            .. deprecated:: 0.9

                The :paramref:`.IdentifierPreparer.quote_schema.force`
                parameter is deprecated and will be removed in a future
                release.  This flag has no effect on the behavior of the
                :meth:`.IdentifierPreparer.quote` method; please refer to
                :class:`.quoted_name`.

        NzThe IdentifierPreparer.quote_schema.force parameter is deprecated and will be removed in a future release.  This flag has no effect on the behavior of the IdentifierPreparer.quote method; please refer to quoted_name().)r   warn_deprecatedr<  )r   r   forcerU   rU   rY   r>  '  s
   
zIdentifierPreparer.quote_schemac                 C   s|   |dur	t d t|dd}|du r5|| jv r| j| S | |r+| || j|< n|| j|< | j| S |r<| |S |S )a  Conditionally quote an identfier.

        The identifier is quoted if it is a reserved word, contains
        quote-necessary characters, or is an instance of
        :class:`.quoted_name` which includes ``quote`` set to ``True``.

        Subclasses can override this to provide database-dependent
        quoting behavior for identifier names.

        :param ident: string identifier
        :param force: unused

            .. deprecated:: 0.9

                The :paramref:`.IdentifierPreparer.quote.force`
                parameter is deprecated and will be removed in a future
                release.  This flag has no effect on the behavior of the
                :meth:`.IdentifierPreparer.quote` method; please refer to
                :class:`.quoted_name`.

        NzThe IdentifierPreparer.quote.force parameter is deprecated and will be removed in a future release.  This flag has no effect on the behavior of the IdentifierPreparer.quote method; please refer to quoted_name().r<  )r   r  r   r  r)  r  )r   r   r  rU   rU   rY   r<  L  s   





zIdentifierPreparer.quotec                 C   s   | j r| |S |S r   )r  r<  )r   Zcollation_namerU   rU   rY   rB  ~  s   
z#IdentifierPreparer.format_collationc                 C   s>   |  |j}| |}| js|r|d ur| |d | }|S r  )r<  r   r=  r  r>  )r   r  r  r   r@  rU   rU   rY   r    s   
z"IdentifierPreparer.format_sequencec                 C      |  |p|jS r   r<  r   )r   r   r   rU   rU   rY   r0    r  zIdentifierPreparer.format_labelc                 C   r  r   r  )r   r9  r   rU   rU   rY   r!    r  zIdentifierPreparer.format_aliasc                 C   s"   |p|j }| |r| |}|S r   )r   r)  r  )r   Z	savepointr   r   rU   rU   rY   r    s   


z#IdentifierPreparer.format_savepointzsqlalchemy.sql.namingc                 C   s   t |jtjr|||j}|d u rt |jtjrd S |j}n|j}t |tjrT|jdkr6| j	j
p4| j	j}n| j	j}t||krS|d|d  d t|dd   }n| j	| | |S )NrI  r      r   )r+  r   r   Z_defer_nameZ_constraint_name_for_tablerK   Z_defer_none_namer,  r   r   Zmax_index_name_lengthr   r  r   Zmd5_hexZvalidate_identifierr<  )r   Znamingr   r   Zmax_rU   rU   rY   r%    s*   
&
z$IdentifierPreparer.format_constraintc                 C   
   |  |S r   )r%  r
  rU   rU   rY   r    r   zIdentifierPreparer.format_indexc                 C   sF   |du r|j }| |}| |}| js!|r!|r!| |d | }|S )z'Prepare a quoted table and schema name.Nr8  )r   r<  r=  r  r>  )r   rK   r  r   r  r@  rU   rU   rY   r    s   

zIdentifierPreparer.format_tablec                 C   r  )zPrepare a quoted schema name.)r<  r  rU   rU   rY   r    r   z IdentifierPreparer.format_schemac                 C   sj   |du r|j }t|dds$|r| j|j||dd | | S | |S |r3| j|j||dd | S |S )zPrepare a quoted column name.Nr:  F)r  r   r8  )r   r   r  rK   r<  )r   r   r  r   Z
table_namer  rU   rU   rY   r    s.   

z IdentifierPreparer.format_columnc                 C   s@   |  |}| js|r|r| || j|ddfS | j|ddfS )z(Format table name and schema as a tuple.Fr  )r=  r  r>  r  )r   rK   r  r@  rU   rU   rY   r    s   
z#IdentifierPreparer.format_table_seqc                 C   s@   dd | j | j| | jfD \}}}td|||d }|S )Nc                 S   s   g | ]}t |qS rU   )r  r  ry  rU   rU   rY   r        z5IdentifierPreparer._r_identifiers.<locals>.<listcomp>zM(?:(?:%(initial)s((?:%(escaped)s|[^%(final)s])+)%(final)s|([^\.]+))(?=\.|$))+)initialfinalescaped)r  r  r  r  r   )r   r  r  Zescaped_finalrrU   rU   rY   _r_identifiers
  s   

z!IdentifierPreparer._r_identifiersc                    s(    j } fdddd ||D D S )z:Unpack 'schema.table.column'-like strings into components.c                    s   g | ]}  |qS rU   )r  )rW   r  r   rU   rY   r     r  z;IdentifierPreparer.unformat_identifiers.<locals>.<listcomp>c                 S   s   g | ]\}}|p	|qS rU   rU   )rW   abrU   rU   rY   r  "  r^  )r  findall)r   identifiersr  rU   r   rY   unformat_identifiers  s   
z'IdentifierPreparer.unformat_identifiers)r  Nr  TFr   )T)TN)FNNF)'r   r   r   r   RESERVED_WORDSr  LEGAL_CHARACTERSr  ILLEGAL_INITIAL_CHARACTERSr  r   r  r=  r   r   r  r  rA  r  r)  r  r>  r<  rB  r  r0  r!  r  r   r  r%  r  r  r  r  r  r  r  r  rU   rU   rU   rY   r    sP    

$	


%2



	



&
r  )lr   r  r  r  r   r   r   r   r   r   r   r	   r
   r   r   rI   r  r   Ir  ZLEGAL_CHARACTERS_PLUS_SPACErangerN   r  rB  rC  rE  UNICODEr`  r_  r   and_or_addmulr  divmodtruedivnegltlenegtgeeqZis_distinct_fromZisnot_distinct_fromZ	concat_opr  Znotmatch_opZin_opZnotin_opZcomma_opr  r/  is_Zisnotr   existsZdistinct_opinvZany_opZall_opZdesc_opZasc_opZnullsfirst_opZnullslast_opr.  rh   r   r   r    r!   r7   r8   ri   rj   rH   rP   ZcubeZrollupZgrouping_setsr  r  r$  r{   Z	UNION_ALLr|   Z
EXCEPT_ALLr}   ZINTERSECT_ALLr  objectr~   with_metaclassZEnsureKWArgTyper   Z	Visitabler   r	  r   r   r  r  rI  r  r  rU   rU   rU   rY   <module>   sf  c		
 !"#%&,
                   LB   Q 