o
    i                    @   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)^allanalyseanalyzeandanyarrayasasc
asymmetricauthorizationbetweenbinarybothcasecastcheckcollatecolumn
constraintcreatecrosscurrent_datecurrent_rolecurrent_timecurrent_timestampcurrent_userdefault
deferrabledescdistinctdoelseendexceptfalseforforeignfreezefromfullgrantgrouphavingilikein	initiallyinner	intersectintoisisnulljoinleadingleftlikelimit	localtimelocaltimestampnaturalnewnotnotnullnulloffoffsetoldononlyororderouteroverlapsplacingprimary
referencesrightselectsession_usersetsimilarsome	symmetrictablethento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xrl   rl   R/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/sqlalchemy/sql/compiler.py	<setcomp>       rq   
   $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)pyformat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coalesceCURRENT_DATECURRENT_TIMECURRENT_TIMESTAMPCURRENT_USER	LOCALTIMELOCALTIMESTAMPrandomsysdateSESSION_USERUSERCUBEROLLUPzGROUPING SETSmonthdayyearsecondhourdoyminutequarterdowweekepochmillisecondsmicrosecondstimezone_hourtimezone_minute)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   UNIONz	UNION ALLEXCEPTz
EXCEPT ALL	INTERSECTzINTERSECT ALLc                   @   s   e 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   sj   || _ || _| j j| _|r| j|| _|dur3|| _|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bindidentifier_preparerpreparer_with_schema_translate	statementsupports_executioncan_execute_execution_optionsexecution_optionsprocessstring)selfr   r   r   schema_translate_mapcompile_kwargsrl   rl   rp   __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 )zDProduce the internal string representation of this element.
        Nrl   r   rl   rl   rp   compileA  s   
zCompiled.compilec                 C   s    | j r
|| ||S t| jN)r   _execute_compiledr   ObjectNotExecutableErrorr   )r   
connectionmultiparamsparamsrl   rl   rp   _execute_on_connectionM  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   rl   rl   rp   sql_compilerS     zCompiled.sql_compilerc                 K      |j | fi |S r   _compiler_dispatch)r   objkwargsrl   rl   rp   r   ]     zCompiled.processc                 C   s
   | j pdS )z3Return the string text of the generated SQL or DDL. )r   r   rl   rl   rp   __str__`     
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   rl   rl   rp   construct_paramse  r   zCompiled.construct_paramsc                 C   s   |   S )z0Return the bind params for this compiled object.r   r   rl   rl   rp   r   o  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.2aficode)r   r   UnboundExecutionErrorr   )r   r   r   erl   rl   rp   executet  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   rl   rl   rp   r     s   zCompiled.scalarr   )__name__
__module____qualname____doc___cached_metadatar   immutabledictr   r   
deprecatedr   r   propertyr   r   r   r   r   r   r   rl   rl   rl   rp   r      s0    	
/

	


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   rl   rl   rp   r        
zTypeCompiler.__init__c                 K   r   r   r   r   type_kwrl   rl   rp   r     r   zTypeCompiler.processN)r   r   r   r   ensure_kwargr   r   rl   rl   rl   rp   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namerl   c                 C   s   || _ || _|f| | _d S r   )r   r   
_alt_names)r   colr   	alt_namesrl   rl   rp   r     s   z_CompileLabel.__init__c                 C      | j jS r   )r   	proxy_setr   rl   rl   rp   r        z_CompileLabel.proxy_setc                 C   r   r   )r   typer   rl   rl   rp   r     r   z_CompileLabel.typec                 K      | S r   rl   )r   r   rl   rl   rp   
self_group     z_CompileLabel.self_groupN)rl   )r   r   r   r   __visit_name__	__slots__r   r   r   r   r   rl   rl   rl   rp   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getrm   )r   keyidentderivedanonymous_countervaluerl   rl   rp   __missing__  s   zprefix_anon_map.__missing__N)r   r   r   r   r   rl   rl   rl   rp   r     s    r   c                   @   sL  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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*Z/d+d, Z0d-d. Z1d/d0 Z2d1d2 Z3d3d4 Z4d5d6 Z5d7d8 Z6	dd9d:Z7d;d< Z8d=d> Z9d?d@ Z:dAdB Z;dCdD Z<dEdF Z=dGdH Z>dIdJ Z?dKdL Z@dMdN ZAdOdP ZBdQdR ZCddSdTZDdUdV ZEdWdX ZFdYdZ ZG	[d	d\d]ZHd^d_ ZId`da ZJdbdc ZKddde ZLdfdg ZMdhdi ZNdjdk ZOdldm ZPdndo ZQ	ddpdqZRdrds ZSdtdu ZTdvdw ZUdxdy ZVdzd{ ZW	dd|d}ZXd~d ZYdd ZZej!dd Z[dd Z\dd Z]dd Z^dd Z_dd Z`dd Zadd Zbdd Zcdd Zddd Zedd Zfdd Zg			d
ddZhdd Zidd Zjdd Zkdd Zldd Zm	dddZn				dddZo				dddZpdd ZqdddZrdd Zsdd Zt			dddZudd Zvdd Zwdd Zxdd Zydd ZzddÄ 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 Zdd Zd d ZdS (  SQLCompilerz~Default implementation of :class:`.Compiled`.

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

    FNTrl   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.

        inlineFry   N)column_keysgetattrr   bindsr   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   rl   rl   rp   r     s:   

zSQLCompiler.__init__c                 C   s   t | j| j S r   )listinsert_prefetchupdate_prefetchr   rl   rl   rp   prefetchX     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   rl   rl   rp   _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'FTneed_result_map_for_nestedN)r  _ordered_columnsr  pop)r   result_columnsordered_columnsentryrl   rl   rp   _nested_resultj  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   )rm   r   nextmposcountrl   rp   <lambda>  s    z4SQLCompiler._apply_numbered_params.<locals>.<lambda>)	itertoolscountresubr   r   rl   r*  rp   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   rl   )rn   r   r   rl   rl   rp   	<genexpr>  s    z/SQLCompiler._bind_processors.<locals>.<genexpr>c                 3   s(    | ]} j | |j jfV  qd S r   )r  r   _cached_bind_processorr   )rn   	bindparamr   rl   rp   r1    s    
)dictr  r   rl   r   rp   _bind_processors  s
   
zSQLCompiler._bind_processorsc                 C   s   t | jdkS Nr   )lenr  r   rl   rl   rp   is_subquery     zSQLCompiler.is_subqueryc                 C   r   r   rl   r   rl   rl   rp   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 %dcd3xr   z)A value is required for bind parameter %r)r  r   requiredr   InvalidRequestErrorcallableeffective_valuer   )r   r   _group_number_checkpdr3  r   rl   rl   rp   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)rA  r   r   rl   rl   rp   r     s   zSQLCompiler.paramszsqlalchemy.engine.resultc                 C   s   |j | jS )z(utility method used for unit tests only.)ResultMetaData_create_result_mapr  )r   resultrl   rl   rp   rD    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   rl   r   rl   rl   rp   default_from  s   zSQLCompiler.default_fromc                 K   s   d|j j| fi | d S )N()r   r   )r   groupingasfromr   rl   rl   rp   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   supports_simple_order_by_label_label_resolve_dictr   _order_by_label_elementr   shares_lineager   )
r   r   rN  r   r   	with_cols
only_froms	only_colsresolve_dictorder_by_elemrl   rl   rp   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.)errrM  rN  )
r  r   _text_clauserP  r   KeyErrorr   _no_text_coercionr   CompileError)
r   r   rN  r   r   rS  rT  rU  r   kerl   rl   rp   visit_textual_label_reference  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)rN  within_label_clauserN  F)
isinstancer   r   _truncated_label_truncated_identifierr   r   r   r   	OPERATORSr   as_r   format_label)
r   r   add_to_result_mapra  rN  rM  r   render_label_with_asrender_label_only	labelnamerl   rl   rp   visit_label*  sJ   
zSQLCompiler.visit_labelc                 C   
   t d)Nz:Cannot compile Column object until its 'name' is assigned.r   r]  r   r   rl   rl   rp   _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   rp  
is_literalrb  r   rc  rd  r   r   escape_literal_columnr   quoter`   named_with_columnschema_for_objectquote_schema)r   r   rh  include_tabler   r   	orig_namert  r`   effective_schemaschema_prefix	tablenamerl   rl   rp   visit_column`  s2   

