ddl.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. # sql/ddl.py
  2. # Copyright (C) 2009-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. """
  9. Provides the hierarchy of DDL-defining schema items as well as routines
  10. to invoke them for a create/drop call.
  11. """
  12. from __future__ import annotations
  13. import contextlib
  14. import typing
  15. from typing import Any
  16. from typing import Callable
  17. from typing import Generic
  18. from typing import Iterable
  19. from typing import List
  20. from typing import Optional
  21. from typing import Sequence as typing_Sequence
  22. from typing import Tuple
  23. from typing import TypeVar
  24. from typing import Union
  25. from . import roles
  26. from .base import _generative
  27. from .base import Executable
  28. from .base import SchemaVisitor
  29. from .elements import ClauseElement
  30. from .. import exc
  31. from .. import util
  32. from ..util import topological
  33. from ..util.typing import Protocol
  34. from ..util.typing import Self
  35. if typing.TYPE_CHECKING:
  36. from .compiler import Compiled
  37. from .compiler import DDLCompiler
  38. from .elements import BindParameter
  39. from .schema import Column
  40. from .schema import Constraint
  41. from .schema import ForeignKeyConstraint
  42. from .schema import Index
  43. from .schema import SchemaItem
  44. from .schema import Sequence as Sequence # noqa: F401
  45. from .schema import Table
  46. from .selectable import TableClause
  47. from ..engine.base import Connection
  48. from ..engine.interfaces import CacheStats
  49. from ..engine.interfaces import CompiledCacheType
  50. from ..engine.interfaces import Dialect
  51. from ..engine.interfaces import SchemaTranslateMapType
  52. _SI = TypeVar("_SI", bound=Union["SchemaItem", str])
  53. class BaseDDLElement(ClauseElement):
  54. """The root of DDL constructs, including those that are sub-elements
  55. within the "create table" and other processes.
  56. .. versionadded:: 2.0
  57. """
  58. _hierarchy_supports_caching = False
  59. """disable cache warnings for all _DDLCompiles subclasses. """
  60. def _compiler(self, dialect, **kw):
  61. """Return a compiler appropriate for this ClauseElement, given a
  62. Dialect."""
  63. return dialect.ddl_compiler(dialect, self, **kw)
  64. def _compile_w_cache(
  65. self,
  66. dialect: Dialect,
  67. *,
  68. compiled_cache: Optional[CompiledCacheType],
  69. column_keys: List[str],
  70. for_executemany: bool = False,
  71. schema_translate_map: Optional[SchemaTranslateMapType] = None,
  72. **kw: Any,
  73. ) -> Tuple[
  74. Compiled, Optional[typing_Sequence[BindParameter[Any]]], CacheStats
  75. ]:
  76. raise NotImplementedError()
  77. class DDLIfCallable(Protocol):
  78. def __call__(
  79. self,
  80. ddl: BaseDDLElement,
  81. target: Union[SchemaItem, str],
  82. bind: Optional[Connection],
  83. tables: Optional[List[Table]] = None,
  84. state: Optional[Any] = None,
  85. *,
  86. dialect: Dialect,
  87. compiler: Optional[DDLCompiler] = ...,
  88. checkfirst: bool,
  89. ) -> bool: ...
  90. class DDLIf(typing.NamedTuple):
  91. dialect: Optional[str]
  92. callable_: Optional[DDLIfCallable]
  93. state: Optional[Any]
  94. def _should_execute(
  95. self,
  96. ddl: BaseDDLElement,
  97. target: Union[SchemaItem, str],
  98. bind: Optional[Connection],
  99. compiler: Optional[DDLCompiler] = None,
  100. **kw: Any,
  101. ) -> bool:
  102. if bind is not None:
  103. dialect = bind.dialect
  104. elif compiler is not None:
  105. dialect = compiler.dialect
  106. else:
  107. assert False, "compiler or dialect is required"
  108. if isinstance(self.dialect, str):
  109. if self.dialect != dialect.name:
  110. return False
  111. elif isinstance(self.dialect, (tuple, list, set)):
  112. if dialect.name not in self.dialect:
  113. return False
  114. if self.callable_ is not None and not self.callable_(
  115. ddl,
  116. target,
  117. bind,
  118. state=self.state,
  119. dialect=dialect,
  120. compiler=compiler,
  121. **kw,
  122. ):
  123. return False
  124. return True
  125. class ExecutableDDLElement(roles.DDLRole, Executable, BaseDDLElement):
  126. """Base class for standalone executable DDL expression constructs.
  127. This class is the base for the general purpose :class:`.DDL` class,
  128. as well as the various create/drop clause constructs such as
  129. :class:`.CreateTable`, :class:`.DropTable`, :class:`.AddConstraint`,
  130. etc.
  131. .. versionchanged:: 2.0 :class:`.ExecutableDDLElement` is renamed from
  132. :class:`.DDLElement`, which still exists for backwards compatibility.
  133. :class:`.ExecutableDDLElement` integrates closely with SQLAlchemy events,
  134. introduced in :ref:`event_toplevel`. An instance of one is
  135. itself an event receiving callable::
  136. event.listen(
  137. users,
  138. "after_create",
  139. AddConstraint(constraint).execute_if(dialect="postgresql"),
  140. )
  141. .. seealso::
  142. :class:`.DDL`
  143. :class:`.DDLEvents`
  144. :ref:`event_toplevel`
  145. :ref:`schema_ddl_sequences`
  146. """
  147. _ddl_if: Optional[DDLIf] = None
  148. target: Union[SchemaItem, str, None] = None
  149. def _execute_on_connection(
  150. self, connection, distilled_params, execution_options
  151. ):
  152. return connection._execute_ddl(
  153. self, distilled_params, execution_options
  154. )
  155. @_generative
  156. def against(self, target: SchemaItem) -> Self:
  157. """Return a copy of this :class:`_schema.ExecutableDDLElement` which
  158. will include the given target.
  159. This essentially applies the given item to the ``.target`` attribute of
  160. the returned :class:`_schema.ExecutableDDLElement` object. This target
  161. is then usable by event handlers and compilation routines in order to
  162. provide services such as tokenization of a DDL string in terms of a
  163. particular :class:`_schema.Table`.
  164. When a :class:`_schema.ExecutableDDLElement` object is established as
  165. an event handler for the :meth:`_events.DDLEvents.before_create` or
  166. :meth:`_events.DDLEvents.after_create` events, and the event then
  167. occurs for a given target such as a :class:`_schema.Constraint` or
  168. :class:`_schema.Table`, that target is established with a copy of the
  169. :class:`_schema.ExecutableDDLElement` object using this method, which
  170. then proceeds to the :meth:`_schema.ExecutableDDLElement.execute`
  171. method in order to invoke the actual DDL instruction.
  172. :param target: a :class:`_schema.SchemaItem` that will be the subject
  173. of a DDL operation.
  174. :return: a copy of this :class:`_schema.ExecutableDDLElement` with the
  175. ``.target`` attribute assigned to the given
  176. :class:`_schema.SchemaItem`.
  177. .. seealso::
  178. :class:`_schema.DDL` - uses tokenization against the "target" when
  179. processing the DDL string.
  180. """
  181. self.target = target
  182. return self
  183. @_generative
  184. def execute_if(
  185. self,
  186. dialect: Optional[str] = None,
  187. callable_: Optional[DDLIfCallable] = None,
  188. state: Optional[Any] = None,
  189. ) -> Self:
  190. r"""Return a callable that will execute this
  191. :class:`_ddl.ExecutableDDLElement` conditionally within an event
  192. handler.
  193. Used to provide a wrapper for event listening::
  194. event.listen(
  195. metadata,
  196. "before_create",
  197. DDL("my_ddl").execute_if(dialect="postgresql"),
  198. )
  199. :param dialect: May be a string or tuple of strings.
  200. If a string, it will be compared to the name of the
  201. executing database dialect::
  202. DDL("something").execute_if(dialect="postgresql")
  203. If a tuple, specifies multiple dialect names::
  204. DDL("something").execute_if(dialect=("postgresql", "mysql"))
  205. :param callable\_: A callable, which will be invoked with
  206. three positional arguments as well as optional keyword
  207. arguments:
  208. :ddl:
  209. This DDL element.
  210. :target:
  211. The :class:`_schema.Table` or :class:`_schema.MetaData`
  212. object which is the
  213. target of this event. May be None if the DDL is executed
  214. explicitly.
  215. :bind:
  216. The :class:`_engine.Connection` being used for DDL execution.
  217. May be None if this construct is being created inline within
  218. a table, in which case ``compiler`` will be present.
  219. :tables:
  220. Optional keyword argument - a list of Table objects which are to
  221. be created/ dropped within a MetaData.create_all() or drop_all()
  222. method call.
  223. :dialect: keyword argument, but always present - the
  224. :class:`.Dialect` involved in the operation.
  225. :compiler: keyword argument. Will be ``None`` for an engine
  226. level DDL invocation, but will refer to a :class:`.DDLCompiler`
  227. if this DDL element is being created inline within a table.
  228. :state:
  229. Optional keyword argument - will be the ``state`` argument
  230. passed to this function.
  231. :checkfirst:
  232. Keyword argument, will be True if the 'checkfirst' flag was
  233. set during the call to ``create()``, ``create_all()``,
  234. ``drop()``, ``drop_all()``.
  235. If the callable returns a True value, the DDL statement will be
  236. executed.
  237. :param state: any value which will be passed to the callable\_
  238. as the ``state`` keyword argument.
  239. .. seealso::
  240. :meth:`.SchemaItem.ddl_if`
  241. :class:`.DDLEvents`
  242. :ref:`event_toplevel`
  243. """
  244. self._ddl_if = DDLIf(dialect, callable_, state)
  245. return self
  246. def _should_execute(self, target, bind, **kw):
  247. if self._ddl_if is None:
  248. return True
  249. else:
  250. return self._ddl_if._should_execute(self, target, bind, **kw)
  251. def _invoke_with(self, bind):
  252. if self._should_execute(self.target, bind):
  253. return bind.execute(self)
  254. def __call__(self, target, bind, **kw):
  255. """Execute the DDL as a ddl_listener."""
  256. self.against(target)._invoke_with(bind)
  257. def _generate(self):
  258. s = self.__class__.__new__(self.__class__)
  259. s.__dict__ = self.__dict__.copy()
  260. return s
  261. DDLElement = ExecutableDDLElement
  262. """:class:`.DDLElement` is renamed to :class:`.ExecutableDDLElement`."""
  263. class DDL(ExecutableDDLElement):
  264. """A literal DDL statement.
  265. Specifies literal SQL DDL to be executed by the database. DDL objects
  266. function as DDL event listeners, and can be subscribed to those events
  267. listed in :class:`.DDLEvents`, using either :class:`_schema.Table` or
  268. :class:`_schema.MetaData` objects as targets.
  269. Basic templating support allows
  270. a single DDL instance to handle repetitive tasks for multiple tables.
  271. Examples::
  272. from sqlalchemy import event, DDL
  273. tbl = Table("users", metadata, Column("uid", Integer))
  274. event.listen(tbl, "before_create", DDL("DROP TRIGGER users_trigger"))
  275. spow = DDL("ALTER TABLE %(table)s SET secretpowers TRUE")
  276. event.listen(tbl, "after_create", spow.execute_if(dialect="somedb"))
  277. drop_spow = DDL("ALTER TABLE users SET secretpowers FALSE")
  278. connection.execute(drop_spow)
  279. When operating on Table events, the following ``statement``
  280. string substitutions are available:
  281. .. sourcecode:: text
  282. %(table)s - the Table name, with any required quoting applied
  283. %(schema)s - the schema name, with any required quoting applied
  284. %(fullname)s - the Table name including schema, quoted if needed
  285. The DDL's "context", if any, will be combined with the standard
  286. substitutions noted above. Keys present in the context will override
  287. the standard substitutions.
  288. """
  289. __visit_name__ = "ddl"
  290. def __init__(self, statement, context=None):
  291. """Create a DDL statement.
  292. :param statement:
  293. A string or unicode string to be executed. Statements will be
  294. processed with Python's string formatting operator using
  295. a fixed set of string substitutions, as well as additional
  296. substitutions provided by the optional :paramref:`.DDL.context`
  297. parameter.
  298. A literal '%' in a statement must be escaped as '%%'.
  299. SQL bind parameters are not available in DDL statements.
  300. :param context:
  301. Optional dictionary, defaults to None. These values will be
  302. available for use in string substitutions on the DDL statement.
  303. .. seealso::
  304. :class:`.DDLEvents`
  305. :ref:`event_toplevel`
  306. """
  307. if not isinstance(statement, str):
  308. raise exc.ArgumentError(
  309. "Expected a string or unicode SQL statement, got '%r'"
  310. % statement
  311. )
  312. self.statement = statement
  313. self.context = context or {}
  314. def __repr__(self):
  315. parts = [repr(self.statement)]
  316. if self.context:
  317. parts.append(f"context={self.context}")
  318. return "<%s@%s; %s>" % (
  319. type(self).__name__,
  320. id(self),
  321. ", ".join(parts),
  322. )
  323. class _CreateDropBase(ExecutableDDLElement, Generic[_SI]):
  324. """Base class for DDL constructs that represent CREATE and DROP or
  325. equivalents.
  326. The common theme of _CreateDropBase is a single
  327. ``element`` attribute which refers to the element
  328. to be created or dropped.
  329. """
  330. def __init__(self, element: _SI) -> None:
  331. self.element = self.target = element
  332. self._ddl_if = getattr(element, "_ddl_if", None)
  333. @property
  334. def stringify_dialect(self):
  335. assert not isinstance(self.element, str)
  336. return self.element.create_drop_stringify_dialect
  337. def _create_rule_disable(self, compiler):
  338. """Allow disable of _create_rule using a callable.
  339. Pass to _create_rule using
  340. util.portable_instancemethod(self._create_rule_disable)
  341. to retain serializability.
  342. """
  343. return False
  344. class _CreateBase(_CreateDropBase[_SI]):
  345. def __init__(self, element: _SI, if_not_exists: bool = False) -> None:
  346. super().__init__(element)
  347. self.if_not_exists = if_not_exists
  348. class _DropBase(_CreateDropBase[_SI]):
  349. def __init__(self, element: _SI, if_exists: bool = False) -> None:
  350. super().__init__(element)
  351. self.if_exists = if_exists
  352. class CreateSchema(_CreateBase[str]):
  353. """Represent a CREATE SCHEMA statement.
  354. The argument here is the string name of the schema.
  355. """
  356. __visit_name__ = "create_schema"
  357. stringify_dialect = "default"
  358. def __init__(
  359. self,
  360. name: str,
  361. if_not_exists: bool = False,
  362. ) -> None:
  363. """Create a new :class:`.CreateSchema` construct."""
  364. super().__init__(element=name, if_not_exists=if_not_exists)
  365. class DropSchema(_DropBase[str]):
  366. """Represent a DROP SCHEMA statement.
  367. The argument here is the string name of the schema.
  368. """
  369. __visit_name__ = "drop_schema"
  370. stringify_dialect = "default"
  371. def __init__(
  372. self,
  373. name: str,
  374. cascade: bool = False,
  375. if_exists: bool = False,
  376. ) -> None:
  377. """Create a new :class:`.DropSchema` construct."""
  378. super().__init__(element=name, if_exists=if_exists)
  379. self.cascade = cascade
  380. class CreateTable(_CreateBase["Table"]):
  381. """Represent a CREATE TABLE statement."""
  382. __visit_name__ = "create_table"
  383. def __init__(
  384. self,
  385. element: Table,
  386. include_foreign_key_constraints: Optional[
  387. typing_Sequence[ForeignKeyConstraint]
  388. ] = None,
  389. if_not_exists: bool = False,
  390. ) -> None:
  391. """Create a :class:`.CreateTable` construct.
  392. :param element: a :class:`_schema.Table` that's the subject
  393. of the CREATE
  394. :param on: See the description for 'on' in :class:`.DDL`.
  395. :param include_foreign_key_constraints: optional sequence of
  396. :class:`_schema.ForeignKeyConstraint` objects that will be included
  397. inline within the CREATE construct; if omitted, all foreign key
  398. constraints that do not specify use_alter=True are included.
  399. :param if_not_exists: if True, an IF NOT EXISTS operator will be
  400. applied to the construct.
  401. .. versionadded:: 1.4.0b2
  402. """
  403. super().__init__(element, if_not_exists=if_not_exists)
  404. self.columns = [CreateColumn(column) for column in element.columns]
  405. self.include_foreign_key_constraints = include_foreign_key_constraints
  406. class _DropView(_DropBase["Table"]):
  407. """Semi-public 'DROP VIEW' construct.
  408. Used by the test suite for dialect-agnostic drops of views.
  409. This object will eventually be part of a public "view" API.
  410. """
  411. __visit_name__ = "drop_view"
  412. class CreateConstraint(BaseDDLElement):
  413. element: Constraint
  414. def __init__(self, element: Constraint) -> None:
  415. self.element = element
  416. class CreateColumn(BaseDDLElement):
  417. """Represent a :class:`_schema.Column`
  418. as rendered in a CREATE TABLE statement,
  419. via the :class:`.CreateTable` construct.
  420. This is provided to support custom column DDL within the generation
  421. of CREATE TABLE statements, by using the
  422. compiler extension documented in :ref:`sqlalchemy.ext.compiler_toplevel`
  423. to extend :class:`.CreateColumn`.
  424. Typical integration is to examine the incoming :class:`_schema.Column`
  425. object, and to redirect compilation if a particular flag or condition
  426. is found::
  427. from sqlalchemy import schema
  428. from sqlalchemy.ext.compiler import compiles
  429. @compiles(schema.CreateColumn)
  430. def compile(element, compiler, **kw):
  431. column = element.element
  432. if "special" not in column.info:
  433. return compiler.visit_create_column(element, **kw)
  434. text = "%s SPECIAL DIRECTIVE %s" % (
  435. column.name,
  436. compiler.type_compiler.process(column.type),
  437. )
  438. default = compiler.get_column_default_string(column)
  439. if default is not None:
  440. text += " DEFAULT " + default
  441. if not column.nullable:
  442. text += " NOT NULL"
  443. if column.constraints:
  444. text += " ".join(
  445. compiler.process(const) for const in column.constraints
  446. )
  447. return text
  448. The above construct can be applied to a :class:`_schema.Table`
  449. as follows::
  450. from sqlalchemy import Table, Metadata, Column, Integer, String
  451. from sqlalchemy import schema
  452. metadata = MetaData()
  453. table = Table(
  454. "mytable",
  455. MetaData(),
  456. Column("x", Integer, info={"special": True}, primary_key=True),
  457. Column("y", String(50)),
  458. Column("z", String(20), info={"special": True}),
  459. )
  460. metadata.create_all(conn)
  461. Above, the directives we've added to the :attr:`_schema.Column.info`
  462. collection
  463. will be detected by our custom compilation scheme:
  464. .. sourcecode:: sql
  465. CREATE TABLE mytable (
  466. x SPECIAL DIRECTIVE INTEGER NOT NULL,
  467. y VARCHAR(50),
  468. z SPECIAL DIRECTIVE VARCHAR(20),
  469. PRIMARY KEY (x)
  470. )
  471. The :class:`.CreateColumn` construct can also be used to skip certain
  472. columns when producing a ``CREATE TABLE``. This is accomplished by
  473. creating a compilation rule that conditionally returns ``None``.
  474. This is essentially how to produce the same effect as using the
  475. ``system=True`` argument on :class:`_schema.Column`, which marks a column
  476. as an implicitly-present "system" column.
  477. For example, suppose we wish to produce a :class:`_schema.Table`
  478. which skips
  479. rendering of the PostgreSQL ``xmin`` column against the PostgreSQL
  480. backend, but on other backends does render it, in anticipation of a
  481. triggered rule. A conditional compilation rule could skip this name only
  482. on PostgreSQL::
  483. from sqlalchemy.schema import CreateColumn
  484. @compiles(CreateColumn, "postgresql")
  485. def skip_xmin(element, compiler, **kw):
  486. if element.element.name == "xmin":
  487. return None
  488. else:
  489. return compiler.visit_create_column(element, **kw)
  490. my_table = Table(
  491. "mytable",
  492. metadata,
  493. Column("id", Integer, primary_key=True),
  494. Column("xmin", Integer),
  495. )
  496. Above, a :class:`.CreateTable` construct will generate a ``CREATE TABLE``
  497. which only includes the ``id`` column in the string; the ``xmin`` column
  498. will be omitted, but only against the PostgreSQL backend.
  499. """
  500. __visit_name__ = "create_column"
  501. element: Column[Any]
  502. def __init__(self, element: Column[Any]) -> None:
  503. self.element = element
  504. class DropTable(_DropBase["Table"]):
  505. """Represent a DROP TABLE statement."""
  506. __visit_name__ = "drop_table"
  507. def __init__(self, element: Table, if_exists: bool = False) -> None:
  508. """Create a :class:`.DropTable` construct.
  509. :param element: a :class:`_schema.Table` that's the subject
  510. of the DROP.
  511. :param on: See the description for 'on' in :class:`.DDL`.
  512. :param if_exists: if True, an IF EXISTS operator will be applied to the
  513. construct.
  514. .. versionadded:: 1.4.0b2
  515. """
  516. super().__init__(element, if_exists=if_exists)
  517. class CreateSequence(_CreateBase["Sequence"]):
  518. """Represent a CREATE SEQUENCE statement."""
  519. __visit_name__ = "create_sequence"
  520. class DropSequence(_DropBase["Sequence"]):
  521. """Represent a DROP SEQUENCE statement."""
  522. __visit_name__ = "drop_sequence"
  523. class CreateIndex(_CreateBase["Index"]):
  524. """Represent a CREATE INDEX statement."""
  525. __visit_name__ = "create_index"
  526. def __init__(self, element: Index, if_not_exists: bool = False) -> None:
  527. """Create a :class:`.Createindex` construct.
  528. :param element: a :class:`_schema.Index` that's the subject
  529. of the CREATE.
  530. :param if_not_exists: if True, an IF NOT EXISTS operator will be
  531. applied to the construct.
  532. .. versionadded:: 1.4.0b2
  533. """
  534. super().__init__(element, if_not_exists=if_not_exists)
  535. class DropIndex(_DropBase["Index"]):
  536. """Represent a DROP INDEX statement."""
  537. __visit_name__ = "drop_index"
  538. def __init__(self, element: Index, if_exists: bool = False) -> None:
  539. """Create a :class:`.DropIndex` construct.
  540. :param element: a :class:`_schema.Index` that's the subject
  541. of the DROP.
  542. :param if_exists: if True, an IF EXISTS operator will be applied to the
  543. construct.
  544. .. versionadded:: 1.4.0b2
  545. """
  546. super().__init__(element, if_exists=if_exists)
  547. class AddConstraint(_CreateBase["Constraint"]):
  548. """Represent an ALTER TABLE ADD CONSTRAINT statement."""
  549. __visit_name__ = "add_constraint"
  550. def __init__(
  551. self,
  552. element: Constraint,
  553. *,
  554. isolate_from_table: bool = True,
  555. ) -> None:
  556. """Construct a new :class:`.AddConstraint` construct.
  557. :param element: a :class:`.Constraint` object
  558. :param isolate_from_table: optional boolean, defaults to True. Has
  559. the effect of the incoming constraint being isolated from being
  560. included in a CREATE TABLE sequence when associated with a
  561. :class:`.Table`.
  562. .. versionadded:: 2.0.39 - added
  563. :paramref:`.AddConstraint.isolate_from_table`, defaulting
  564. to True. Previously, the behavior of this parameter was implicitly
  565. turned on in all cases.
  566. """
  567. super().__init__(element)
  568. if isolate_from_table:
  569. element._create_rule = util.portable_instancemethod(
  570. self._create_rule_disable
  571. )
  572. class DropConstraint(_DropBase["Constraint"]):
  573. """Represent an ALTER TABLE DROP CONSTRAINT statement."""
  574. __visit_name__ = "drop_constraint"
  575. def __init__(
  576. self,
  577. element: Constraint,
  578. *,
  579. cascade: bool = False,
  580. if_exists: bool = False,
  581. isolate_from_table: bool = True,
  582. **kw: Any,
  583. ) -> None:
  584. """Construct a new :class:`.DropConstraint` construct.
  585. :param element: a :class:`.Constraint` object
  586. :param cascade: optional boolean, indicates backend-specific
  587. "CASCADE CONSTRAINT" directive should be rendered if available
  588. :param if_exists: optional boolean, indicates backend-specific
  589. "IF EXISTS" directive should be rendered if available
  590. :param isolate_from_table: optional boolean, defaults to True. Has
  591. the effect of the incoming constraint being isolated from being
  592. included in a CREATE TABLE sequence when associated with a
  593. :class:`.Table`.
  594. .. versionadded:: 2.0.39 - added
  595. :paramref:`.DropConstraint.isolate_from_table`, defaulting
  596. to True. Previously, the behavior of this parameter was implicitly
  597. turned on in all cases.
  598. """
  599. self.cascade = cascade
  600. super().__init__(element, if_exists=if_exists, **kw)
  601. if isolate_from_table:
  602. element._create_rule = util.portable_instancemethod(
  603. self._create_rule_disable
  604. )
  605. class SetTableComment(_CreateDropBase["Table"]):
  606. """Represent a COMMENT ON TABLE IS statement."""
  607. __visit_name__ = "set_table_comment"
  608. class DropTableComment(_CreateDropBase["Table"]):
  609. """Represent a COMMENT ON TABLE '' statement.
  610. Note this varies a lot across database backends.
  611. """
  612. __visit_name__ = "drop_table_comment"
  613. class SetColumnComment(_CreateDropBase["Column[Any]"]):
  614. """Represent a COMMENT ON COLUMN IS statement."""
  615. __visit_name__ = "set_column_comment"
  616. class DropColumnComment(_CreateDropBase["Column[Any]"]):
  617. """Represent a COMMENT ON COLUMN IS NULL statement."""
  618. __visit_name__ = "drop_column_comment"
  619. class SetConstraintComment(_CreateDropBase["Constraint"]):
  620. """Represent a COMMENT ON CONSTRAINT IS statement."""
  621. __visit_name__ = "set_constraint_comment"
  622. class DropConstraintComment(_CreateDropBase["Constraint"]):
  623. """Represent a COMMENT ON CONSTRAINT IS NULL statement."""
  624. __visit_name__ = "drop_constraint_comment"
  625. class InvokeDDLBase(SchemaVisitor):
  626. def __init__(self, connection, **kw):
  627. self.connection = connection
  628. assert not kw, f"Unexpected keywords: {kw.keys()}"
  629. @contextlib.contextmanager
  630. def with_ddl_events(self, target, **kw):
  631. """helper context manager that will apply appropriate DDL events
  632. to a CREATE or DROP operation."""
  633. raise NotImplementedError()
  634. class InvokeCreateDDLBase(InvokeDDLBase):
  635. @contextlib.contextmanager
  636. def with_ddl_events(self, target, **kw):
  637. """helper context manager that will apply appropriate DDL events
  638. to a CREATE or DROP operation."""
  639. target.dispatch.before_create(
  640. target, self.connection, _ddl_runner=self, **kw
  641. )
  642. yield
  643. target.dispatch.after_create(
  644. target, self.connection, _ddl_runner=self, **kw
  645. )
  646. class InvokeDropDDLBase(InvokeDDLBase):
  647. @contextlib.contextmanager
  648. def with_ddl_events(self, target, **kw):
  649. """helper context manager that will apply appropriate DDL events
  650. to a CREATE or DROP operation."""
  651. target.dispatch.before_drop(
  652. target, self.connection, _ddl_runner=self, **kw
  653. )
  654. yield
  655. target.dispatch.after_drop(
  656. target, self.connection, _ddl_runner=self, **kw
  657. )
  658. class SchemaGenerator(InvokeCreateDDLBase):
  659. def __init__(
  660. self, dialect, connection, checkfirst=False, tables=None, **kwargs
  661. ):
  662. super().__init__(connection, **kwargs)
  663. self.checkfirst = checkfirst
  664. self.tables = tables
  665. self.preparer = dialect.identifier_preparer
  666. self.dialect = dialect
  667. self.memo = {}
  668. def _can_create_table(self, table):
  669. self.dialect.validate_identifier(table.name)
  670. effective_schema = self.connection.schema_for_object(table)
  671. if effective_schema:
  672. self.dialect.validate_identifier(effective_schema)
  673. return not self.checkfirst or not self.dialect.has_table(
  674. self.connection, table.name, schema=effective_schema
  675. )
  676. def _can_create_index(self, index):
  677. effective_schema = self.connection.schema_for_object(index.table)
  678. if effective_schema:
  679. self.dialect.validate_identifier(effective_schema)
  680. return not self.checkfirst or not self.dialect.has_index(
  681. self.connection,
  682. index.table.name,
  683. index.name,
  684. schema=effective_schema,
  685. )
  686. def _can_create_sequence(self, sequence):
  687. effective_schema = self.connection.schema_for_object(sequence)
  688. return self.dialect.supports_sequences and (
  689. (not self.dialect.sequences_optional or not sequence.optional)
  690. and (
  691. not self.checkfirst
  692. or not self.dialect.has_sequence(
  693. self.connection, sequence.name, schema=effective_schema
  694. )
  695. )
  696. )
  697. def visit_metadata(self, metadata):
  698. if self.tables is not None:
  699. tables = self.tables
  700. else:
  701. tables = list(metadata.tables.values())
  702. collection = sort_tables_and_constraints(
  703. [t for t in tables if self._can_create_table(t)]
  704. )
  705. seq_coll = [
  706. s
  707. for s in metadata._sequences.values()
  708. if s.column is None and self._can_create_sequence(s)
  709. ]
  710. event_collection = [t for (t, fks) in collection if t is not None]
  711. with self.with_ddl_events(
  712. metadata,
  713. tables=event_collection,
  714. checkfirst=self.checkfirst,
  715. ):
  716. for seq in seq_coll:
  717. self.traverse_single(seq, create_ok=True)
  718. for table, fkcs in collection:
  719. if table is not None:
  720. self.traverse_single(
  721. table,
  722. create_ok=True,
  723. include_foreign_key_constraints=fkcs,
  724. _is_metadata_operation=True,
  725. )
  726. else:
  727. for fkc in fkcs:
  728. self.traverse_single(fkc)
  729. def visit_table(
  730. self,
  731. table,
  732. create_ok=False,
  733. include_foreign_key_constraints=None,
  734. _is_metadata_operation=False,
  735. ):
  736. if not create_ok and not self._can_create_table(table):
  737. return
  738. with self.with_ddl_events(
  739. table,
  740. checkfirst=self.checkfirst,
  741. _is_metadata_operation=_is_metadata_operation,
  742. ):
  743. for column in table.columns:
  744. if column.default is not None:
  745. self.traverse_single(column.default)
  746. if not self.dialect.supports_alter:
  747. # e.g., don't omit any foreign key constraints
  748. include_foreign_key_constraints = None
  749. CreateTable(
  750. table,
  751. include_foreign_key_constraints=(
  752. include_foreign_key_constraints
  753. ),
  754. )._invoke_with(self.connection)
  755. if hasattr(table, "indexes"):
  756. for index in table.indexes:
  757. self.traverse_single(index, create_ok=True)
  758. if (
  759. self.dialect.supports_comments
  760. and not self.dialect.inline_comments
  761. ):
  762. if table.comment is not None:
  763. SetTableComment(table)._invoke_with(self.connection)
  764. for column in table.columns:
  765. if column.comment is not None:
  766. SetColumnComment(column)._invoke_with(self.connection)
  767. if self.dialect.supports_constraint_comments:
  768. for constraint in table.constraints:
  769. if constraint.comment is not None:
  770. self.connection.execute(
  771. SetConstraintComment(constraint)
  772. )
  773. def visit_foreign_key_constraint(self, constraint):
  774. if not self.dialect.supports_alter:
  775. return
  776. with self.with_ddl_events(constraint):
  777. AddConstraint(constraint)._invoke_with(self.connection)
  778. def visit_sequence(self, sequence, create_ok=False):
  779. if not create_ok and not self._can_create_sequence(sequence):
  780. return
  781. with self.with_ddl_events(sequence):
  782. CreateSequence(sequence)._invoke_with(self.connection)
  783. def visit_index(self, index, create_ok=False):
  784. if not create_ok and not self._can_create_index(index):
  785. return
  786. with self.with_ddl_events(index):
  787. CreateIndex(index)._invoke_with(self.connection)
  788. class SchemaDropper(InvokeDropDDLBase):
  789. def __init__(
  790. self, dialect, connection, checkfirst=False, tables=None, **kwargs
  791. ):
  792. super().__init__(connection, **kwargs)
  793. self.checkfirst = checkfirst
  794. self.tables = tables
  795. self.preparer = dialect.identifier_preparer
  796. self.dialect = dialect
  797. self.memo = {}
  798. def visit_metadata(self, metadata):
  799. if self.tables is not None:
  800. tables = self.tables
  801. else:
  802. tables = list(metadata.tables.values())
  803. try:
  804. unsorted_tables = [t for t in tables if self._can_drop_table(t)]
  805. collection = list(
  806. reversed(
  807. sort_tables_and_constraints(
  808. unsorted_tables,
  809. filter_fn=lambda constraint: (
  810. False
  811. if not self.dialect.supports_alter
  812. or constraint.name is None
  813. else None
  814. ),
  815. )
  816. )
  817. )
  818. except exc.CircularDependencyError as err2:
  819. if not self.dialect.supports_alter:
  820. util.warn(
  821. "Can't sort tables for DROP; an "
  822. "unresolvable foreign key "
  823. "dependency exists between tables: %s; and backend does "
  824. "not support ALTER. To restore at least a partial sort, "
  825. "apply use_alter=True to ForeignKey and "
  826. "ForeignKeyConstraint "
  827. "objects involved in the cycle to mark these as known "
  828. "cycles that will be ignored."
  829. % (", ".join(sorted([t.fullname for t in err2.cycles])))
  830. )
  831. collection = [(t, ()) for t in unsorted_tables]
  832. else:
  833. raise exc.CircularDependencyError(
  834. err2.args[0],
  835. err2.cycles,
  836. err2.edges,
  837. msg="Can't sort tables for DROP; an "
  838. "unresolvable foreign key "
  839. "dependency exists between tables: %s. Please ensure "
  840. "that the ForeignKey and ForeignKeyConstraint objects "
  841. "involved in the cycle have "
  842. "names so that they can be dropped using "
  843. "DROP CONSTRAINT."
  844. % (", ".join(sorted([t.fullname for t in err2.cycles]))),
  845. ) from err2
  846. seq_coll = [
  847. s
  848. for s in metadata._sequences.values()
  849. if self._can_drop_sequence(s)
  850. ]
  851. event_collection = [t for (t, fks) in collection if t is not None]
  852. with self.with_ddl_events(
  853. metadata,
  854. tables=event_collection,
  855. checkfirst=self.checkfirst,
  856. ):
  857. for table, fkcs in collection:
  858. if table is not None:
  859. self.traverse_single(
  860. table,
  861. drop_ok=True,
  862. _is_metadata_operation=True,
  863. _ignore_sequences=seq_coll,
  864. )
  865. else:
  866. for fkc in fkcs:
  867. self.traverse_single(fkc)
  868. for seq in seq_coll:
  869. self.traverse_single(seq, drop_ok=seq.column is None)
  870. def _can_drop_table(self, table):
  871. self.dialect.validate_identifier(table.name)
  872. effective_schema = self.connection.schema_for_object(table)
  873. if effective_schema:
  874. self.dialect.validate_identifier(effective_schema)
  875. return not self.checkfirst or self.dialect.has_table(
  876. self.connection, table.name, schema=effective_schema
  877. )
  878. def _can_drop_index(self, index):
  879. effective_schema = self.connection.schema_for_object(index.table)
  880. if effective_schema:
  881. self.dialect.validate_identifier(effective_schema)
  882. return not self.checkfirst or self.dialect.has_index(
  883. self.connection,
  884. index.table.name,
  885. index.name,
  886. schema=effective_schema,
  887. )
  888. def _can_drop_sequence(self, sequence):
  889. effective_schema = self.connection.schema_for_object(sequence)
  890. return self.dialect.supports_sequences and (
  891. (not self.dialect.sequences_optional or not sequence.optional)
  892. and (
  893. not self.checkfirst
  894. or self.dialect.has_sequence(
  895. self.connection, sequence.name, schema=effective_schema
  896. )
  897. )
  898. )
  899. def visit_index(self, index, drop_ok=False):
  900. if not drop_ok and not self._can_drop_index(index):
  901. return
  902. with self.with_ddl_events(index):
  903. DropIndex(index)(index, self.connection)
  904. def visit_table(
  905. self,
  906. table,
  907. drop_ok=False,
  908. _is_metadata_operation=False,
  909. _ignore_sequences=(),
  910. ):
  911. if not drop_ok and not self._can_drop_table(table):
  912. return
  913. with self.with_ddl_events(
  914. table,
  915. checkfirst=self.checkfirst,
  916. _is_metadata_operation=_is_metadata_operation,
  917. ):
  918. DropTable(table)._invoke_with(self.connection)
  919. # traverse client side defaults which may refer to server-side
  920. # sequences. noting that some of these client side defaults may
  921. # also be set up as server side defaults
  922. # (see https://docs.sqlalchemy.org/en/
  923. # latest/core/defaults.html
  924. # #associating-a-sequence-as-the-server-side-
  925. # default), so have to be dropped after the table is dropped.
  926. for column in table.columns:
  927. if (
  928. column.default is not None
  929. and column.default not in _ignore_sequences
  930. ):
  931. self.traverse_single(column.default)
  932. def visit_foreign_key_constraint(self, constraint):
  933. if not self.dialect.supports_alter:
  934. return
  935. with self.with_ddl_events(constraint):
  936. DropConstraint(constraint)._invoke_with(self.connection)
  937. def visit_sequence(self, sequence, drop_ok=False):
  938. if not drop_ok and not self._can_drop_sequence(sequence):
  939. return
  940. with self.with_ddl_events(sequence):
  941. DropSequence(sequence)._invoke_with(self.connection)
  942. def sort_tables(
  943. tables: Iterable[TableClause],
  944. skip_fn: Optional[Callable[[ForeignKeyConstraint], bool]] = None,
  945. extra_dependencies: Optional[
  946. typing_Sequence[Tuple[TableClause, TableClause]]
  947. ] = None,
  948. ) -> List[Table]:
  949. """Sort a collection of :class:`_schema.Table` objects based on
  950. dependency.
  951. This is a dependency-ordered sort which will emit :class:`_schema.Table`
  952. objects such that they will follow their dependent :class:`_schema.Table`
  953. objects.
  954. Tables are dependent on another based on the presence of
  955. :class:`_schema.ForeignKeyConstraint`
  956. objects as well as explicit dependencies
  957. added by :meth:`_schema.Table.add_is_dependent_on`.
  958. .. warning::
  959. The :func:`._schema.sort_tables` function cannot by itself
  960. accommodate automatic resolution of dependency cycles between
  961. tables, which are usually caused by mutually dependent foreign key
  962. constraints. When these cycles are detected, the foreign keys
  963. of these tables are omitted from consideration in the sort.
  964. A warning is emitted when this condition occurs, which will be an
  965. exception raise in a future release. Tables which are not part
  966. of the cycle will still be returned in dependency order.
  967. To resolve these cycles, the
  968. :paramref:`_schema.ForeignKeyConstraint.use_alter` parameter may be
  969. applied to those constraints which create a cycle. Alternatively,
  970. the :func:`_schema.sort_tables_and_constraints` function will
  971. automatically return foreign key constraints in a separate
  972. collection when cycles are detected so that they may be applied
  973. to a schema separately.
  974. .. versionchanged:: 1.3.17 - a warning is emitted when
  975. :func:`_schema.sort_tables` cannot perform a proper sort due to
  976. cyclical dependencies. This will be an exception in a future
  977. release. Additionally, the sort will continue to return
  978. other tables not involved in the cycle in dependency order
  979. which was not the case previously.
  980. :param tables: a sequence of :class:`_schema.Table` objects.
  981. :param skip_fn: optional callable which will be passed a
  982. :class:`_schema.ForeignKeyConstraint` object; if it returns True, this
  983. constraint will not be considered as a dependency. Note this is
  984. **different** from the same parameter in
  985. :func:`.sort_tables_and_constraints`, which is
  986. instead passed the owning :class:`_schema.ForeignKeyConstraint` object.
  987. :param extra_dependencies: a sequence of 2-tuples of tables which will
  988. also be considered as dependent on each other.
  989. .. seealso::
  990. :func:`.sort_tables_and_constraints`
  991. :attr:`_schema.MetaData.sorted_tables` - uses this function to sort
  992. """
  993. if skip_fn is not None:
  994. fixed_skip_fn = skip_fn
  995. def _skip_fn(fkc):
  996. for fk in fkc.elements:
  997. if fixed_skip_fn(fk):
  998. return True
  999. else:
  1000. return None
  1001. else:
  1002. _skip_fn = None # type: ignore
  1003. return [
  1004. t
  1005. for (t, fkcs) in sort_tables_and_constraints(
  1006. tables,
  1007. filter_fn=_skip_fn,
  1008. extra_dependencies=extra_dependencies,
  1009. _warn_for_cycles=True,
  1010. )
  1011. if t is not None
  1012. ]
  1013. def sort_tables_and_constraints(
  1014. tables, filter_fn=None, extra_dependencies=None, _warn_for_cycles=False
  1015. ):
  1016. """Sort a collection of :class:`_schema.Table` /
  1017. :class:`_schema.ForeignKeyConstraint`
  1018. objects.
  1019. This is a dependency-ordered sort which will emit tuples of
  1020. ``(Table, [ForeignKeyConstraint, ...])`` such that each
  1021. :class:`_schema.Table` follows its dependent :class:`_schema.Table`
  1022. objects.
  1023. Remaining :class:`_schema.ForeignKeyConstraint`
  1024. objects that are separate due to
  1025. dependency rules not satisfied by the sort are emitted afterwards
  1026. as ``(None, [ForeignKeyConstraint ...])``.
  1027. Tables are dependent on another based on the presence of
  1028. :class:`_schema.ForeignKeyConstraint` objects, explicit dependencies
  1029. added by :meth:`_schema.Table.add_is_dependent_on`,
  1030. as well as dependencies
  1031. stated here using the :paramref:`~.sort_tables_and_constraints.skip_fn`
  1032. and/or :paramref:`~.sort_tables_and_constraints.extra_dependencies`
  1033. parameters.
  1034. :param tables: a sequence of :class:`_schema.Table` objects.
  1035. :param filter_fn: optional callable which will be passed a
  1036. :class:`_schema.ForeignKeyConstraint` object,
  1037. and returns a value based on
  1038. whether this constraint should definitely be included or excluded as
  1039. an inline constraint, or neither. If it returns False, the constraint
  1040. will definitely be included as a dependency that cannot be subject
  1041. to ALTER; if True, it will **only** be included as an ALTER result at
  1042. the end. Returning None means the constraint is included in the
  1043. table-based result unless it is detected as part of a dependency cycle.
  1044. :param extra_dependencies: a sequence of 2-tuples of tables which will
  1045. also be considered as dependent on each other.
  1046. .. seealso::
  1047. :func:`.sort_tables`
  1048. """
  1049. fixed_dependencies = set()
  1050. mutable_dependencies = set()
  1051. if extra_dependencies is not None:
  1052. fixed_dependencies.update(extra_dependencies)
  1053. remaining_fkcs = set()
  1054. for table in tables:
  1055. for fkc in table.foreign_key_constraints:
  1056. if fkc.use_alter is True:
  1057. remaining_fkcs.add(fkc)
  1058. continue
  1059. if filter_fn:
  1060. filtered = filter_fn(fkc)
  1061. if filtered is True:
  1062. remaining_fkcs.add(fkc)
  1063. continue
  1064. dependent_on = fkc.referred_table
  1065. if dependent_on is not table:
  1066. mutable_dependencies.add((dependent_on, table))
  1067. fixed_dependencies.update(
  1068. (parent, table) for parent in table._extra_dependencies
  1069. )
  1070. try:
  1071. candidate_sort = list(
  1072. topological.sort(
  1073. fixed_dependencies.union(mutable_dependencies),
  1074. tables,
  1075. )
  1076. )
  1077. except exc.CircularDependencyError as err:
  1078. if _warn_for_cycles:
  1079. util.warn(
  1080. "Cannot correctly sort tables; there are unresolvable cycles "
  1081. 'between tables "%s", which is usually caused by mutually '
  1082. "dependent foreign key constraints. Foreign key constraints "
  1083. "involving these tables will not be considered; this warning "
  1084. "may raise an error in a future release."
  1085. % (", ".join(sorted(t.fullname for t in err.cycles)),)
  1086. )
  1087. for edge in err.edges:
  1088. if edge in mutable_dependencies:
  1089. table = edge[1]
  1090. if table not in err.cycles:
  1091. continue
  1092. can_remove = [
  1093. fkc
  1094. for fkc in table.foreign_key_constraints
  1095. if filter_fn is None or filter_fn(fkc) is not False
  1096. ]
  1097. remaining_fkcs.update(can_remove)
  1098. for fkc in can_remove:
  1099. dependent_on = fkc.referred_table
  1100. if dependent_on is not table:
  1101. mutable_dependencies.discard((dependent_on, table))
  1102. candidate_sort = list(
  1103. topological.sort(
  1104. fixed_dependencies.union(mutable_dependencies),
  1105. tables,
  1106. )
  1107. )
  1108. return [
  1109. (table, table.foreign_key_constraints.difference(remaining_fkcs))
  1110. for table in candidate_sort
  1111. ] + [(None, list(remaining_fkcs))]