You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1337 lines
43KB

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