zSQLCompiler.visit_columnc                 K   s   | j |jS r   )r   format_collation	collation)r   r   r   rl   rl   rp   visit_collation  r9  zSQLCompiler.visit_collationc                 K      |j S r   r   )r   
fromclauser   rl   rl   rp   visit_fromclause     zSQLCompiler.visit_fromclausec                 K   r  r   r  )r   indexr   rl   rl   rp   visit_index  r  zSQLCompiler.visit_indexc                 K   s    ||d< | j jj|jfi |S )Ntype_expression)r   type_compilerr   r   )r   
typeclauser   rl   rl   rp   visit_typeclause  s   zSQLCompiler.visit_typeclausec                 C      | j jr
|dd}|S N%%%r   _double_percentsreplacer   textrl   rl   rp   post_process_text     zSQLCompiler.post_process_textc                 C   r  r  r  r  rl   rl   rp   ru    r  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 r6  )r7   _bindparamsr   bindparam_string)r)  r   r   r   
textclauserl   rp   do_bindparam  s   

z2SQLCompiler.visit_textclause.<locals>.do_bindparamTc                 S   s
   |  dS r6  )r7   r(  rl   rl   rp   r,    s   
 z.SQLCompiler.visit_textclause.<locals>.<lambda>)r  isplaintextBIND_PARAMS_ESCr0  BIND_PARAMSr  r  )r   r  r   r  rl   r  rp   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rN  rh  (%s))
r  _default_stack_entryr   r  r!  _textual_ordered_columnscolumn_argsr   _add_to_result_mapr   )r   tafcompound_indexrK  parensr   toplevelr%  populate_result_mapcr  rl   rl   rp   visit_text_as_from  s,   

	
zSQLCompiler.visit_text_as_fromc                 K   r   )NNULLrl   r   exprr   rl   rl   rp   
visit_null  r   zSQLCompiler.visit_nullc                 K      | j jrdS dS )Nrd   1r   supports_native_booleanr  rl   rl   rp   
visit_true     zSQLCompiler.visit_truec                 K   r  )Nr0   0r  r  rl   rl   rp   visit_false  r  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   rl   rn   srl   rl   rp   r1    s    
z/SQLCompiler.visit_clauselist.<locals>.<genexpr>c                 3   s"    | ]}|j fi  V  qd S r   r   rn   r  r   r   rl   rp   r1    s    
zVALUES )operatorre  rA   clauses_tuple_valuesr   tuple_in_values)r   
clauselistr   sepr  rl   r  rp   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   whenselse_)r   clauser   ro   condrE  rl   rl   rp   
visit_case  s*   

zSQLCompiler.visit_casec                 K      |j j| fi |S r   )typed_expressionr   )r   type_coercer   rl   rl   rp   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   r  )r   r   r   rl   rl   rp   
visit_cast	     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   RANGE_UNBOUNDEDRANGE_CURRENTr   literalabs)r   range_r   rl   rl   rp   _format_frame_clause  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)r7  r   )rn   wordr  r   r   rl   rp   
<listcomp>5  s    z*SQLCompiler.visit_over.<locals>.<listcomp>	PARTITIONORDER)r  r  rowsr   r   rA   partition_byorder_by)r   overr   r  rl   r  rp   
visit_over&  s2   

	zSQLCompiler.visit_overc                 K   r  )Nz%s WITHIN GROUP (ORDER BY %s))r   r   r  )r   withingroupr   rl   rl   rp   visit_withingroupB  r  zSQLCompiler.visit_withingroupc                 K   r  )Nz%s FILTER (WHERE %s))funcr   	criterion)r   
funcfilterr   rl   rl   rp   visit_funcfilterH  r  zSQLCompiler.visit_funcfilterc                 K   s.   | j |j|j}d||jj| fi |f S )NzEXTRACT(%s FROM %s))extract_mapr   fieldr  r   )r   extractr   r  rl   rl   rp   visit_extractN  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 )Nrl   zvisit_%s_funcz%(expr)srr  c                    s4   g | ]}j |st tjrj |n|qS rl   )r   _requires_quotes_illegal_charsrb  r   quoted_namerv  )rn   tokr   r   rl   rp   r  k  s    

z.SQLCompiler.visit_function.<locals>.<listcomp>r  )r   r   r   lower	FUNCTIONSr   	__class__	_has_argsr   r  rb  r   r  rv  rA   packagenamesfunction_argspec)r   r  rh  r   disprl   r  rp   visit_functionU  s6   

	zSQLCompiler.visit_functionc                 K   s   |  |jS r   )visit_sequencesequence)r   
next_valuer   rl   rl   rp   visit_next_value_funcw     z!SQLCompiler.visit_next_value_funcc                 K      t d| jj )Nz2Dialect '%s' does not support sequence increments.r   r   r   )r   r  r   rl   rl   rp   r  z  
   zSQLCompiler.visit_sequencec                 K   r  r   )clause_exprr   )r   r  r   rl   rl   rp   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   r  Fcorrelate_fromsasfrom_froms)r  r  r   r  r   c                 3   s.    | ]\}}|j f d |dV  qdS )F)rK  r  r  Nr   )rn   ir  rK  r   r   rl   rp   r1    s    
