U kf"@sdZddlmZddlZddlZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z d d l mZd d lmZd dlmZd dlmZd dlmZddl mZddl mZddlmZddlmZddlmZejrd dlmZd dlmZd dlmZd dl m!Z!d dl m"Z"d dl m#Z#d d l m Z d dl m$Z$d dl%m&Z&ddl'm(Z(dd l)m*Z*dd!l)m+Z+dd"l)m,Z,dd#l)m-Z-Gd$d%d%eZ.Gd&d'd'eZ/Gd(d)d)ej0Z1Gd*d+d+ej2ee.Z3e3Z4Gd,d-d-e3Z5Gd.d/d/e3Z6Gd0d1d1e6Z7Gd2d3d3e6Z8Gd4d5d5e7Z9Gd6d7d7e8Z:Gd8d9d9e7Z;Gd:d;d;e8Zd?d?e.Z>Gd@dAdAe8Z?GdBdCdCe7Z@GdDdEdEe8ZAGdFdGdGe7ZBGdHdIdIe8ZCGdJdKdKe7ZDGdLdMdMe8ZEGdNdOdOe6ZFGdPdQdQe6ZGGdRdSdSe6ZHGdTdUdUe6ZIGdVdWdWe6ZJGdXdYdYe6ZKGdZd[d[eZLGd\d]d]eLZMGd^d_d_eLZNGd`dadaeMZOGdbdcdceNZPdndddedfdgdhdidjZQdodldmZRdS)pzq Provides the hierarchy of DDL-defining schema items as well as routines to invoke them for a create/drop call. ) annotationsN)Any)Callable)Iterable)List)Optional)Sequence)Tuple)roles) _generative) Executable) SchemaVisitor) ClauseElement)exc)util) topological)Protocol)Self)Compiled) DDLCompiler) BindParameter) Constraint)ForeignKeyConstraint) SchemaItem)Table) TableClause) Connection) CacheStats)CompiledCacheType)Dialect)SchemaTranslateMapTypec @s>eZdZdZdZddZdddddd d d d d dddZdS)BaseDDLElementzThe root of DDL constructs, including those that are sub-elements within the "create table" and other processes. .. versionadded:: 2.0 FcKs|j||f|S)zNReturn a compiler appropriate for this ClauseElement, given a Dialect.)Z ddl_compiler)selfdialectkwr'B/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/sql/ddl.py _compilerAszBaseDDLElement._compilerN)for_executemanyschema_translate_mapr!zOptional[CompiledCacheType]z List[str]boolz Optional[SchemaTranslateMapType]rzJTuple[Compiled, Optional[typing_Sequence[BindParameter[Any]]], CacheStats])r%compiled_cache column_keysr*r+r&returncKs tdSNNotImplementedError)r$r%r-r.r*r+r&r'r'r(_compile_w_cacheGs zBaseDDLElement._compile_w_cache)__name__ __module__ __qualname____doc__Z_hierarchy_supports_cachingr)r3r'r'r'r(r#6s  r#c @s2eZdZddddddddd d d d d d dZdS) DDLIfCallableN.)compilerr#rOptional[Connection]zOptional[List[Table]] Optional[Any]r!Optional[DDLCompiler]r,) ddltargetbindtablesstater%r9 checkfirstr/c CsdSr0r') r$r=r>r?r@rAr%r9rBr'r'r(__call__Ws zDDLIfCallable.__call__)NN)r4r5r6rCr'r'r'r(r8Vs  r8c@s@eZdZUded<ded<ded<ddd d d d d dddZdS)DDLIf Optional[str]r%Optional[DDLIfCallable] callable_r;rANr#rr:r<rr,)r=r>r?r9r&r/cKs|dk r|j}n|dk r |j}n ds,tdt|jtrJ|j|jkrldSn"t|jtttfrl|j|jkrldS|jdk r|j|||f|j ||d|sdSdS)NFzcompiler or dialect is required)rAr%r9T) r%AssertionError isinstancestrnametuplelistsetrGrA)r$r=r>r?r9r&r%r'r'r(_should_executejs0     zDDLIf._should_execute)N)r4r5r6__annotations__rOr'r'r'r(rDes rDc@seZdZUdZdZded<dZded<ddZed d d d d Z eddddd dddZ ddZ ddZ ddZ ddZdS)ExecutableDDLElementaBase class for standalone executable DDL expression constructs. This class is the base for the general purpose :class:`.DDL` class, as well as the various create/drop clause constructs such as :class:`.CreateTable`, :class:`.DropTable`, :class:`.AddConstraint`, etc. .. versionchanged:: 2.0 :class:`.ExecutableDDLElement` is renamed from :class:`.DDLElement`, which still exists for backwards compatibility. :class:`.ExecutableDDLElement` integrates closely with SQLAlchemy events, introduced in :ref:`event_toplevel`. An instance of one is itself an event receiving callable:: event.listen( users, 'after_create', AddConstraint(constraint).execute_if(dialect='postgresql') ) .. seealso:: :class:`.DDL` :class:`.DDLEvents` :ref:`event_toplevel` :ref:`schema_ddl_sequences` NzOptional[DDLIf]_ddl_ifzOptional[SchemaItem]r>cCs||||Sr0)Z _execute_ddl)r$ connectionZdistilled_paramsZexecution_optionsr'r'r(_execute_on_connections z+ExecutableDDLElement._execute_on_connectionrr)r>r/cCs ||_|S)aReturn a copy of this :class:`_schema.ExecutableDDLElement` which will include the given target. This essentially applies the given item to the ``.target`` attribute of the returned :class:`_schema.ExecutableDDLElement` object. This target is then usable by event handlers and compilation routines in order to provide services such as tokenization of a DDL string in terms of a particular :class:`_schema.Table`. When a :class:`_schema.ExecutableDDLElement` object is established as an event handler for the :meth:`_events.DDLEvents.before_create` or :meth:`_events.DDLEvents.after_create` events, and the event then occurs for a given target such as a :class:`_schema.Constraint` or :class:`_schema.Table`, that target is established with a copy of the :class:`_schema.ExecutableDDLElement` object using this method, which then proceeds to the :meth:`_schema.ExecutableDDLElement.execute` method in order to invoke the actual DDL instruction. :param target: a :class:`_schema.SchemaItem` that will be the subject of a DDL operation. :return: a copy of this :class:`_schema.ExecutableDDLElement` with the ``.target`` attribute assigned to the given :class:`_schema.SchemaItem`. .. seealso:: :class:`_schema.DDL` - uses tokenization against the "target" when processing the DDL string. )r>)r$r>r'r'r(againsts!zExecutableDDLElement.againstrErFr;)r%rGrAr/cCst||||_|S)a` Return a callable that will execute this :class:`_ddl.ExecutableDDLElement` conditionally within an event handler. Used to provide a wrapper for event listening:: event.listen( metadata, 'before_create', DDL("my_ddl").execute_if(dialect='postgresql') ) :param dialect: May be a string or tuple of strings. If a string, it will be compared to the name of the executing database dialect:: DDL('something').execute_if(dialect='postgresql') If a tuple, specifies multiple dialect names:: DDL('something').execute_if(dialect=('postgresql', 'mysql')) :param callable\_: A callable, which will be invoked with three positional arguments as well as optional keyword arguments: :ddl: This DDL element. :target: The :class:`_schema.Table` or :class:`_schema.MetaData` object which is the target of this event. May be None if the DDL is executed explicitly. :bind: The :class:`_engine.Connection` being used for DDL execution. May be None if this construct is being created inline within a table, in which case ``compiler`` will be present. :tables: Optional keyword argument - a list of Table objects which are to be created/ dropped within a MetaData.create_all() or drop_all() method call. :dialect: keyword argument, but always present - the :class:`.Dialect` involved in the operation. :compiler: keyword argument. Will be ``None`` for an engine level DDL invocation, but will refer to a :class:`.DDLCompiler` if this DDL element is being created inline within a table. :state: Optional keyword argument - will be the ``state`` argument passed to this function. :checkfirst: Keyword argument, will be True if the 'checkfirst' flag was set during the call to ``create()``, ``create_all()``, ``drop()``, ``drop_all()``. If the callable returns a True value, the DDL statement will be executed. :param state: any value which will be passed to the callable\_ as the ``state`` keyword argument. .. seealso:: :meth:`.SchemaItem.ddl_if` :class:`.DDLEvents` :ref:`event_toplevel` )rDrR)r$r%rGrAr'r'r( execute_ifsSzExecutableDDLElement.execute_ifcKs&|jdkrdS|jj|||f|SdSNT)rRrOr$r>r?r&r'r'r(rO2s z$ExecutableDDLElement._should_executecCs||j|r||SdSr0)rOr>execute)r$r?r'r'r( _invoke_with8sz!ExecutableDDLElement._invoke_withcKs|||dS)z"Execute the DDL as a ddl_listener.N)rUrZrXr'r'r(rC<szExecutableDDLElement.__call__cCs|j|j}|j|_|Sr0) __class____new____dict__copy)r$sr'r'r( _generateAs zExecutableDDLElement._generate)NNN)r4r5r6r7rRrPr>rTr rUrVrOrZrCr`r'r'r'r(rQs   #UrQc@s&eZdZdZdZdddZddZdS) DDLaAA literal DDL statement. Specifies literal SQL DDL to be executed by the database. DDL objects function as DDL event listeners, and can be subscribed to those events listed in :class:`.DDLEvents`, using either :class:`_schema.Table` or :class:`_schema.MetaData` objects as targets. Basic templating support allows a single DDL instance to handle repetitive tasks for multiple tables. Examples:: from sqlalchemy import event, DDL tbl = Table('users', metadata, Column('uid', Integer)) event.listen(tbl, 'before_create', DDL('DROP TRIGGER users_trigger')) spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE') event.listen(tbl, 'after_create', spow.execute_if(dialect='somedb')) drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE') connection.execute(drop_spow) When operating on Table events, the following ``statement`` string substitutions are available:: %(table)s - the Table name, with any required quoting applied %(schema)s - the schema name, with any required quoting applied %(fullname)s - the Table name including schema, quoted if needed The DDL's "context", if any, will be combined with the standard substitutions noted above. Keys present in the context will override the standard substitutions. r=NcCs,t|tstd|||_|p$i|_dS)aCreate a DDL statement. :param statement: A string or unicode string to be executed. Statements will be processed with Python's string formatting operator using a fixed set of string substitutions, as well as additional substitutions provided by the optional :paramref:`.DDL.context` parameter. A literal '%' in a statement must be escaped as '%%'. SQL bind parameters are not available in DDL statements. :param context: Optional dictionary, defaults to None. These values will be available for use in string substitutions on the DDL statement. .. seealso:: :class:`.DDLEvents` :ref:`event_toplevel` z4Expected a string or unicode SQL statement, got '%r'N)rIrJr ArgumentError statementcontext)r$rcrdr'r'r(__init__qs z DDL.__init__cCsBt|jg}|jr$|d|jdt|jt|d|fS)Nzcontext=z <%s@%s; %s>, )reprrcrdappendtyper4idjoin)r$partsr'r'r(__repr__s z DDL.__repr__)N)r4r5r6r7__visit_name__rermr'r'r'r(raKs# #rac@s,eZdZdZddZeddZddZdS) _CreateDropBasezBase class for DDL constructs that represent CREATE and DROP or equivalents. The common theme of _CreateDropBase is a single ``element`` attribute which refers to the element to be created or dropped. cCs||_|_t|dd|_dS)NrR)elementr>getattrrRr$rpr'r'r(res z_CreateDropBase.__init__cCs|jjSr0)rpZcreate_drop_stringify_dialectr$r'r'r(stringify_dialectsz!_CreateDropBase.stringify_dialectcCsdS)zAllow disable of _create_rule using a callable. Pass to _create_rule using util.portable_instancemethod(self._create_rule_disable) to retain serializability. Fr')r$r9r'r'r(_create_rule_disablesz$_CreateDropBase._create_rule_disableN)r4r5r6r7repropertyrtrur'r'r'r(ros   rocseZdZdfdd ZZS) _CreateBaseFcst|||_dSr0)superre if_not_existsr$rpryr[r'r(res z_CreateBase.__init__)Fr4r5r6re __classcell__r'r'r{r(rwsrwcseZdZdfdd ZZS) _DropBaseFcst|||_dSr0)rxre if_existsr$rprr{r'r(res z_DropBase.__init__)Fr|r'r'r{r(r~sr~cs*eZdZdZdZdZdfdd ZZS) CreateSchemazcRepresent a CREATE SCHEMA statement. The argument here is the string name of the schema. Z create_schemadefaultFcstj||ddS)z.Create a new :class:`.CreateSchema` construct.rpryNrxre)r$rKryr{r'r(reszCreateSchema.__init__)Fr4r5r6r7rnrtrer}r'r'r{r(rs rcs*eZdZdZdZdZdfdd ZZS) DropSchemazaRepresent a DROP SCHEMA statement. The argument here is the string name of the schema. Z drop_schemarFcstj||d||_dS)z,Create a new :class:`.DropSchema` construct.rprN)rxrecascade)r$rKrrr{r'r(reszDropSchema.__init__)FFrr'r'r{r(rs rcs0eZdZdZdZd ddddfd d ZZS) CreateTablez#Represent a CREATE TABLE statement.Z create_tableNFrz/Optional[typing_Sequence[ForeignKeyConstraint]]r,)rpinclude_foreign_key_constraintsrycs,tj||ddd|jD|_||_dS)aCreate a :class:`.CreateTable` construct. :param element: a :class:`_schema.Table` that's the subject of the CREATE :param on: See the description for 'on' in :class:`.DDL`. :param include_foreign_key_constraints: optional sequence of :class:`_schema.ForeignKeyConstraint` objects that will be included inline within the CREATE construct; if omitted, all foreign key constraints that do not specify use_alter=True are included. :param if_not_exists: if True, an IF NOT EXISTS operator will be applied to the construct. .. versionadded:: 1.4.0b2 rycSsg|] }t|qSr') CreateColumn).0columnr'r'r( sz(CreateTable.__init__..N)rxrecolumnsr)r$rprryr{r'r(reszCreateTable.__init__)NFr4r5r6r7rnrer}r'r'r{r(rs rc@seZdZdZdZdS) _DropViewzSemi-public 'DROP VIEW' construct. Used by the test suite for dialect-agnostic drops of views. This object will eventually be part of a public "view" API. Z drop_viewNr4r5r6r7rnr'r'r'r(rsrc@seZdZddddZdS)CreateConstraintrrpcCs ||_dSr0rrrr'r'r(re&szCreateConstraint.__init__N)r4r5r6rer'r'r'r(r%src@seZdZdZdZddZdS)raRepresent a :class:`_schema.Column` as rendered in a CREATE TABLE statement, via the :class:`.CreateTable` construct. This is provided to support custom column DDL within the generation of CREATE TABLE statements, by using the compiler extension documented in :ref:`sqlalchemy.ext.compiler_toplevel` to extend :class:`.CreateColumn`. Typical integration is to examine the incoming :class:`_schema.Column` object, and to redirect compilation if a particular flag or condition is found:: from sqlalchemy import schema from sqlalchemy.ext.compiler import compiles @compiles(schema.CreateColumn) def compile(element, compiler, **kw): column = element.element if "special" not in column.info: return compiler.visit_create_column(element, **kw) text = "%s SPECIAL DIRECTIVE %s" % ( column.name, compiler.type_compiler.process(column.type) ) default = compiler.get_column_default_string(column) if default is not None: text += " DEFAULT " + default if not column.nullable: text += " NOT NULL" if column.constraints: text += " ".join( compiler.process(const) for const in column.constraints) return text The above construct can be applied to a :class:`_schema.Table` as follows:: from sqlalchemy import Table, Metadata, Column, Integer, String from sqlalchemy import schema metadata = MetaData() table = Table('mytable', MetaData(), Column('x', Integer, info={"special":True}, primary_key=True), Column('y', String(50)), Column('z', String(20), info={"special":True}) ) metadata.create_all(conn) Above, the directives we've added to the :attr:`_schema.Column.info` collection will be detected by our custom compilation scheme:: CREATE TABLE mytable ( x SPECIAL DIRECTIVE INTEGER NOT NULL, y VARCHAR(50), z SPECIAL DIRECTIVE VARCHAR(20), PRIMARY KEY (x) ) The :class:`.CreateColumn` construct can also be used to skip certain columns when producing a ``CREATE TABLE``. This is accomplished by creating a compilation rule that conditionally returns ``None``. This is essentially how to produce the same effect as using the ``system=True`` argument on :class:`_schema.Column`, which marks a column as an implicitly-present "system" column. For example, suppose we wish to produce a :class:`_schema.Table` which skips rendering of the PostgreSQL ``xmin`` column against the PostgreSQL backend, but on other backends does render it, in anticipation of a triggered rule. A conditional compilation rule could skip this name only on PostgreSQL:: from sqlalchemy.schema import CreateColumn @compiles(CreateColumn, "postgresql") def skip_xmin(element, compiler, **kw): if element.element.name == 'xmin': return None else: return compiler.visit_create_column(element, **kw) my_table = Table('mytable', metadata, Column('id', Integer, primary_key=True), Column('xmin', Integer) ) Above, a :class:`.CreateTable` construct will generate a ``CREATE TABLE`` which only includes the ``id`` column in the string; the ``xmin`` column will be omitted, but only against the PostgreSQL backend. Z create_columncCs ||_dSr0rrrr'r'r(reszCreateColumn.__init__N)r4r5r6r7rnrer'r'r'r(r*sfrcs.eZdZdZdZd dddfdd ZZS) DropTablez!Represent a DROP TABLE statement.Z drop_tableFrr,rcstj||ddS)aVCreate a :class:`.DropTable` construct. :param element: a :class:`_schema.Table` that's the subject of the DROP. :param on: See the description for 'on' in :class:`.DDL`. :param if_exists: if True, an IF EXISTS operator will be applied to the construct. .. versionadded:: 1.4.0b2 rNrrr{r'r(res zDropTable.__init__)Frr'r'r{r(rsrcs.eZdZdZdZd dddfdd ZZS) CreateSequencez&Represent a CREATE SEQUENCE statement.Zcreate_sequenceFrr,rcstj||ddS)Nrrrzr{r'r(reszCreateSequence.__init__)Frr'r'r{r(rsrcs.eZdZdZdZd dddfdd ZZS) DropSequencez$Represent a DROP SEQUENCE statement.Z drop_sequenceFrr,rcstj||ddS)Nrrrr{r'r(reszDropSequence.__init__)Frr'r'r{r(rsrcs&eZdZdZdZdfdd ZZS) CreateIndexz#Represent a CREATE INDEX statement.Z create_indexFcstj||ddS)a Create a :class:`.Createindex` construct. :param element: a :class:`_schema.Index` that's the subject of the CREATE. :param if_not_exists: if True, an IF NOT EXISTS operator will be applied to the construct. .. versionadded:: 1.4.0b2 rNrrzr{r'r(res zCreateIndex.__init__)Frr'r'r{r(rsrcs&eZdZdZdZdfdd ZZS) DropIndexz!Represent a DROP INDEX statement.Z drop_indexFcstj||ddS)aCreate a :class:`.DropIndex` construct. :param element: a :class:`_schema.Index` that's the subject of the DROP. :param if_exists: if True, an IF EXISTS operator will be applied to the construct. .. versionadded:: 1.4.0b2 rNrrr{r'r(res zDropIndex.__init__)Frr'r'r{r(rsrcs$eZdZdZdZfddZZS) AddConstraintz2Represent an ALTER TABLE ADD CONSTRAINT statement.Zadd_constraintcst|t|j|_dSr0)rxrerportable_instancemethodru _create_rulerrr{r'r(res zAddConstraint.__init__rr'r'r{r(rsrcs&eZdZdZdZdfdd ZZS)DropConstraintz3Represent an ALTER TABLE DROP CONSTRAINT statement.Zdrop_constraintFc s0||_tj|fd|i|t|j|_dS)Nr)rrxrerrrur)r$rprrr&r{r'r(res zDropConstraint.__init__)FFrr'r'r{r(rsrc@seZdZdZdZdS)SetTableCommentz*Represent a COMMENT ON TABLE IS statement.Zset_table_commentNrr'r'r'r(rsrc@seZdZdZdZdS)DropTableCommentzfRepresent a COMMENT ON TABLE '' statement. Note this varies a lot across database backends. Zdrop_table_commentNrr'r'r'r(rsrc@seZdZdZdZdS)SetColumnCommentz+Represent a COMMENT ON COLUMN IS statement.Zset_column_commentNrr'r'r'r(r src@seZdZdZdZdS)DropColumnCommentz0Represent a COMMENT ON COLUMN IS NULL statement.Zdrop_column_commentNrr'r'r'r(rsrc@seZdZdZdZdS)SetConstraintCommentz/Represent a COMMENT ON CONSTRAINT IS statement.Zset_constraint_commentNrr'r'r'r(rsrc@seZdZdZdZdS)DropConstraintCommentz4Represent a COMMENT ON CONSTRAINT IS NULL statement.Zdrop_constraint_commentNrr'r'r'r(rsrc@s"eZdZddZejddZdS) InvokeDDLBasecCs ||_dSr0)rS)r$rSr'r'r(re%szInvokeDDLBase.__init__cKs tdS)dhelper context manager that will apply appropriate DDL events to a CREATE or DROP operation.Nr1r$r>r&r'r'r(with_ddl_events(szInvokeDDLBase.with_ddl_eventsN)r4r5r6re contextlibcontextmanagerrr'r'r'r(r$src@seZdZejddZdS)InvokeCreateDDLBasecksB|jj||jfd|i|dV|jj||jfd|i|dSrZ _ddl_runnerN)dispatchZ before_createrSZ after_createrr'r'r(r1s"z#InvokeCreateDDLBase.with_ddl_eventsNr4r5r6rrrr'r'r'r(r0src@seZdZejddZdS)InvokeDropDDLBasecksB|jj||jfd|i|dV|jj||jfd|i|dSr)rZ before_droprSZ after_droprr'r'r(r@s"z!InvokeDropDDLBase.with_ddl_eventsNrr'r'r'r(r?srcsdeZdZdfdd ZddZddZd d Zd d Zdd dZddZ dddZ dddZ Z S)SchemaGeneratorFNc s4tj|f|||_||_|j|_||_i|_dSr0rxrerBr@Zidentifier_preparerpreparerr%memor$r%rSrBr@kwargsr{r'r(reOs zSchemaGenerator.__init__cCsJ|j|j|j|}|r*|j||j pH|jj|j|j|d SN)schemar%validate_identifierrKrSschema_for_objectrBZ has_tabler$tableeffective_schemar'r'r(_can_create_tableYs  z!SchemaGenerator._can_create_tablecCsD|j|j}|r|j||j pB|jj|j|jj|j|d SrrSrrr%rrBZ has_indexrKr$indexrr'r'r(_can_create_indexbs z!SchemaGenerator._can_create_indexcCsF|j|}|jjoD|jj s&|j oD|j pD|jj|j|j|d Sr rSrr%Zsupports_sequencesZsequences_optionaloptionalrBZ has_sequencerKr$sequencerr'r'r(_can_create_sequencems z$SchemaGenerator._can_create_sequencec sjdk rj}nt|j}tfdd|D}fdd|jD}dd|D}j||jd\|D]}j|ddqt|D]8\}}|dk rj|d|ddq|D]} | qqW5QRXdS) Ncsg|]}|r|qSr')rrtrsr'r(rs z2SchemaGenerator.visit_metadata..cs$g|]}|jdkr|r|qSr0)rrrr_rsr'r(rs cSsg|]\}}|dk r|qSr0r'rrZfksr'r'r(rsr@rBT create_ok)rr_is_metadata_operation)r@rMvaluessort_tables_and_constraints _sequencesrrBtraverse_single) r$metadatar@ collectionseq_collevent_collectionseqrfkcsfkcr'rsr(visit_metadatazs6   zSchemaGenerator.visit_metadatac Cs|s||sdS|j||j|d|jD]}|jdk r,||jq,|jjsTd}t||d |j t |dr|j D]}|j|ddqx|jj r|jjs|jdk rt| |j |jD]}|jdk rt| |j q|jjr|jD]}|jdk r|j t|qW5QRXdS)NrBr)rindexesTr)rrrBrrrr%supports_alterrrZrShasattrrZsupports_commentsZinline_commentscommentrrZsupports_constraint_comments constraintsrYr)r$rrrrrr constraintr'r'r( visit_tablesH          zSchemaGenerator.visit_tablec Cs6|jjs dS||t||jW5QRXdSr0)r%rrrrZrSr$rr'r'r(visit_foreign_key_constraints z,SchemaGenerator.visit_foreign_key_constraintc Cs<|s||sdS||t||jW5QRXdSr0)rrrrZrS)r$rrr'r'r(visit_sequences zSchemaGenerator.visit_sequencec Cs<|s||sdS||t||jW5QRXdSr0)rrrrZrS)r$rrr'r'r( visit_indexs zSchemaGenerator.visit_index)FN)FNF)F)F) r4r5r6rerrrrrrrrr}r'r'r{r(rNs    ) 4 rcsdeZdZdfdd ZddZddZd d Zd d Zdd dZdddZ ddZ dddZ Z S) SchemaDropperFNc s4tj|f|||_||_|j|_||_i|_dSr0rrr{r'r(res zSchemaDropper.__init__c sjdk rj}nt|j}z2fdd|D}ttt|fddd}Wntjk r}zxjjst dd t dd|j Dd d|D}n8tj|jd |j |jd d t d d|j Dd |W5d}~XYnXfdd|jD}dd|D}j||jdj|D]>\}} |dk rPj|dd|dn| D]} | qTq*|D]} j| | jdkdqnW5QRXdS)Ncsg|]}|r|qSr')_can_drop_tablerrsr'r(rs z0SchemaDropper.visit_metadata..csjjr|jdkrdSdSNF)r%rrK)rrsr'r(s z.SchemaDropper.visit_metadata.. filter_fna4Can't sort tables for DROP; an unresolvable foreign key dependency exists between tables: %s; and backend does not support ALTER. To restore at least a partial sort, apply use_alter=True to ForeignKey and ForeignKeyConstraint objects involved in the cycle to mark these as known cycles that will be ignored.rfcSsg|] }|jqSr'fullnamerr'r'r(rscSsg|] }|dfqS)r'r'rr'r'r(rsrzCan't sort tables for DROP; an unresolvable foreign key dependency exists between tables: %s. Please ensure that the ForeignKey and ForeignKeyConstraint objects involved in the cycle have names so that they can be dropped using DROP CONSTRAINT.cSsg|] }|jqSr'rrr'r'r(r"s)msgcsg|]}|r|qSr')_can_drop_sequencerrsr'r(r%s cSsg|]\}}|dk r|qSr0r'rr'r'r(r+srT)drop_okr_ignore_sequences)r)r@rMrreversedrrCircularDependencyErrorr%rrwarnrksortedcyclesargsedgesrrrBrr) r$rr@Zunsorted_tablesrZerr2rrrrrrr'rsr(rsh        zSchemaDropper.visit_metadatacCsH|j|j|j|}|r*|j||j pF|jj|j|j|dSrrrr'r'r(rAs  zSchemaDropper._can_drop_tablecCsB|j|j}|r|j||j p@|jj|j|jj|j|dSrrrr'r'r(_can_drop_indexJs zSchemaDropper._can_drop_indexcCsD|j|}|jjoB|jj s&|j oB|j pB|jj|j|j|dSrrrr'r'r(rUs z SchemaDropper._can_drop_sequencec Cs<|s||sdS||t|||jW5QRXdSr0)rrrrS)r$rrr'r'r(ras zSchemaDropper.visit_indexr'c Csp|s||sdS|j||j|dBt||j|jD]$}|jdk r<|j|kr<||jq._skip_fncSsg|]\}}|dk r|qSr0r')rrrr'r'r(rszsort_tables..T)rr_warn_for_cycles)r)r@rrrr'rr( sort_tablessArFc st}t}|dk r||t|D]|jD]V}|jdkrL|q2rl|}|dkrl|q2|j}|k r2||fq2|fddjDq(ztt | ||} Wnt j k r} z|rt ddtdd| jDf| jD]p} | |kr| d| jkr.qfd d jD} | | D]$}|j}|k rP||fqPqtt | ||} W5d} ~ XYnXfd d | DdtfgS) aSort a collection of :class:`_schema.Table` / :class:`_schema.ForeignKeyConstraint` objects. This is a dependency-ordered sort which will emit tuples of ``(Table, [ForeignKeyConstraint, ...])`` such that each :class:`_schema.Table` follows its dependent :class:`_schema.Table` objects. Remaining :class:`_schema.ForeignKeyConstraint` objects that are separate due to dependency rules not satisfied by the sort are emitted afterwards as ``(None, [ForeignKeyConstraint ...])``. Tables are dependent on another based on the presence of :class:`_schema.ForeignKeyConstraint` objects, explicit dependencies added by :meth:`_schema.Table.add_is_dependent_on`, as well as dependencies stated here using the :paramref:`~.sort_tables_and_constraints.skip_fn` and/or :paramref:`~.sort_tables_and_constraints.extra_dependencies` parameters. :param tables: a sequence of :class:`_schema.Table` objects. :param filter_fn: optional callable which will be passed a :class:`_schema.ForeignKeyConstraint` object, and returns a value based on whether this constraint should definitely be included or excluded as an inline constraint, or neither. If it returns False, the constraint will definitely be included as a dependency that cannot be subject to ALTER; if True, it will **only** be included as an ALTER result at the end. Returning None means the constraint is included in the table-based result unless it is detected as part of a dependency cycle. :param extra_dependencies: a sequence of 2-tuples of tables which will also be considered as dependent on each other. .. seealso:: :func:`.sort_tables` NTc3s|]}|fVqdSr0r')rparent)rr'r( 4sz.sort_tables_and_constraints..aCannot correctly sort tables; there are unresolvable cycles between tables "%s", which is usually caused by mutually dependent foreign key constraints. Foreign key constraints involving these tables will not be considered; this warning may raise an error in a future release.rfcss|] }|jVqdSr0rrr'r'r(rGsr cs$g|]}dks|dk r|qSrr')rrrr'r(rNs z/sort_tables_and_constraints..csg|]}||jfqSr')foreign_key_constraints difference)rr)remaining_fkcsr'r(r_s)rNupdaterZ use_alteraddZreferred_tableZ_extra_dependenciesrMrsortunionrrrrrkrrrdiscard) r@rrrZfixed_dependenciesZmutable_dependenciesrfilteredZ dependent_onZcandidate_sorterredgeZ can_remover')rrrr(rsv.              r)NN)NNF)Sr7 __future__rrtypingrrrrrrZtyping_Sequencer r baser r rrrrrrZ util.typingrr TYPE_CHECKINGr9rrrrrrrrZ selectablerZ engine.baserZengine.interfacesrr r!r"r#r8 NamedTuplerDZDDLRolerQZ DDLElementrarorwr~rrrrrrrrrrrrrrrrrrrrrrrrrrr'r'r'r( s                                 (;U " m      /[