o znh@sdZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd l m Z Gd d d eZ Gdddee 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/eZGd0d1d1eZGd2d3d3eZ Gd4d5d5eZ!Gd6d7d7e!Z"Gd8d9d9e!Z#d?d;d<Z$ :d?d=d>Z%d:S)@zq Provides the hierarchy of DDL-defining schema items as well as routines to invoke them for a create/drop call. )_bind_or_error) _generative) Executable) SchemaVisitor) ClauseElement)event)exc)util) topologicalc@eZdZddZdS) _DDLCompilescKs|j||fi|S)zNReturn a compiler appropriate for this ClauseElement, given a Dialect.) ddl_compiler)selfdialectkwr=/usr/local/lib/python3.10/dist-packages/sqlalchemy/sql/ddl.py _compilersz_DDLCompiles._compilerN)__name__ __module__ __qualname__rrrrrr  r c@seZdZdZejddiZdZdZdZ dZ ddZ dddZ e d d d d Zed dZed ddZddZddZddZddZddZddZeeeZddZdS)! 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` autocommitTNcCs||||SN) _execute_ddl)r connection multiparamsparamsrrr_execute_on_connectionGsz!DDLElement._execute_on_connectioncCs>|durt|}|||r|||S|jjddS)a Execute 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 SchemaItem for the execute call. Will be passed to the ``on`` callable if any, and may also provide string expansion data for the statement. See ``execute_at`` for more information. Nz(DDL execution skipped, criteria not met.)r_should_executeexecuteagainstengineloggerinfo)rbindtargetrrrr"Js  zDDLElement.execute0.7zThe :meth:`.DDLElement.execute_at` method is deprecated and will be removed in a future release. Please use the :class:`.DDLEvents` listener interface in conjunction with the :meth:`.DDLElement.execute_if` method.cs,fdd}t|ddd|dS)aQLink execution of this DDL to the DDL lifecycle of a SchemaItem. Links this ``DDLElement`` to a ``Table`` or ``MetaData`` instance, executing it when that schema item is created or dropped. The DDL statement will be executed using the same Connection and transactional context as the Table create/drop itself. The ``.bind`` property of this statement is ignored. :param event: One of the events defined in the schema item's ``.ddl_events``; e.g. 'before-create', 'after-create', 'before-drop' or 'after-drop' :param target: The Table or MetaData instance for which this DDLElement will be associated with. A DDLElement instance can be linked to any number of schema items. ``execute_at`` builds on the ``append_ddl_listener`` interface of :class:`.MetaData` and :class:`.Table` objects. Caveat: Creating or dropping a Table in isolation will also trigger any DDL set to ``execute_at`` that Table's MetaData. This may change in a future release. cs*j||fi|r||SdSr)_should_execute_deprecatedr"r#)r(rr event_namerrr call_eventsz)DDLElement.execute_at..call_event-_N)rlistenreplace)rr,r(r-rr+r execute_aths#zDDLElement.execute_atcCs ||_dS)z9Return a copy of this DDL against a specific schema item.N)r()rr(rrrr#s zDDLElement.againstcCs||_||_||_dS)aReturn a callable that will execute this DDLElement conditionally. 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, tuple or a callable predicate. 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:`.Table` or :class:`.MetaData` object which is the target of this event. May be None if the DDL is executed explicitly. :bind: The :class:`.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)rrr4r5rrr execute_ifsA zDDLElement.execute_ifcKs|jdur|jd||fi|sdSt|jtjr#|j|jjkr"dSnt|jtt t fr5|jj|jvr5dS|j durJ|j |||fd|j i|sJdSdS)NFr5T) onr* isinstancerr string_typesr$nametuplelistsetr4r5rr(r'rrrrr!s,zDDLElement._should_executecKsb|jdurdSt|jtjr|j|jjkSt|jtttfr%|jj|jvS|j||||fi|SNT) r7r8r r9r$r:r;r<r=)rrr(r'rrrrr*s z%DDLElement._should_execute_deprecatedcKs(|j||fi|r|||SdS)z"Execute the DDL as a ddl_listener.N)r!r"r#r>rrr__call__szDDLElement.__call__cCsH|durt|tjtttfs t|s"tdt |j dSdSdS)NzjExpected the name of a database dialect, a tuple of names, or a callable for 'on' criteria, got type '%s'.) r8r r9r;r<r=callabler ArgumentErrortyper)rr7rrr _check_ddl_ons zDDLElement._check_ddl_oncCs|jr|jSdSr_bindrrrrr' szDDLElement.bindcC ||_dSrrE)rr'rrr _set_bind zDDLElement._set_bindcCs|j|j}|j|_|Sr) __class____new____dict__copy)rsrrr _generates zDDLElement._generateNNNNN)rrr__doc__r_execution_optionsunionr(r7rr4r r"r deprecatedr3rr#r6r!r*r@rDr'rIpropertyrPrrrrr s8  $  D    rc@s2eZdZdZdZejddd ddZdd ZdS) DDLa1A 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:`.Table` or :class:`.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. ddl)r)zThe :paramref:`.DDL.on` parameter is deprecated and will be removed in a future release. Please refer to :meth:`.DDLElement.execute_if`.)r7NcCsDt|tjs td|||_|pi|_||||_||_ 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 on: Optional filtering criteria. May be a string, tuple or a callable predicate. If a string, it will be compared to the name of the executing database dialect:: DDL('something', on='postgresql') If a tuple, specifies multiple dialect names:: DDL('something', on=('postgresql', 'mysql')) If a callable, it will be invoked with four positional arguments as well as optional keyword arguments: :ddl: This DDL element. :event: The name of the event that has triggered this DDL, such as 'after-create' Will be None if the DDL is executed explicitly. :target: The ``Table`` or ``MetaData`` object which is the target of this event. May be None if the DDL is executed explicitly. :connection: The ``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. If the callable returns a true value, the DDL statement will be executed. :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) r8r r9r rB statementcontextrDr7rF)rrZr7r[r'rrr__init__@s K   z DDL.__init__c s8dtjtdtjgfdddDfS)Nz <%s@%s; %s>, cs(g|]}t|rd|t|fqS)z%s=%r)getattr).0keyrGrr s z DDL.__repr__..)r7r[)rCridjoinreprrZrGrrGr__repr__s  z DDL.__repr__rR) rrrrS__visit_name__r deprecated_paramsr\rerrrrrXs"  PrXc@s"eZdZdZdddZddZdS)_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. NcCs ||_||||_||_dSr)elementrDr7r')rrir7r'rrrr\s  z_CreateDropBase.__init__cCsdS)zAllow disable of _create_rule using a callable. Pass to _create_rule using util.portable_instancemethod(self._create_rule_disable) to retain serializability. Fr)rcompilerrrr_create_rule_disablesz$_CreateDropBase._create_rule_disablerQ)rrrrSr\rkrrrrrhs rhc&eZdZdZdZdfdd ZZS) CreateSchemazcRepresent a CREATE SCHEMA statement. The argument here is the string name of the schema. create_schemaNc s"||_tt|j|fi|dS)z.Create a new :class:`.CreateSchema` construct.N)quotesuperrmr\)rr:rorrKrrr\szCreateSchema.__init__rrrrrSrfr\ __classcell__rrrqrrmrmcs&eZdZdZdZdfdd ZZS) DropSchemazaRepresent a DROP SCHEMA statement. The argument here is the string name of the schema. drop_schemaNFc s(||_||_tt|j|fi|dS)z,Create a new :class:`.DropSchema` construct.N)rocascaderprur\)rr:rorwrrqrrr\szDropSchema.__init__NFrrrrrqrrurtrucs(eZdZdZdZ dfdd ZZS) CreateTablez#Represent a CREATE TABLE statement. create_tableNcs2tt|j|||ddd|jD|_||_dS)aLCreate a :class:`.CreateTable` construct. :param element: a :class:`.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:`.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 )r7r'cSsg|]}t|qSr) CreateColumn)r_columnrrrraz(CreateTable.__init__..N)rpryr\columnsinclude_foreign_key_constraints)rrir7r'rrqrrr\s zCreateTable.__init__rRrrrrrqrrys ryc@eZdZdZdZdS) _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. drop_viewNrrrrSrfrrrrrsrc@seZdZdZdZddZdS)r{a\Represent a :class:`.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:`.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:`.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:`.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:`.Column`, which marks a column as an implicitly-present "system" column. For example, suppose we wish to produce a :class:`.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. create_columncCrHr)ri)rrirrrr\nrJzCreateColumn.__init__N)rrrrSrfr\rrrrr{ sb r{c@r) DropTablez!Represent a DROP TABLE statement. drop_tableNrrrrrrrrc@r)CreateSequencez&Represent a CREATE SEQUENCE statement.create_sequenceNrrrrrrxrrc@r) DropSequencez$Represent a DROP SEQUENCE statement. drop_sequenceNrrrrrr~rrc@r) CreateIndexz#Represent a CREATE INDEX statement. create_indexNrrrrrrrrc@r) DropIndexz!Represent a DROP INDEX statement. drop_indexNrrrrrrrrcs$eZdZdZdZfddZZS) AddConstraintz2Represent an ALTER TABLE ADD CONSTRAINT statement.add_constraintcs0tt|j|g|Ri|t|j|_dSr)rprr\r portable_instancemethodrk _create_rule)rriargsrrqrrr\s zAddConstraint.__init__rrrrrqrrsrcrl)DropConstraintz3Represent an ALTER TABLE DROP CONSTRAINT statement.drop_constraintFc s0||_tt|j|fi|t|j|_dSr)rwrprr\r rrkr)rrirwrrqrrr\s  zDropConstraint.__init__Frrrrrqrrsrc@r)SetTableCommentz*Represent a COMMENT ON TABLE IS statement.set_table_commentNrrrrrrrrc@r)DropTableCommentzfRepresent a COMMENT ON TABLE '' statement. Note this varies a lot across database backends. drop_table_commentNrrrrrrsrc@r)SetColumnCommentz+Represent a COMMENT ON COLUMN IS statement.set_column_commentNrrrrrrrrc@r)DropColumnCommentz0Represent a COMMENT ON COLUMN IS NULL statement.drop_column_commentNrrrrrrrrc@r )DDLBasecCrHr)r)rrrrrr\rJzDDLBase.__init__N)rrrr\rrrrrrrcsbeZdZ dfdd ZddZddZd d Z   dd d Zd dZdddZ ddZ Z S)SchemaGeneratorFNc <tt|j|fi|||_||_|j|_||_i|_dSr) rprr\ checkfirsttablesidentifier_preparerpreparerrmemorrrrrkwargsrqrrr\  zSchemaGenerator.__init__cCsJ|j|j|j|}|r|j||j p$|jj|j|j|d SN)schemarvalidate_identifierr:rschema_for_objectr has_tablertableeffective_schemarrr_can_create_tables   z!SchemaGenerator._can_create_tablecCsF|j|}|jjo"|jj s|j o"|j p"|jj|j|j|d Sr rrrsupports_sequencessequences_optionaloptionalr has_sequencer:rsequencerrrr_can_create_sequences  z$SchemaGenerator._can_create_sequencec sjdur j}nt|j}tfdd|D}fdd|jD}dd|D}|jj|j|jd|D] }j |ddq=|D]\}}|dur[j |d|ddqI|D]} | q]qI|jj |j|jddS) Ncg|] }|r|qSr)rr_trGrrraz2SchemaGenerator.visit_metadata..c$g|]}|jdur|r|qSr)r|rr_rOrGrrra cSg|] \}}|dur|qSrrr_rfksrrrrarr _ddl_runnerT) create_ok)rr_is_metadata_operation) rr<valuessort_tables_and_constraints _sequencesdispatch before_createrrtraverse_single after_create) rmetadatar collectionseq_collevent_collectionseqrfkcsfkcrrGrvisit_metadatasJ     zSchemaGenerator.visit_metadatacCs|s ||s dS|jj||j|j||d|jD] }|jdur&||jq|jj s-d}|j t ||dt |drG|j D]}||q?|jjro|jjso|jdur\|j t||jD]}|jdurn|j t|q_|jj||j|j||ddS)Nrrr)rindexes)rrrrrr~defaultrrsupports_alterr"ryhasattrrsupports_commentsinline_commentscommentrrr)rrrrrr|indexrrr visit_tablesL         zSchemaGenerator.visit_tablecC |jjsdS|jt|dSr)rrrr"rr constraintrrrvisit_foreign_key_constraintSz,SchemaGenerator.visit_foreign_key_constraintcC&|s ||s dS|jt|dSr)rrr"r)rrrrrrvisit_sequenceXszSchemaGenerator.visit_sequencecC|jt|dSr)rr"rrrrrr visit_index]zSchemaGenerator.visit_indexFN)FNFr) rrrr\rrrrrrrrsrrrqrrs   3 8 rcs\eZdZ dfdd ZddZddZd d Zd d Zdd dZddZ dddZ Z S) SchemaDropperFNc rr) rprr\rrrrrrrrqrrr\brzSchemaDropper.__init__c sjdur j}nt|j}zfdd|D}ttt|fddd}WnOtjyx}zBjjsPt dd t dd|j Dd d|D}nt tj|jd |j |jd d t d d|j Dd WYd}~nd}~wwfdd|jD}dd|D}|jj|j|jd|D]\}} |durj|dddq| D]} | qq|D] } j| ddq|jj|j|jddS)Ncrr)_can_drop_tablerrGrrrasrz0SchemaDropper.visit_metadata..csjjr |jdur dSdSrx)rrr:)rrGrrxs  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.r]cSg|]}|jqSrfullnamerrrrracSsg|]}|dfqS)rrrrrrrar}zCan'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.cSrrrrrrrrar)msgcrr)r|_can_drop_sequencerrGrrrarcSrrrrrrrrarrT)drop_okr)r)rr<rreversedrr CircularDependencyErrorrrr warnrcsortedcyclesraise_from_causeredgesrr before_droprrr after_drop) rrrunsorted_tablesrerr2rrrrrrrrGrrls~     #   zSchemaDropper.visit_metadatacCsH|j|j|j|}|r|j||j p#|jj|j|j|dSrrrrrrrs   zSchemaDropper._can_drop_tablecCsD|j|}|jjo!|jj s|j o!|j p!|jj|j|j|dSrrrrrrrs  z SchemaDropper._can_drop_sequencecCrr)rr"rrrrrrrzSchemaDropper.visit_indexcCs||s ||s dS|jj||j|j||d|jt||jD] }|jdur.| |jq!|jj ||j|j||ddS)Nr) rrrrrr"rr~rrr)rrrrr|rrrrs*    zSchemaDropper.visit_tablecCrr)rrrr"rrrrrrrz*SchemaDropper.visit_foreign_key_constraintcCrr)rrr"r)rrrrrrrszSchemaDropper.visit_sequencer)FFr) rrrr\rrrrrrrrsrrrqrras Z  rNcs2dur fdd}nd}ddt|||dDS)a]sort a collection of :class:`.Table` objects based on dependency. This is a dependency-ordered sort which will emit :class:`.Table` objects such that they will follow their dependent :class:`.Table` objects. Tables are dependent on another based on the presence of :class:`.ForeignKeyConstraint` objects as well as explicit dependencies added by :meth:`.Table.add_is_dependent_on`. .. warning:: The :func:`.sort_tables` function cannot by itself accommodate automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. To resolve these cycles, either the :paramref:`.ForeignKeyConstraint.use_alter` parameter may be applied to those constraints, or use the :func:`.sql.sort_tables_and_constraints` function which will break out foreign key constraints involved in cycles separately. :param tables: a sequence of :class:`.Table` objects. :param skip_fn: optional callable which will be passed a :class:`.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:`.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` :meth:`.MetaData.sorted_tables` - uses this function to sort Ncs|jD] }|r dSqdSr?)elements)rfkskip_fnrr_skip_fn4s zsort_tables.._skip_fncSrrr)r_rrrrrra>s zsort_tables..)rextra_dependencies)r)rr rr rr r sort_tables s)rc st}t}|dur||t|D]>jD]+}|jdur&|qr6|}|dur6|q|j}|urD||fq|fddjDqzttj | ||dd}WnPt j y} zC| j D],} | |vr| dfddjD} | | D]}|j}|ur||fqqnttj | ||dd}WYd} ~ nd} ~ wwfd d|DdtfgS) asort a collection of :class:`.Table` / :class:`.ForeignKeyConstraint` objects. This is a dependency-ordered sort which will emit tuples of ``(Table, [ForeignKeyConstraint, ...])`` such that each :class:`.Table` follows its dependent :class:`.Table` objects. Remaining :class:`.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:`.ForeignKeyConstraint` objects, explicit dependencies added by :meth:`.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:`.Table` objects. :param filter_fn: optional callable which will be passed a :class:`.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)r_parent)rrr s z.sort_tables_and_constraints..)deterministic_orderrcs$g|]}dus|dur|qSrxr)r_rrrrrarz/sort_tables_and_constraints..csg|] }||jfqSr)foreign_key_constraints difference)r_r)remaining_fkcsrrras)r=updater use_alteraddreferred_table_extra_dependenciesr<r sortrUr rrdiscard) rrrfixed_dependenciesmutable_dependenciesrfiltered dependent_oncandidate_sorterredge can_remover)rrrrrGsr+           rrQ)&rSbaserrrrr rr.rr r r r rrXrhrmruryrr{rrrrrrrrrrrrrrrrrrrrsP         |  i    )?