z4SQLCompiler.visit_compound_select.<locals>.<genexpr>rK  r   rG  rH  rl   )r  r  r   appendcompound_keywordskeywordrA   	enumerateselectsgroup_by_clauser4  order_by_clause_limit_clause_offset_clauselimit_clauser
  _render_cte_clauser"  )r   csrK  r  r  r   r  r%  need_result_mapr
  r  rl   r  rp   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_
qualifier1
qualifier2attrnamerl   rl   rp   _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_operatorre   _generate_generic_unary_modifier)r   r  r   r  rl   rl   rp   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_is_implicitly_booleanr   r  r   r   r   r   r  r   rl   rl   rp   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"  rl   rl   rp   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   rl   rl   rp   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   rl   rl   rp   _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   _use_static_in_warn_on_empty_inr,  r   rC   r)  rl   rl   rp   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)  rl   rl   rp   visit_empty_notin_op_binary  r1  z'SQLCompiler.visit_empty_notin_op_binaryc                 C   r   )Nz3Dialect '%s' does not support empty set expression.r  )r   element_typesrl   rl   rp   visit_empty_set_expr  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   )replace_context)ansi_bind_rulesrb  rC   r   BindParameterrY   r  r  re  r[  r   raise_r   UnsupportedCompilationError_generate_generic_binary)	r   r   r&  eager_groupingr   r  r  opstringrY  rl   rl   rp   r'    s*   

zSQLCompiler.visit_binaryc                 K   s   | j |jfi |S r   )r   sql_functionr"  rl   rl   rp   &visit_function_as_comparison_op_binary.  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 %% r{   )r   r  r   rC   rY   r)  rl   rl   rp   visit_mod_binary1  s   zSQLCompiler.visit_mod_binaryc                 K   s(   |j |d< | j|d|j d fi |S )Nr<  r   )r<  r;  r=  r"  rl   rl   rp   visit_custom_op_binary?  s   
z"SQLCompiler.visit_custom_op_binaryc                 K   s   | j ||jd fi |S Nr   )r  r=  r"  rl   rl   rp   visit_custom_op_unary_operatorE  
   
z*SQLCompiler.visit_custom_op_unary_operatorc                 K   s   | j |d|j fi |S rB  )r  r=  r"  rl   rl   rp   visit_custom_op_unary_modifierJ  rD  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<  r  )r   rC   r   rY   )r   r   r=  r<  r   rF  r  rl   rl   rp   r;  O  s.   
z$SQLCompiler._generate_generic_binaryc                 K   s   ||j j| fi | S r   rI  r   r  r=  r   rl   rl   rp   r  d     z,SQLCompiler._generate_generic_unary_operatorc                 K   s   |j j| fi || S r   rI  rG  rl   rl   rp   r  g  rH  z,SQLCompiler._generate_generic_unary_modifierc                 C   s   t jdtjdS )Nz'%')r   )r   literal_columnr	   
STRINGTYPEr   rl   rl   rp   _like_percent_literalj  r  z!SQLCompiler._like_percent_literalc                 K   6   |  }| j}||j||_| j||fi |S r   _clonerK  __add__rY   visit_like_op_binaryr   r   r  r   percentrl   rl   rp   visit_contains_op_binaryn     z$SQLCompiler.visit_contains_op_binaryc                 K   rL  r   rN  rK  rO  rY   visit_notlike_op_binaryrQ  rl   rl   rp   visit_notcontains_op_binaryt  rT  z'SQLCompiler.visit_notcontains_op_binaryc                 K   0   |  }| j}||j|_| j||fi |S r   )rN  rK  __radd__rY   rP  rQ  rl   rl   rp   visit_startswith_op_binaryz     z&SQLCompiler.visit_startswith_op_binaryc                 K   rX  r   )rN  rK  rY  rY   rV  rQ  rl   rl   rp   visit_notstartswith_op_binary  r[  z)SQLCompiler.visit_notstartswith_op_binaryc                 K   rX  r   rM  rQ  rl   rl   rp   visit_endswith_op_binary  r[  z$SQLCompiler.visit_endswith_op_binaryc                 K   rX  r   rU  rQ  rl   rl   rp   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   rC   r   rY   render_literal_valuer	   rJ  r   r   r  r   r`  rl   rl   rp   rP    s   z SQLCompiler.visit_like_op_binaryc                 K   r_  )Nr`  z%s NOT LIKE %sra  r   rb  re  rl   rl   rp   rV       z#SQLCompiler.visit_notlike_op_binaryc                 K   r_  )Nr`  zlower(%s) LIKE lower(%s)ra  r   rb  re  rl   rl   rp   visit_ilike_op_binary  rf  z!SQLCompiler.visit_ilike_op_binaryc                 K   r_  )Nr`  zlower(%s) NOT LIKE lower(%s)ra  r   rb  re  rl   rl   rp   visit_notilike_op_binary  rf  z$SQLCompiler.visit_notilike_op_binaryc                 K   *   |j dd}| j||rdndfi |S )Nr_   Fz BETWEEN SYMMETRIC z	 BETWEEN rc  r   r;  r   r   r  r   r_   rl   rl   rp   visit_between_op_binary  s   z#SQLCompiler.visit_between_op_binaryc                 K   ri  )Nr_   Fz NOT BETWEEN SYMMETRIC z NOT BETWEEN rj  rk  rl   rl   rp   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_expressionrN  r5  z@Bind parameter '%s' without a renderable value not allowed here.rN  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   _has_bind_expressionbind_expressionr   r7  r   r>  r   r]  r   render_literal_bindparam_truncate_bindparamr   rf   r   intersection_is_crudr  ro  )
r   r3  rN  r5  rn  r   implrr  r   existingrl   rl   rp   visit_bindparam  sp   	





zSQLCompiler.visit_bindparamc                 K   s   |j }| ||jS r   )r?  rd  r   )r   r3  r   r   rl   rl   rp   rs    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)_cached_literal_processorr   r   )r   r   r   	processorrl   rl   rp   rd    s   z SQLCompiler.render_literal_valuec                 C   s@   || j v r
| j | S |j}t|tjr| d|}|| j |< |S )Nr3  )r  r   rb  r   rc  rd  )r   r3  	bind_namerl   rl   rp   rt  "  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  	apply_mapr  r7  r  r   maxhex)r   ident_classr   anonnamecounter	truncnamerl   rl   rp   rd  /  s   z!SQLCompiler._truncated_identifierc                 C   s
   || j  S r   )r  r   r   rl   rl   rp   
