U a@sdZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd l m Z Gd d d e Z Gdddejee ZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGddde ZGdddeZGd d!d!eZGd"d#d#eZGd$d%d%eZGd&d'd'eZGd(d)d)eZGd*d+d+eZGd,d-d-eZGd.d/d/eZGd0d1d1eZ Gd2d3d3eZ!Gd4d5d5eZ"Gd6d7d7e"Z#Gd8d9d9e"Z$d@d;d<Z%dAd>d?Z&d:S)Bzq Provides the hierarchy of DDL-defining schema items as well as routines to invoke them for a create/drop call. )roles)_bind_or_error) _generative) Executable) SchemaVisitor) ClauseElement)exc)util) topologicalc@seZdZddZddZdS) _DDLCompilescKs|j||f|S)zNReturn a compiler appropriate for this ClauseElement, given a Dialect.)Z ddl_compiler)selfdialectkwrSC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\sql\ddl.py _compilersz_DDLCompiles._compilercOs tdSN)NotImplementedError)r argrrrr_compile_w_cachesz_DDLCompiles._compile_w_cacheN)__name__ __module__ __qualname__rrrrrrr sr c@seZdZdZejddiZdZdZdZ dZ ddZ e j ddd dd d Zed d ZedddZddZddZddZddZeeeZddZdS) DDLElementaBase class for 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. :class:`.DDLElement` 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` Z autocommitTNcCs|||||Sr)Z _execute_ddl)r connectionZ multiparamsparamsZexecution_optionsrrr_execute_on_connectionJs z!DDLElement._execute_on_connectionz:meth:`.DDLElement.execute`zAll statement execution in SQLAlchemy 2.0 is performed by the :meth:`_engine.Connection.execute` method of :class:`_engine.Connection`, or in the ORM by the :meth:`.Session.execute` method of :class:`.Session`.) alternativecCs>|dkrt|}|||r,|||S|jjddS)aExecute this DDL immediately. Executes the DDL statement in isolation using the supplied :class:`.Connectable` or :class:`.Connectable` assigned to the ``.bind`` property, if not supplied. If the DDL has a conditional ``on`` criteria, it will be invoked with None as the event. :param bind: Optional, an ``Engine`` or ``Connection``. If not supplied, a valid :class:`.Connectable` must be present in the ``.bind`` property. :param target: Optional, defaults to None. The target :class:`_schema.SchemaItem` for the execute call. This is equivalent to passing the :class:`_schema.SchemaItem` to the :meth:`.DDLElement.against` method and then invoking :meth:`_schema.DDLElement.execute` upon the resulting :class:`_schema.DDLElement` object. See :meth:`.DDLElement.against` for further detail. Nz(DDL execution skipped, criteria not met.)r_should_executeexecuteagainstengineloggerinfo)r bindtargetrrrr Qs  zDDLElement.executecCs ||_dS)aReturn a copy of this :class:`_schema.DDLElement` which will include the given target. This essentially applies the given item to the ``.target`` attribute of the returned :class:`_schema.DDLElement` 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.DDLElement` 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.DDLElement` object using this method, which then proceeds to the :meth:`_schema.DDLElement.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.DDLElement` 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. N)r&)r r&rrrr!ys"zDDLElement.againstcCs||_||_||_dS)a7Return a callable that will execute this :class:`_ddl.DDLElement` 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 four 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 :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. :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:: :class:`.DDLEvents` :ref:`event_toplevel` N)r callable_state)r rr'r(rrr execute_ifsBzDDLElement.execute_ifcKstt|jtjr"|j|jjkrFdSn$t|jtttfrF|jj|jkrFdS|j dk rp|j |||fd|j i|spdSdS)NFr(T) isinstancerr string_typesr"nametuplelistsetr'r(r r&r%rrrrrs"zDDLElement._should_executecKs$|j||f|r |||SdS)z"Execute the DDL as a ddl_listener.N)rr r!r0rrr__call__szDDLElement.__call__cCs|jr |jSdSr_bindr rrrr%szDDLElement.bindcCs ||_dSrr2)r r%rrr _set_bindszDDLElement._set_bindcCs|j|j}|j|_|Sr) __class____new____dict__copy)r srrr _generates zDDLElement._generate)NN)NNN)rrr__doc__rZ_execution_optionsunionr&onrr'rr Z deprecated_20r rr!r)rr1r%r5propertyr;rrrrr#s0  # E rc@s2eZdZdZdZejddd ddZdd ZdS) 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. Zddl)2.0z[The :paramref:`_ddl.DDL.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.r%NcCs4t|tjstd|||_|p&i|_||_dS)a(Create a DDL statement. :param statement: A string or unicode string to be executed. Statements will be processed with Python's string formatting operator. See the ``context`` argument and the ``execute_at`` method. 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. :param bind: Optional. A :class:`.Connectable`, used by default when ``execute()`` is invoked without a bind argument. .. seealso:: :class:`.DDLEvents` :ref:`event_toplevel` z4Expected a string or unicode SQL statement, got '%r'N)r*r r+r ArgumentError statementcontextr3)r rDrEr%rrr__init__,s$  z DDL.__init__c s8dtjtdtjgfdddDfS)Nz <%s@%s; %s>, cs(g|] }t|rd|t|fqS)z%s=%r)getattr).0keyr4rr as z DDL.__repr__..)r>rE)typeridjoinreprrDr4rr4r__repr__[s  z DDL.__repr__)NN) rrrr<__visit_name__r deprecated_paramsrFrPrrrrr@s# (r@c@s:eZdZdZejddd ddZedd Zd d Z dS) _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. )rAzbThe :paramref:`_ddl.DDLElement.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.rBNFcCs,||_|r||_n |r||_||_||_dSr)elementr% if_exists if_not_exists)r rTr%rUrV _legacy_bindrrrrFtsz_CreateDropBase.__init__cCs|jjSr)rTZcreate_drop_stringify_dialectr4rrrstringify_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 compilerrrr_create_rule_disablesz$_CreateDropBase._create_rule_disable)NFFN) rrrr<r rRrFr?rXrZrrrrrSjs    rScs&eZdZdZdZdfdd ZZS) CreateSchemazcRepresent a CREATE SCHEMA statement. The argument here is the string name of the schema. Z create_schemaNc s||_tt|j|f|dS)z.Create a new :class:`.CreateSchema` construct.N)quotesuperr[rF)r r,r\rr6rrrFszCreateSchema.__init__)Nrrrr<rQrF __classcell__rrr^rr[sr[cs&eZdZdZdZdfdd ZZS) DropSchemazaRepresent a DROP SCHEMA statement. The argument here is the string name of the schema. Z drop_schemaNFc s$||_||_tt|j|f|dS)z,Create a new :class:`.DropSchema` construct.N)r\cascader]rarF)r r,r\rbrr^rrrFszDropSchema.__init__)NFr_rrr^rrasracs2eZdZdZdZejddd fdd ZZS) CreateTablez#Represent a CREATE TABLE statement.Z create_table)rAzcThe :paramref:`_ddl.CreateTable.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.rBNFcs2tt|j|||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 bind: See the description for 'bind' 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. .. versionadded:: 1.0.0 :param if_not_exists: if True, an IF NOT EXISTS operator will be applied to the construct. .. versionadded:: 1.4.0b2 rWrVcSsg|] }t|qSr) CreateColumn)rIcolumnrrrrKsz(CreateTable.__init__..N)r]rcrFcolumnsinclude_foreign_key_constraints)r rTr%rhrVr^rrrFs! zCreateTable.__init__)NNF rrrr<rQr rRrFr`rrr^rrcs rcc@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_viewNrrrr<rQrrrrrjsrjc@seZdZdZdZddZdS)reaRepresent 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 ||_dSr)rT)r rTrrrrF]szCreateColumn.__init__N)rrrr<rQrFrrrrresfrecs2eZdZdZdZejddd fdd ZZS) DropTablez!Represent a DROP TABLE statement.Z drop_table)rAzaThe :paramref:`_ddl.DropTable.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.rBNFcstt|j|||ddS)aCreate 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 bind: See the description for 'bind' in :class:`.DDL`. :param if_exists: if True, an IF EXISTS operator will be applied to the construct. .. versionadded:: 1.4.0b2 rWrUN)r]rlrFr rTr%rUr^rrrFfs  zDropTable.__init__)NFrirrr^rrlas rlc@seZdZdZdZdS)CreateSequencez&Represent a CREATE SEQUENCE statement.Zcreate_sequenceNrkrrrrrosroc@seZdZdZdZdS) DropSequencez$Represent a DROP SEQUENCE statement.Z drop_sequenceNrkrrrrrpsrpcs2eZdZdZdZejddd fdd ZZS) CreateIndexz#Represent a CREATE INDEX statement.Z create_index)rAzcThe :paramref:`_ddl.CreateIndex.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.rBNFcstt|j|||ddS)aCreate a :class:`.Createindex` construct. :param element: a :class:`_schema.Index` that's the subject of the CREATE. :param on: See the description for 'on' in :class:`.DDL`. :param bind: See the description for 'bind' in :class:`.DDL`. :param if_not_exists: if True, an IF NOT EXISTS operator will be applied to the construct. .. versionadded:: 1.4.0b2 rdN)r]rqrF)r rTr%rVr^rrrFs  zCreateIndex.__init__)NFrirrr^rrqs rqcs2eZdZdZdZejddd fdd ZZS) DropIndexz!Represent a DROP INDEX statement.Z drop_index)rAzaThe :paramref:`_ddl.DropIndex.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.rBNFcstt|j|||ddS)aCreate a :class:`.DropIndex` construct. :param element: a :class:`_schema.Index` that's the subject of the DROP. :param on: See the description for 'on' in :class:`.DDL`. :param bind: See the description for 'bind' in :class:`.DDL`. :param if_exists: if True, an IF EXISTS operator will be applied to the construct. .. versionadded:: 1.4.0b2 rmN)r]rrrFrnr^rrrFs  zDropIndex.__init__)NFrirrr^rrrs rrcs$eZdZdZdZfddZZS) AddConstraintz2Represent an ALTER TABLE ADD CONSTRAINT statement.Zadd_constraintcs*tt|j|f||t|j|_dSr)r]rsrFr portable_instancemethodrZ _create_rule)r rTargsrr^rrrFszAddConstraint.__init__r_rrr^rrssrscs&eZdZdZdZdfdd ZZS)DropConstraintz3Represent an ALTER TABLE DROP CONSTRAINT statement.Zdrop_constraintFc s,||_tt|j|f|t|j|_dSr)rbr]rwrFr rtrZru)r rTrbrr^rrrFs zDropConstraint.__init__)Fr_rrr^rrwsrwc@seZdZdZdZdS)SetTableCommentz*Represent a COMMENT ON TABLE IS statement.Zset_table_commentNrkrrrrrxsrxc@seZdZdZdZdS)DropTableCommentzfRepresent a COMMENT ON TABLE '' statement. Note this varies a lot across database backends. Zdrop_table_commentNrkrrrrrysryc@seZdZdZdZdS)SetColumnCommentz+Represent a COMMENT ON COLUMN IS statement.Zset_column_commentNrkrrrrrzsrzc@seZdZdZdZdS)DropColumnCommentz0Represent a COMMENT ON COLUMN IS NULL statement.Zdrop_column_commentNrkrrrrr{sr{c@seZdZddZdS)DDLBasecCs ||_dSr)r)r rrrrrFszDDLBase.__init__N)rrrrFrrrrr|sr|csdeZdZdfdd ZddZddZd d Zd d Zdd dZddZ dddZ dddZ Z S)SchemaGeneratorFNc s8tt|j|f|||_||_|j|_||_i|_dSr) r]r}rF checkfirsttablesidentifier_preparerpreparerrmemor rrr~rkwargsr^rrrFs zSchemaGenerator.__init__cCsJ|j|j|j|}|r*|j||j pH|jj|j|j|d SN)Zschemarvalidate_identifierr,rschema_for_objectr~Z has_tabler tableeffective_schemarrr_can_create_tables  z!SchemaGenerator._can_create_tablecCsD|j|j}|r|j||j pB|jj|j|jj|j|d Srrrrrrr~Z has_indexr,r indexrrrr_can_create_indexs z!SchemaGenerator._can_create_indexcCsF|j|}|jjoD|jj s&|j oD|j pD|jj|j|j|d Sr rrrZsupports_sequencesZsequences_optionaloptionalr~Z has_sequencer,r sequencerrrr_can_create_sequence#s z$SchemaGenerator._can_create_sequencec sjdk rj}nt|j}tfdd|D}fdd|jD}dd|D}|jj|j|jd|D]}j |ddqz|D]8\}}|dk rj |d|ddq|D]} | qq|jj |j|jddS) Ncsg|]}|r|qSr)rrItr4rrrK7s z2SchemaGenerator.visit_metadata..cs$g|]}|jdkr|r|qSr)rfrrIr:r4rrrK:s cSsg|]\}}|dk r|qSrrrIrZfksrrrrK@srr~ _ddl_runnerT create_ok)rrh_is_metadata_operation) rr.valuessort_tables_and_constraints _sequencesdispatch before_createrr~traverse_single after_create) r metadatar collectionseq_collevent_collectionseqrfkcsfkcrr4rvisit_metadata0sH   zSchemaGenerator.visit_metadatacCs|s||sdS|jj||j|j||d|jD]}|jdk r2||jq2|jj sZd}|j t ||dt |dr|j D]}|j|ddq~|jjr|jjs|jdk r|j t||jD]}|jdk r|j t|q|jj||j|j||ddS)Nr~rr)rhindexesTr)rrrrr~rgdefaultrrsupports_alterr rchasattrrZsupports_commentsZinline_commentscommentrxrzr)r rrrhrrfrrrr visit_table`sH       zSchemaGenerator.visit_tablecCs |jjs dS|jt|dSr)rrrr rsr constraintrrrvisit_foreign_key_constraintsz,SchemaGenerator.visit_foreign_key_constraintcCs&|s||sdS|jt|dSr)rrr ro)r rrrrrvisit_sequenceszSchemaGenerator.visit_sequencecCs&|s||sdS|jt|dSr)rrr rq)r rrrrr visit_indexszSchemaGenerator.visit_index)FN)FNF)F)F) rrrrFrrrrrrrrr`rrr^rr}s    3 8 r}csjeZdZdfdd ZddZddZd d Zd d Zdd dZddgfddZ ddZ dddZ Z S) SchemaDropperFNc s8tt|j|f|||_||_|j|_||_i|_dSr) r]rrFr~rrrrrrr^rrrFs zSchemaDropper.__init__c sjdk rj}nt|j}z2fdd|D}ttt|fddd}Wntjk r}zjjst dd t dd|j Dd d|D}n@t jtj|jd |j |jd d t d d|j Dd |dW5d}~XYnXfdd|jD}dd|D}|jj|j|jd|D]>\}} |dk r^j|dd|dn| D]} | qbq8|D]} j| | jdkdq||jj|j|jddS)Ncsg|]}|r|qSr)_can_drop_tablerr4rrrKs z0SchemaDropper.visit_metadata..csjjr|jdkrdSdSNF)rrr,)rr4rrs 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.rGcSsg|] }|jqSrfullnamerrrrrKscSsg|] }|dfqS)rrrrrrrKszCan'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|] }|jqSrrrrrrrKs)msg)from_csg|]}|r|qSr)_can_drop_sequencerr4rrrKs cSsg|]\}}|dk r|qSrrrrrrrKsrT)drop_okr_ignore_sequences)r)rr.rreversedrr CircularDependencyErrorrrr warnrNsortedcyclesZraise_rvedgesrr before_droprr~rrf after_drop) r rrZunsorted_tablesrZerr2rrrrrrrr4rrs       zSchemaDropper.visit_metadatacCsH|j|j|j|}|r*|j||j pF|jj|j|j|dSrrrrrrrs  zSchemaDropper._can_drop_tablecCsB|j|j}|r|j||j p@|jj|j|jj|j|dSrrrrrr_can_drop_indexs zSchemaDropper._can_drop_indexcCsD|j|}|jjoB|jj s&|j oB|j pB|jj|j|j|dSrrrrrrr%s z SchemaDropper._can_drop_sequencecCs&|s||sdS|jt|dSr)rrr rr)r rrrrrr1szSchemaDropper.visit_indexcCs|s||sdS|jj||j|j||d|jt||jD]$}|jdk rB|j|krB| |jqB|jj ||j|j||ddS)Nr) rrrrr~r rlrgrrr)r rrrrrfrrrr7s. zSchemaDropper.visit_tablecCs |jjs dS|jt|dSr)rrrr rwrrrrr_sz*SchemaDropper.visit_foreign_key_constraintcCs&|s||sdS|jt|dSr)rrr rp)r rrrrrrdszSchemaDropper.visit_sequence)FN)F)F) rrrrFrrrrrrrrr`rrr^rrs ^    (rNcs4dk rfdd}nd}ddt|||ddDS)a Sort a collection of :class:`_schema.Table` objects based on dependency. This is a dependency-ordered sort which will emit :class:`_schema.Table` objects such that they will follow their dependent :class:`_schema.Table` objects. Tables are dependent on another based on the presence of :class:`_schema.ForeignKeyConstraint` objects as well as explicit dependencies added by :meth:`_schema.Table.add_is_dependent_on`. .. warning:: The :func:`._schema.sort_tables` function cannot by itself accommodate automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. When these cycles are detected, the foreign keys of these tables are omitted from consideration in the sort. A warning is emitted when this condition occurs, which will be an exception raise in a future release. Tables which are not part of the cycle will still be returned in dependency order. To resolve these cycles, the :paramref:`_schema.ForeignKeyConstraint.use_alter` parameter may be applied to those constraints which create a cycle. Alternatively, the :func:`_schema.sort_tables_and_constraints` function will automatically return foreign key constraints in a separate collection when cycles are detected so that they may be applied to a schema separately. .. versionchanged:: 1.3.17 - a warning is emitted when :func:`_schema.sort_tables` cannot perform a proper sort due to cyclical dependencies. This will be an exception in a future release. Additionally, the sort will continue to return other tables not involved in the cycle in dependency order which was not the case previously. :param tables: a sequence of :class:`_schema.Table` objects. :param skip_fn: optional callable which will be passed a :class:`_schema.ForeignKey` object; if it returns True, this constraint will not be considered as a dependency. Note this is **different** from the same parameter in :func:`.sort_tables_and_constraints`, which is instead passed the owning :class:`_schema.ForeignKeyConstraint` object. :param extra_dependencies: a sequence of 2-tuples of tables which will also be considered as dependent on each other. .. seealso:: :func:`.sort_tables_and_constraints` :attr:`_schema.MetaData.sorted_tables` - uses this function to sort Ncs|jD]}|rdSqdS)NT)elements)rZfkskip_fnrr_skip_fns zsort_tables.._skip_fncSsg|]\}}|dk r|qSrr)rIrrrrrrKszsort_tables..T)rextra_dependencies_warn_for_cycles)r)rrrrrrr sort_tablesks?rFc 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. .. versionadded:: 1.0.0 .. seealso:: :func:`.sort_tables` NTc3s|]}|fVqdSrr)rIparent)rrr sz.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.rGcss|] }|jVqdSrrrrrrrsrcs$g|]}dks|dk r|qSrr)rIrrrrrK$s z/sort_tables_and_constraints..csg|]}||jfqSr)foreign_key_constraints difference)rIr)remaining_fkcsrrrK5s)r/updaterZ use_alteraddZreferred_tableZ_extra_dependenciesr.r sortr=r rr rrNrrrdiscard) rrrrZfixed_dependenciesZmutable_dependenciesrfilteredZ dependent_onZcandidate_sorterrZedgeZ can_remover)rrrrrsv0              r)NN)NNF)'r<rbaserrrrrrr r r r ZDDLRolerr@rSr[rarcrjrerlrorprqrrrsrwrxryrzr{r|r}rrrrrrrsT          dd1- m   %F X