_anonymizeB  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_namesro  r   rl   rl   rp   r  E  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_cters  TFz5Multiple, unrelated CTEs found with the same name: %r
autocommitr   c                 S      g | ]}|d ur|qS r   rl   r  rl   rl   rp   r    s
    z)SQLCompiler.visit_cte.<locals>.<listcomp>r  r}   c                 3   s    | ]	} j |V  qd S r   )r   format_column)rn   r   r   rl   rp   r1    s
    

z(SQLCompiler.visit_cte.<locals>.<genexpr>r  z	 AS %s
%srK  r   )'r  rb  r   r   rc  rd  r  	_restatesr
  r   r]  
_cte_aliasr   r   r   re   	visit_cte	recursiver  r   format_aliasoriginalr   SelectCompoundSelectr  r   unique_listinner_columnsrA   r  r  _generate_prefixes	_prefixesr   	_suffixes_requires_quotesrv  get_render_as_alias_suffix)r   cterK  ashint	fromhintsr  r   cte_name
is_new_cteembedded_in_current_named_cteexisting_ctepre_alias_ctecte_pre_alias_namer  
col_source
recur_colsrl   r   rp   r  S  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 )Nrs  rK  T)rb  r   r   rc  rd  r   r  r  r   r  format_from_hint_text)	r   rs  rK  r  iscrudr  r   
alias_nameretrl   rl   rp   visit_alias  s0   	zSQLCompiler.visit_aliasc                 K   s   d|d< d| j |fi | S )NTlateralz
LATERAL %s)r  )r   r  r   rl   rl   rp   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 %srK  Tz REPEATABLE (%s))r  _get_methodr   seed)r   tablesamplerK  r   r  rl   rl   rp   visit_tablesample  s   
zSQLCompiler.visit_tablesamplec                 C   s   d| S )Nr~   rl   )r   alias_name_textrl   rl   rp   r       z&SQLCompiler.get_render_as_alias_suffixc                 C   s   | j ||||f d S r   )r  r  )r   keynamer   objectsr   rl   rl   rp   r    rH  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   )r  )r  r   r  r   r   r   rl   rp   rh    s   z;SQLCompiler._label_select_column.<locals>.add_to_result_mapN)r   r   r  )r   rp  r   _has_column_expressioncolumn_expressionr  rb  r   Labelr   r   r   
_key_labelColumnClausert  r`   r   r  _as_truncatedr   
TextClauseUnaryExpressionwraps_column_expressionhasattrr   Function
anon_labelupdater   )r   rZ   r   r  rK  column_clause_argsr   rN  need_column_expressionsrw  col_exprrh  result_exprrl   r  rp   _label_select_column  s~   








z SQLCompiler._label_select_columnc                 C   s    |  ||}|r|d| 7 }|S rB  )get_from_hint_text)r   sqltextr`   hintr  hinttextrl   rl   rp   r  c  s   z!SQLCompiler.format_from_hint_textc                 C      d S r   rl   )r   byfromsrl   rl   rp   get_select_hint_texti  r   z SQLCompiler.get_select_hint_textc                 C   r  r   rl   r   r`   r  rl   rl   rp   r  l  r   zSQLCompiler.get_from_hint_textc                 C   r  r   rl   r  rl   rl   rp   get_crud_hint_texto  r   zSQLCompiler.get_crud_hint_textc                 C   s
   d |S rB  rA   )r   
hint_textsrl   rl   rp   get_statement_hint_textr  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_labelsselect_containertransform_cluecloneinside_selectrl   )rN  is_selectable_is_joinrb  rY   r   FromGrouping_reset_exportedrC   r  r   rs  r  r   r  r   _labelr4  zipr  itemsr  onclause_is_from_container_copy_internals
_is_selectr   r  )
r   r   newelemrY   selectable_r  translate_dictkvbarrier_selectclonedcolumn_translatevisitrl   rp   r    sj   


z=SQLCompiler._transform_select_for_nested_joins.<locals>.visitrl   )r   rZ   rl   r  rp   "_transform_select_for_nested_joinsu  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  rl   rl   rp   r1        

zESQLCompiler._transform_result_map_for_nested_joins.<locals>.<genexpr>c                 3   s    | ]
} |j  |fV  qd S r   r  r  )	inner_colrl   rp   r1        c                    2   g | ]\}}}}||t  fd d|D |fqS )c                    s   g | ]}  ||qS rl   r   )rn   r   drl   rp   r        zQSQLCompiler._transform_result_map_for_nested_joins.<locals>.<listcomp>.<listcomp>tuple)rn   r   r   objstypr  rl   rp   r        
zFSQLCompiler._transform_result_map_for_nested_joins.<locals>.<listcomp>)r4  r  r  )r   rZ   transformed_selectrl   )r  r  rp   &_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  rl   explicit_correlate_fromsimplicit_correlate_froms)r  r  _get_display_froms
difference)	r   rZ   rK  r  r  r%  r  r  fromsrl   rl   rp   _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)rK  r  r  r  nested_join_translationr  r  Fr   r   rh  )ra  rN  zSELECT r   c                 S   r  r   rl   r  rl   rl   rp   r  M  s
    z,SQLCompiler.visit_select.<locals>.<listcomp>c                    s(   g | ]\}}j | |d qS ))r   r  r  )rn   r   r   )rK  r  r  r  rZ   r   rl   rp   r  O  s    
c                 S      g | ]\}}|qS rl   rl   rn   r   r   rl   rl   rp   r  d  rr   c                 S   r	  rl   rl   r
  rl   rl   rp   r  e  s    c                    r  )c                 3   s    | ]	}  ||V  qd S r   r  )rn   o	translaterl   rp   r1  m  s    z6SQLCompiler.visit_select.<locals>.<listcomp>.<genexpr>r  )rn   r   r   r   r   r  rl   rp   r  l  r  c                    s$   g | ]\}}|d  j jfv r|qS *r   r   )rn   dialect_namehtr   rl   rp   r  v  s
    rG  rH  )r  r  r   supports_right_nested_joinsr  visit_selectr  r   r  _setup_select_stackcopyr  _hints_setup_select_hintsr  r  get_select_precolumns_columns_plus_namesr4  r  r  _compose_select_body_statement_hintsr  r
  r  r  r"  )r   rZ   rK  r  r  r  r  select_wraps_forr  r   needs_nested_translationr  r  r  r%  r  	hint_textbyfromr  per_dialectrl   )rK  r  r  r  rZ   r   r  rp   r    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 )r  r   T)r  r   r   r   )rn   from_r   r  r   rl   rp   r    s    
z3SQLCompiler._setup_select_hints.<locals>.<listcomp>)r4  r  r  r  )r   rZ   r   r  rl   r   rp   r    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  rl   r   )r  r  r   )r  r  r\   r   _from_objectsre   r  r  )r   rZ   r%  rK  r  r  r  r  new_correlate_fromsall_correlate_froms	new_entryrl   rl   rp   r    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 )Nr}   z 
FROM c                    s$   g | ]}|j fd  dqS )TrK  r  r   rn   fr   r   r   rl   rp   r    s    z4SQLCompiler._compose_select_body.<locals>.<listcomp>c                    s"   g | ]}|j fd di qS )rK  Tr   r)  r  rl   rp   r    s    z 
WHERE z	 
HAVING )rA   r  rF  _whereclauser   _group_by_clauser  r  _having_order_by_clauser  r  r  r  _for_update_argfor_update_clause)r   r  rZ   r  r  r   r   trl   r+  rp   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"  )rn   prefixr  r  rl   rp   r1    s    z1SQLCompiler._generate_prefixes.<locals>.<genexpr>r  )r   stmtprefixesr   r  rl   r  rp   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 rl   )r  )rn   r  r   rl   rp   r    s    z2SQLCompiler._render_cte_clause.<locals>.<listcomp>r   , 
c                 S   s   g | ]}|qS rl   rl   )rn   txtrl   rl   rp   r   	  s    z
 )r  sumr
  r  get_cte_preambler  rA   values)r   cte_textrl   r   rp   r    s   zSQLCompiler._render_cte_clausec                 C   s   |rdS dS )NzWITH RECURSIVEWITHrl   )r   r  rl   rl   rp   r9  	  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.

        r   r   )	_distinctr   rZ   r   rl   rl   rp   r  
	  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   rZ   r   group_byrl   rl   rp   r  	     zSQLCompiler.group_by_clausec                 K   r?  )z5allow dialects to customize how ORDER BY is rendered.z
 ORDER BY r   )r/  r   )r   rZ   r   r  rl   rl   rp   r  	  rA  zSQLCompiler.order_by_clausec                 K   r   )Nz FOR UPDATErl   r>  rl   rl   rp   r1  #	  r   zSQLCompiler.for_update_clausec                 C   rm  )Nz@RETURNING is not supported by this dialect's statement compiler.rn  )r   r4  returning_colsrl   rl   rp   returning_clause&	  rq  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   rZ   r   r  rl   rl   rp   r  ,	  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 )Nrr  r   )r   rx  ry  rv  r   r  )
r   r`   rK  r  r  r  
use_schemar   r|  r  rl   rl   rp   visit_table6	  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 rK  Tz ON )r5   isouterrC   r   rY   r  )r   rA   rK  r   	join_typerl   rl   rp   
visit_joinS	  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 r  r  )rn   r`   r   r  r   rl   rp   r  d	  s
    
z1SQLCompiler._setup_crud_hints.<locals>.<listcomp>T)r4  r  r  r`   r  )r   r4  
table_textdialect_hintsrl   r   rp   _setup_crud_hintsb	  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)r}   c                    s   g | ]	}  |d  qS )r   )r  r  r   rl   rp   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 )r  r}   c                 s   s    | ]}|d  V  qdS )r   Nrl   r  rl   rl   rp   r1  	  s    z5SQLCompiler.visit_insert.<locals>.<genexpr>.<genexpr>Nr  )rn   crud_param_setrl   rl   rp   r1  	  
    
z+SQLCompiler.visit_insert.<locals>.<genexpr>c                 S   s   g | ]}|d  qS )r   rl   r  rl   rl   rp   r  	  rr   z VALUES (%s)r  rG  rH  )#r  r  r\   r   _setup_crud_paramsISINSERTr   supports_default_valuessupports_empty_insertr   r]  r   _has_multi_parameterssupports_multivalues_insertr   r  r  format_tabler`   r  rK  rA   r  r  rC  returning_precedes_valuesrZ   r   _insert_from_selectr
  cte_follows_insertr  insert_single_values_expr_post_values_clauser"  )r   insert_stmtrK  r   r  crud_paramscrud_params_singlerR  r  rI  r   rC  select_textrZ  post_values_clauserl   rM  rp   visit_insertp	  s   



zSQLCompiler.visit_insertc                 C   r   )z3Provide a hook for MySQL to add LIMIT to the UPDATENrl   )r   update_stmtrl   rl   rp   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.

        TrK  r  r   )r   rb  
from_tableextra_fromsr   rl   rl   rp   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   rb  rd  re  
from_hintsr   rl   rl   rp   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 rl   rl   r)  )
main_fromsrl   rp   r  
  s    z,SQLCompiler.visit_update.<locals>.<listcomp>rL  zUPDATE z SET r}   c                 3   s.    | ]}|d  j  dd |d  V  qdS )r   )rz  =r   Nr   r  )rz  r   rl   rp   r1  0
  s    
z+SQLCompiler.visit_update.<locals>.<genexpr>r    WHERE r  rG  rH  )r  _extra_fromsboolr\   r   r$  r`   re   r  r  r  rf  r   rP  ISUPDATEr  rK  'render_table_with_column_in_update_fromrA   r  r  rW  rC  rj  r,  r   rc  r
  r  r"  )r   rb  rK  r   r  re  is_multitablerender_extra_fromsr  r  rI  r]  rJ  extra_from_textr2  r  rl   )rz  rk  r   rp   visit_update	  s   





zSQLCompiler.visit_updatec                 C   s   t | | jS r   )r   _key_getters_for_crud_columnr   r   rl   rl   rp   rv  b
  s   z(SQLCompiler._key_getters_for_crud_columnc                 K   rg  )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   rh  rl   rl   rp   delete_extra_from_clausef
  s   z$SQLCompiler.delete_extra_from_clausec                 C   s   |j | dddS )NT)rK  r  r   )r   delete_stmtrd  re  rl   rl   rp   delete_table_clausev
     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 )	NrL  zDELETE FROM r   rm  r  rG  rH  )r  r   rP  ISDELETErn  r`   re   r  r  r  ry  r  rK  r  rW  rC  rw  r,  r   r
  r  r"  )r   rx  rK  r   r  re  r  r  rI  rJ  rt  r2  rl   rl   rp   visit_deletey
  sr   


zSQLCompiler.visit_deletec                 C      d| j | S )NzSAVEPOINT %sr   format_savepointr   savepoint_stmtrl   rl   rp   visit_savepoint
  rz  zSQLCompiler.visit_savepointc                 C   r~  )NzROLLBACK TO SAVEPOINT %sr  r  rl   rl   rp   visit_rollback_to_savepoint
     z'SQLCompiler.visit_rollback_to_savepointc                 C   r~  )NzRELEASE SAVEPOINT %sr  r  rl   rl   rp   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  rW  rq  r  r7  r  r!  r  rZ  r  r  r   r   r  r   memoized_instancemethodr  
contextlibcontextmanagerr&  r  memoized_propertyr5  r8  r   r   r   dependenciesrD  rF  rL  rX  r_  rl  rp  r  r  r  r  r  r  ru  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,  r0  r2  r4  r'  r?  r@  rA  rC  rE  r;  r  r  rK  rS  rW  rZ  r\  r]  r^  rP  rV  rg  rh  rl  rm  ry  rs  rd  rt  rd  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   	frozensetr  r  r  r  r  r  r  r  r9  r  r  r  r1  rC  r  rE  rH  rK  ra  rc  rf  rj  ru  rv  rw  ry  r}  r  r  r  rl   rl   rl   rp   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>rl   ro  rl   rl   rp   rp  
  r   z$StrSQLCompiler._fallback_column_namec                 K   s,   d| j |jfi || j |jfi |f S )Nz%s[%s])r   rC   rY   r)  rl   rl   rp   visit_getitem_binary
  r  z#StrSQLCompiler.visit_getitem_binaryc                 K      | j ||fi |S r   r  r)  rl   rl   rp   visit_json_getitem_op_binary
  r  z+StrSQLCompiler.visit_json_getitem_op_binaryc                 K   r  r   r  r)  rl   rl   rp   !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   rl   rl   rp   r  
  rz  zStrSQLCompiler.visit_sequencec                    s&    fddt |D }dd| S )Nc              	      s   g | ]}  d |ddi qS r  r  r  r   rl   rp   r  
  s    z3StrSQLCompiler.returning_clause.<locals>.<listcomp>z
RETURNING r}   )r   _select_iterablesrA   )r   r4  rB  columnsrl   r   rp   rC  
  s   
zStrSQLCompiler.returning_clausec                    s    dd  fdd|D  S )Nr{  r}   c                 3   (    | ]}|j fd  dV  qdS Tr(  Nr   rn   r2  ri  r   r   rl   rp   r1    rO  z4StrSQLCompiler.update_from_clause.<locals>.<genexpr>r  rh  rl   r  rp   rj  
     
z!StrSQLCompiler.update_from_clausec                    s    dd  fdd|D  S )Nr}   c                 3   r  r  r   r  r  rl   rp   r1  
  rO  z:StrSQLCompiler.delete_extra_from_clause.<locals>.<genexpr>r  rh  rl   r  rp   rw    r  z'StrSQLCompiler.delete_extra_from_clausec                 C   s   d| S )Nz[%s]rl   r  rl   rl   rp   r    r  z!StrSQLCompiler.get_from_hint_textN)r   r   r   r   rp  r  r  r  r  rC  rj  rw  r  rl   rl   rl   rp   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 d S r   )r   statement_compilerr   rl   rl   rp   r     r  zDDLCompiler.sql_compilerc                 C   r   r   )r   r  r   rl   rl   rp   r    r   zDDLCompiler.type_compilerNc                 C   r  r   rl   r   rl   rl   rp   r     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  r`   r   fullname)contextrb  targetr   Tabler  r   format_table_seqr7  
setdefaultrV  r   r  r   )r   ddlr   r  r   pathr`   schrl   rl   rp   	visit_ddl  s   zDDLCompiler.visit_ddlc                 C   s   | j |j}d| S )NzCREATE SCHEMA )r   format_schemar   )r   r!   r   rl   rl   rp   visit_create_schema2  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   r  rl   rl   rp   visit_drop_schema6  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 rG  
Ffirst_pkr6  	Tz (in table '%s', column '%s'): %sr   )r#  ) _include_foreign_key_constraintsz
)%s

)r   r   r  rA   rV  create_table_suffixr  r   primary_keyr   r]  r   r9  udescriptionr   argscreate_table_constraintsinclude_foreign_key_constraintspost_create_table)r   r!   r`   r   r  r  	separatorr  create_columnr   	processedceconstrl   rl   rp   visit_create_table=  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   rn   r    r   rl   rp   r1  v  r  z2DDLCompiler.visit_create_column.<locals>.<genexpr>)r   systemget_column_specificationrA   constraints)r   r!   r  r   r  r  rl   r   rp   visit_create_columno  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 rl   )r  r  )	omit_fkcsr`   rl   rp   r    s
    z8DDLCompiler.create_table_constraints.<locals>.<listcomp>z, 
	c                 s   s    | ]	}|d ur|V  qd S r   rl   )rn   prl   rl   rp   r1    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 )N	use_alterF)_create_ruler   supports_alterr   r   r  r   rl   rp   r1    s    

)r  r  foreign_key_constraintsr  r\   extend_sorted_constraintsrA   )r   r`   r  r  all_fkcsrl   )r  r   r`   rp   r  ~  s"   

z$DDLCompiler.create_table_constraintsc                 C      d| j |j S )Nz
DROP TABLE r   rV  r   r   r  rl   rl   rp   visit_drop_table  r   zDDLCompiler.visit_drop_tablec                 C   r  )Nz
DROP VIEW r  r  rl   rl   rp   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.)r`   r   r]  r   r   r  rl   rl   rp   _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rD  r}   c                 3   s"    | ]} j j|d ddV  qdS )FTrz  r5  N)r   r   )rn   r  r   rl   rp   r1    s    
z1DDLCompiler.visit_create_index.<locals>.<genexpr>)r   r  r   rf   r   r   r]  _prepared_index_namerV  r`   rA   expressions)r   r!   r  include_table_schemar  r   r  rl   r   rp   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  r  rl   rl   rp   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 Nrr  )r`   r   rx  ry  format_index)r   r  r  r|  schema_name
index_namerl   rl   rp   r    s   
z DDLCompiler._prepared_index_namec                 C   s    d| j |jj| |jf S )NzALTER TABLE %s ADD %s)r   rV  r   r`   r   r   r!   rl   rl   rp   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   rV  r   r   rd  commentr	   Stringr  rl   rl   rp   visit_set_table_comment  s   z#DDLCompiler.visit_set_table_commentc                 C      d| j |j S )NzCOMMENT ON TABLE %s IS NULLr  r  rl   rl   rp   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_tablerD  )r   r  r   r   rd  r  r	   r  r  rl   rl   rp   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  rl   rl   rp   visit_drop_column_comment  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startminvaluemaxvalue
nominvalue
nomaxvaluecacherS   cycle)r   r!   r  rl   rl   rp   visit_create_sequence  s,   z!DDLCompiler.visit_create_sequencec                 C   r  )NzDROP SEQUENCE %s)r   r  r   r  rl   rl   rp   visit_drop_sequence#  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]  rV  r`   r  )r   r  r    formatted_namerl   rl   rp   visit_drop_constraint&  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   )r  z	 DEFAULT z	 NOT NULL)	r   r  r   r  r   r   get_column_default_stringcomputednullable)r   r   r   colspecr(   rl   rl   rp   r  8  s    


z$DDLCompiler.get_column_specificationc                 C   r   Nr   rl   r   r`   rl   rl   rp   r  K  r   zDDLCompiler.create_table_suffixc                 C   r   r  rl   r  rl   rl   rp   r  N  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)r5  )rb  server_defaultr   DefaultClauseargr   string_typesr   rd  r	   rJ  r   ro  rl   rl   rp   r  Q  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   r  define_constraint_deferrabilityr   r    r  r  rl   rl   rp   visit_check_constraint^     


z"DDLCompiler.visit_check_constraintc                 C   r  r	  r  r  rl   rl   rp   visit_column_check_constraintj  r  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 r  r}   c                 3       | ]
} j |jV  qd S r   r   rv  r   r  r   rl   rp   r1    s
    
z;DDLCompiler.visit_primary_key_constraint.<locals>.<genexpr>)	r7  r   r   r  rA   _implicit_generatedcolumns_autoinc_firstr  r  r  rl   r   rp   visit_primary_key_constraintv  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)r}   c                 3       | ]
}  |jjV  qd S r   )rv  parentr   r)  rM  rl   rp   r1        
z;DDLCompiler.visit_foreign_key_constraint.<locals>.<genexpr>c                 3   r  r   )rv  r   r   r)  rM  rl   rp   r1    r  )r   r   r  r  r   r   r`   rA   define_constraint_remote_tabledefine_constraint_matchdefine_constraint_cascadesr  )r   r    r  r  remote_tablerl   rM  rp   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.)rV  )r   r    r`   r   rl   rl   rp   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)r}   c                 3   r  r   r  r  r   rl   rp   r1    r  z6DDLCompiler.visit_unique_constraint.<locals>.<genexpr>)r7  r   r   r  rA   r  r  rl   r   rp   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)ondeleter   validate_sql_phraseFK_ON_DELETEonupdateFK_ON_UPDATEr   r    r  rl   rl   rp   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   r   FK_INITIALLYr$  rl   rl   rp   r    s   



z+DDLCompiler.define_constraint_deferrabilityc                 C   s    d}|j d ur|d|j  7 }|S )Nr   z	 MATCH %s)matchr$  rl   rl   rp   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   r  	persisted)r   	generatedr  rl   rl   rp   visit_computed_column  s   

z!DDLCompiler.visit_computed_columnr   r  )FT)*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)  rl   rl   rl   rp   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FLOATrl   r   rl   rl   rp   visit_FLOAT  r   zGenericTypeCompiler.visit_FLOATc                 K   r   )NREALrl   r   rl   rl   rp   
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 )NNUMERICzNUMERIC(%(precision)s)	precisionz!NUMERIC(%(precision)s, %(scale)s)r1  scaler2  r   rl   rl   rp   visit_NUMERIC     

z!GenericTypeCompiler.visit_NUMERICc                 K   r/  )NDECIMALzDECIMAL(%(precision)s)r1  z!DECIMAL(%(precision)s, %(scale)s)r2  r2  r   rl   rl   rp   visit_DECIMAL  r5  z!GenericTypeCompiler.visit_DECIMALc                 K   r   )NINTEGERrl   r   rl   rl   rp   visit_INTEGER  r   z!GenericTypeCompiler.visit_INTEGERc                 K   r   )NSMALLINTrl   r   rl   rl   rp   visit_SMALLINT  r   z"GenericTypeCompiler.visit_SMALLINTc                 K   r   )NBIGINTrl   r   rl   rl   rp   visit_BIGINT  r   z GenericTypeCompiler.visit_BIGINTc                 K   r   )N	TIMESTAMPrl   r   rl   rl   rp   visit_TIMESTAMP  r   z#GenericTypeCompiler.visit_TIMESTAMPc                 K   r   )NDATETIMErl   r   rl   rl   rp   visit_DATETIME  r   z"GenericTypeCompiler.visit_DATETIMEc                 K   r   )NDATErl   r   rl   rl   rp   
visit_DATE  r   zGenericTypeCompiler.visit_DATEc                 K   r   )NTIMErl   r   rl   rl   rp   
visit_TIME  r   zGenericTypeCompiler.visit_TIMEc                 K   r   )NCLOBrl   r   rl   rl   rp   
visit_CLOB  r   zGenericTypeCompiler.visit_CLOBc                 K   r   )NNCLOBrl   r   rl   rl   rp   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")lengthr  )r   r   r   r  rl   rl   rp   _render_string_type  s   z'GenericTypeCompiler._render_string_typec                 K      |  |dS )NCHARrL  r   rl   rl   rp   
visit_CHAR   r  zGenericTypeCompiler.visit_CHARc                 K   rM  )NNCHARrO  r   rl   rl   rp   visit_NCHAR#  r  zGenericTypeCompiler.visit_NCHARc                 K   rM  )NVARCHARrO  r   rl   rl   rp   visit_VARCHAR&  r  z!GenericTypeCompiler.visit_VARCHARc                 K   rM  )NNVARCHARrO  r   rl   rl   rp   visit_NVARCHAR)  r  z"GenericTypeCompiler.visit_NVARCHARc                 K   rM  )NTEXTrO  r   rl   rl   rp   
visit_TEXT,  r  zGenericTypeCompiler.visit_TEXTc                 K   r   )NBLOBrl   r   rl   rl   rp   
visit_BLOB/  r   zGenericTypeCompiler.visit_BLOBc                 K      d|j r	d|j  p
d S )NBINARYrJ  r   rK  r   rl   rl   rp   visit_BINARY2  rH  z GenericTypeCompiler.visit_BINARYc                 K   r[  )N	VARBINARYrJ  r   r]  r   rl   rl   rp   visit_VARBINARY5  rH  z#GenericTypeCompiler.visit_VARBINARYc                 K   r   )NBOOLEANrl   r   rl   rl   rp   visit_BOOLEAN8  r   z!GenericTypeCompiler.visit_BOOLEANc                 K      | j |fi |S r   )rZ  r   rl   rl   rp   visit_large_binary;  r   z&GenericTypeCompiler.visit_large_binaryc                 K   rc  r   )rb  r   rl   rl   rp   visit_boolean>  r   z!GenericTypeCompiler.visit_booleanc                 K   rc  r   )rE  r   rl   rl   rp   
visit_timeA  r   zGenericTypeCompiler.visit_timec                 K   rc  r   )rA  r   rl   rl   rp   visit_datetimeD  r   z"GenericTypeCompiler.visit_datetimec                 K   rc  r   )rC  r   rl   rl   rp   
visit_dateG  r   zGenericTypeCompiler.visit_datec                 K   rc  r   )r=  r   rl   rl   rp   visit_big_integerJ  r   z%GenericTypeCompiler.visit_big_integerc                 K   rc  r   )r;  r   rl   rl   rp   visit_small_integerM  r   z'GenericTypeCompiler.visit_small_integerc                 K   rc  r   )r9  r   rl   rl   rp   visit_integerP  r   z!GenericTypeCompiler.visit_integerc                 K   rc  r   )r.  r   rl   rl   rp   
visit_realS  r   zGenericTypeCompiler.visit_realc                 K   rc  r   )r,  r   rl   rl   rp   visit_floatV  r   zGenericTypeCompiler.visit_floatc                 K   rc  r   )r4  r   rl   rl   rp   visit_numericY  r   z!GenericTypeCompiler.visit_numericc                 K   rc  r   rT  r   rl   rl   rp   visit_string\  r   z GenericTypeCompiler.visit_stringc                 K   rc  r   ro  r   rl   rl   rp   visit_unicode_  r   z!GenericTypeCompiler.visit_unicodec                 K   rc  r   rX  r   rl   rl   rp   
visit_textb  r   zGenericTypeCompiler.visit_textc                 K   rc  r   rr  r   rl   rl   rp   visit_unicode_texte  r   z&GenericTypeCompiler.visit_unicode_textc                 K   rc  r   ro  r   rl   rl   rp   
visit_enumh  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?rn  r   rl   rl   rp   r  k  s
   zGenericTypeCompiler.visit_nullc                 K   s   | j || jfi |S r   )r   type_enginer   r   rl   rl   rp   visit_type_decoratorr  s   z(GenericTypeCompiler.visit_type_decoratorc                 K   s   |j di |S )Nrl   )get_col_specr   rl   rl   rp   visit_user_definedu  rz  z&GenericTypeCompiler.visit_user_definedN)-r   r   r   r,  r.  r4  r7  r9  r;  r=  r?  rA  rC  rE  rG  rI  rL  rP  rR  rT  rV  rX  rZ  r^  r`  rb  rd  re  rf  rg  rh  ri  rj  rk  rl  rm  rn  rp  rq  rs  rt  ru  r  rw  ry  rl   rl   rl   rp   r*    sV    	r*  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   rl   rl   rp   __getattr__z  s   
zStrSQLTypeCompiler.__getattr__c                 K   s   d|j j S )Nz%s)r  r   r   rl   rl   rp   r}    r  z!StrSQLTypeCompiler._visit_unknownN)r   r   r   r  r}  rl   rl   rl   rp   rz  y  s    rz  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   )rx   rv   N)
r   initial_quotefinal_quoteescape_quoteescape_to_quoteomit_schemaquote_case_sensitive_collations_stringsr  r  )r   r   r  r  r  r  r  rl   rl   rp   r     s   zIdentifierPreparer.__init__c                 C   s,   | j | j }|j| j t||_|S r   )r  __new____dict__r  r   _schema_getterrx  )r   r   preprl   rl   rp   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.
        r  r  )r  r  r  r  r   r   rl   rl   rp   _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.
        )r  r  r  r  rl   rl   rp   _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))r&  r   r]  pattern)r   r   regrl   rl   rp   r     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  rl   rl   rp   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_charactersr&  r   	text_type)r   r   lc_valuerl   rl   rp   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  r&  r   r  r  rl   rl   rp   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_deprecatedrv  )r   r   forcerl   rl   rp   ry    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().rv  )r   r  r   r  r  r  )r   r   r  rl   rl   rp   rv  "  s   





zIdentifierPreparer.quotec                 C   s   | j r| |S |S r   )r  rv  )r   collation_namerl   rl   rp   r  T  s   
z#IdentifierPreparer.format_collationc                 C   s>   |  |j}| |}| js|r|d ur| |d | }|S r  )rv  r   rx  r  ry  )r   r  rD  r   r|  rl   rl   rp   r  Z  s   
z"IdentifierPreparer.format_sequencec                 C      |  |p|jS r   rv  r   )r   r   r   rl   rl   rp   rg  g  rz  zIdentifierPreparer.format_labelc                 C   r  r   r  )r   rs  r   rl   rl   rp   r  j  rz  zIdentifierPreparer.format_aliasc                 C   s"   |p|j }| |r| |}|S r   )r   r  r  )r   	savepointr   r   rl   rl   rp   r  m  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 )Nr  r      r   )rb  r   r   _defer_name_constraint_name_for_tabler`   _defer_none_namerc  r   r   max_index_name_lengthr  r7  r   md5_hexvalidate_identifierrv  )r   namingr    r   max_rl   rl   rp   r  v  s*   
&
z$IdentifierPreparer.format_constraintc                 C   
   |  |S r   )r  r  rl   rl   rp   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.Nrr  )r   rv  rx  r  ry  )r   r`   rD  r   rE  r|  rl   rl   rp   rV    s   

zIdentifierPreparer.format_tablec                 C   r  )zPrepare a quoted schema name.)rv  r  rl   rl   rp   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.Nrt  F)rD  r   rr  )r   r   rV  r`   rv  )r   r   r  r   
table_namerD  rl   rl   rp   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  )rx  r  ry  rV  )r   r`   rD  r|  rl   rl   rp   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 rl   )r/  r`  r  rl   rl   rp   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  escaped_finalrrl   rl   rp   _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 rl   )r  )rn   r  r   rl   rp   r    r  z;IdentifierPreparer.unformat_identifiers.<locals>.<listcomp>c                 S   s   g | ]\}}|p	|qS rl   rl   )rn   abrl   rl   rp   r    r  )r  findall)r   identifiersr  rl   r   rp   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  rx  r   r   r  r  r   r  r  r  ry  rv  r  r  rg  r  r  r   r  r  r  rV  r  r  r  r  r  r  rl   rl   rl   rp   r    sP    

$	

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

&
r  )lr   r  r-  r/  r   r   r   r   r   r   r   r	   r
   r   r   r\   r  r   Ir  LEGAL_CHARACTERS_PLUS_SPACErangere   r  r!  r#  r%  UNICODEr  r  r  and_or_addmulr0  divmodtruedivnegltlenegtgeeqis_distinct_fromisnot_distinct_from	concat_opr(  notmatch_opin_opnotin_opcomma_opr#  rf  is_isnotr   existsdistinct_opinvany_opall_opdesc_opasc_opnullsfirst_opnullslast_opre  r   r#   r%   r&   r'   rF   rG   r   r   r[   rg   cuberollupgrouping_setsr  r  r  r   	UNION_ALLr   
EXCEPT_ALLr   INTERSECT_ALLr  objectr   with_metaclassEnsureKWArgTyper   	Visitabler   r4  r   r   r  r  r*  rz  r  rl   rl   rl   rp   <module>   sf  c		
 !"#%&,
                   &B   O 