25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5092 lines
182KB

  1. # sql/schema.py
  2. # Copyright (C) 2005-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. """The schema module provides the building blocks for database metadata.
  8. Each element within this module describes a database entity which can be
  9. created and dropped, or is otherwise part of such an entity. Examples include
  10. tables, columns, sequences, and indexes.
  11. All entities are subclasses of :class:`~sqlalchemy.schema.SchemaItem`, and as
  12. defined in this module they are intended to be agnostic of any vendor-specific
  13. constructs.
  14. A collection of entities are grouped into a unit called
  15. :class:`~sqlalchemy.schema.MetaData`. MetaData serves as a logical grouping of
  16. schema elements, and can also be associated with an actual database connection
  17. such that operations involving the contained elements can contact the database
  18. as needed.
  19. Two of the elements here also build upon their "syntactic" counterparts, which
  20. are defined in :class:`~sqlalchemy.sql.expression.`, specifically
  21. :class:`~sqlalchemy.schema.Table` and :class:`~sqlalchemy.schema.Column`.
  22. Since these objects are part of the SQL expression language, they are usable
  23. as components in SQL expressions.
  24. """
  25. from __future__ import absolute_import
  26. import collections
  27. import sqlalchemy
  28. from . import coercions
  29. from . import ddl
  30. from . import roles
  31. from . import type_api
  32. from . import visitors
  33. from .base import _bind_or_error
  34. from .base import DedupeColumnCollection
  35. from .base import DialectKWArgs
  36. from .base import Executable
  37. from .base import SchemaEventTarget
  38. from .coercions import _document_text_coercion
  39. from .elements import ClauseElement
  40. from .elements import ColumnClause
  41. from .elements import ColumnElement
  42. from .elements import quoted_name
  43. from .elements import TextClause
  44. from .selectable import TableClause
  45. from .type_api import to_instance
  46. from .visitors import InternalTraversal
  47. from .. import event
  48. from .. import exc
  49. from .. import inspection
  50. from .. import util
  51. RETAIN_SCHEMA = util.symbol("retain_schema")
  52. BLANK_SCHEMA = util.symbol(
  53. "blank_schema",
  54. """Symbol indicating that a :class:`_schema.Table` or :class:`.Sequence`
  55. should have 'None' for its schema, even if the parent
  56. :class:`_schema.MetaData` has specified a schema.
  57. .. versionadded:: 1.0.14
  58. """,
  59. )
  60. NULL_UNSPECIFIED = util.symbol(
  61. "NULL_UNSPECIFIED",
  62. """Symbol indicating the "nullable" keyword was not passed to a Column.
  63. Normally we would expect None to be acceptable for this but some backends
  64. such as that of SQL Server place special signficance on a "nullability"
  65. value of None.
  66. """,
  67. )
  68. def _get_table_key(name, schema):
  69. if schema is None:
  70. return name
  71. else:
  72. return schema + "." + name
  73. # this should really be in sql/util.py but we'd have to
  74. # break an import cycle
  75. def _copy_expression(expression, source_table, target_table):
  76. if source_table is None or target_table is None:
  77. return expression
  78. def replace(col):
  79. if (
  80. isinstance(col, Column)
  81. and col.table is source_table
  82. and col.key in source_table.c
  83. ):
  84. return target_table.c[col.key]
  85. else:
  86. return None
  87. return visitors.replacement_traverse(expression, {}, replace)
  88. @inspection._self_inspects
  89. class SchemaItem(SchemaEventTarget, visitors.Visitable):
  90. """Base class for items that define a database schema."""
  91. __visit_name__ = "schema_item"
  92. create_drop_stringify_dialect = "default"
  93. def _init_items(self, *args, **kw):
  94. """Initialize the list of child items for this SchemaItem."""
  95. for item in args:
  96. if item is not None:
  97. try:
  98. spwd = item._set_parent_with_dispatch
  99. except AttributeError as err:
  100. util.raise_(
  101. exc.ArgumentError(
  102. "'SchemaItem' object, such as a 'Column' or a "
  103. "'Constraint' expected, got %r" % item
  104. ),
  105. replace_context=err,
  106. )
  107. else:
  108. spwd(self, **kw)
  109. def __repr__(self):
  110. return util.generic_repr(self, omit_kwarg=["info"])
  111. @util.memoized_property
  112. def info(self):
  113. """Info dictionary associated with the object, allowing user-defined
  114. data to be associated with this :class:`.SchemaItem`.
  115. The dictionary is automatically generated when first accessed.
  116. It can also be specified in the constructor of some objects,
  117. such as :class:`_schema.Table` and :class:`_schema.Column`.
  118. """
  119. return {}
  120. def _schema_item_copy(self, schema_item):
  121. if "info" in self.__dict__:
  122. schema_item.info = self.info.copy()
  123. schema_item.dispatch._update(self.dispatch)
  124. return schema_item
  125. _use_schema_map = True
  126. class Table(DialectKWArgs, SchemaItem, TableClause):
  127. r"""Represent a table in a database.
  128. e.g.::
  129. mytable = Table("mytable", metadata,
  130. Column('mytable_id', Integer, primary_key=True),
  131. Column('value', String(50))
  132. )
  133. The :class:`_schema.Table`
  134. object constructs a unique instance of itself based
  135. on its name and optional schema name within the given
  136. :class:`_schema.MetaData` object. Calling the :class:`_schema.Table`
  137. constructor with the same name and same :class:`_schema.MetaData` argument
  138. a second time will return the *same* :class:`_schema.Table`
  139. object - in this way
  140. the :class:`_schema.Table` constructor acts as a registry function.
  141. .. seealso::
  142. :ref:`metadata_describing` - Introduction to database metadata
  143. Constructor arguments are as follows:
  144. :param name: The name of this table as represented in the database.
  145. The table name, along with the value of the ``schema`` parameter,
  146. forms a key which uniquely identifies this :class:`_schema.Table`
  147. within
  148. the owning :class:`_schema.MetaData` collection.
  149. Additional calls to :class:`_schema.Table` with the same name,
  150. metadata,
  151. and schema name will return the same :class:`_schema.Table` object.
  152. Names which contain no upper case characters
  153. will be treated as case insensitive names, and will not be quoted
  154. unless they are a reserved word or contain special characters.
  155. A name with any number of upper case characters is considered
  156. to be case sensitive, and will be sent as quoted.
  157. To enable unconditional quoting for the table name, specify the flag
  158. ``quote=True`` to the constructor, or use the :class:`.quoted_name`
  159. construct to specify the name.
  160. :param metadata: a :class:`_schema.MetaData`
  161. object which will contain this
  162. table. The metadata is used as a point of association of this table
  163. with other tables which are referenced via foreign key. It also
  164. may be used to associate this table with a particular
  165. :class:`.Connectable`.
  166. :param \*args: Additional positional arguments are used primarily
  167. to add the list of :class:`_schema.Column`
  168. objects contained within this
  169. table. Similar to the style of a CREATE TABLE statement, other
  170. :class:`.SchemaItem` constructs may be added here, including
  171. :class:`.PrimaryKeyConstraint`, and
  172. :class:`_schema.ForeignKeyConstraint`.
  173. :param autoload: Defaults to ``False``, unless
  174. :paramref:`_schema.Table.autoload_with`
  175. is set in which case it defaults to ``True``;
  176. :class:`_schema.Column` objects
  177. for this table should be reflected from the database, possibly
  178. augmenting objects that were explicitly specified.
  179. :class:`_schema.Column` and other objects explicitly set on the
  180. table will replace corresponding reflected objects.
  181. .. deprecated:: 1.4
  182. The autoload parameter is deprecated and will be removed in
  183. version 2.0. Please use the
  184. :paramref:`_schema.Table.autoload_with` parameter, passing an
  185. engine or connection.
  186. .. seealso::
  187. :ref:`metadata_reflection_toplevel`
  188. :param autoload_replace: Defaults to ``True``; when using
  189. :paramref:`_schema.Table.autoload`
  190. in conjunction with :paramref:`_schema.Table.extend_existing`,
  191. indicates
  192. that :class:`_schema.Column` objects present in the already-existing
  193. :class:`_schema.Table`
  194. object should be replaced with columns of the same
  195. name retrieved from the autoload process. When ``False``, columns
  196. already present under existing names will be omitted from the
  197. reflection process.
  198. Note that this setting does not impact :class:`_schema.Column` objects
  199. specified programmatically within the call to :class:`_schema.Table`
  200. that
  201. also is autoloading; those :class:`_schema.Column` objects will always
  202. replace existing columns of the same name when
  203. :paramref:`_schema.Table.extend_existing` is ``True``.
  204. .. seealso::
  205. :paramref:`_schema.Table.autoload`
  206. :paramref:`_schema.Table.extend_existing`
  207. :param autoload_with: An :class:`_engine.Engine` or
  208. :class:`_engine.Connection` object,
  209. or a :class:`_reflection.Inspector` object as returned by
  210. :func:`_sa.inspect`
  211. against one, with which this :class:`_schema.Table`
  212. object will be reflected.
  213. When set to a non-None value, the autoload process will take place
  214. for this table against the given engine or connection.
  215. :param extend_existing: When ``True``, indicates that if this
  216. :class:`_schema.Table` is already present in the given
  217. :class:`_schema.MetaData`,
  218. apply further arguments within the constructor to the existing
  219. :class:`_schema.Table`.
  220. If :paramref:`_schema.Table.extend_existing` or
  221. :paramref:`_schema.Table.keep_existing` are not set,
  222. and the given name
  223. of the new :class:`_schema.Table` refers to a :class:`_schema.Table`
  224. that is
  225. already present in the target :class:`_schema.MetaData` collection,
  226. and
  227. this :class:`_schema.Table`
  228. specifies additional columns or other constructs
  229. or flags that modify the table's state, an
  230. error is raised. The purpose of these two mutually-exclusive flags
  231. is to specify what action should be taken when a
  232. :class:`_schema.Table`
  233. is specified that matches an existing :class:`_schema.Table`,
  234. yet specifies
  235. additional constructs.
  236. :paramref:`_schema.Table.extend_existing`
  237. will also work in conjunction
  238. with :paramref:`_schema.Table.autoload` to run a new reflection
  239. operation against the database, even if a :class:`_schema.Table`
  240. of the same name is already present in the target
  241. :class:`_schema.MetaData`; newly reflected :class:`_schema.Column`
  242. objects
  243. and other options will be added into the state of the
  244. :class:`_schema.Table`, potentially overwriting existing columns
  245. and options of the same name.
  246. As is always the case with :paramref:`_schema.Table.autoload`,
  247. :class:`_schema.Column` objects can be specified in the same
  248. :class:`_schema.Table`
  249. constructor, which will take precedence. Below, the existing
  250. table ``mytable`` will be augmented with :class:`_schema.Column`
  251. objects
  252. both reflected from the database, as well as the given
  253. :class:`_schema.Column`
  254. named "y"::
  255. Table("mytable", metadata,
  256. Column('y', Integer),
  257. extend_existing=True,
  258. autoload_with=engine
  259. )
  260. .. seealso::
  261. :paramref:`_schema.Table.autoload`
  262. :paramref:`_schema.Table.autoload_replace`
  263. :paramref:`_schema.Table.keep_existing`
  264. :param implicit_returning: True by default - indicates that
  265. RETURNING can be used by default to fetch newly inserted primary key
  266. values, for backends which support this. Note that
  267. :func:`_sa.create_engine` also provides an ``implicit_returning``
  268. flag.
  269. :param include_columns: A list of strings indicating a subset of
  270. columns to be loaded via the ``autoload`` operation; table columns who
  271. aren't present in this list will not be represented on the resulting
  272. ``Table`` object. Defaults to ``None`` which indicates all columns
  273. should be reflected.
  274. :param resolve_fks: Whether or not to reflect :class:`_schema.Table`
  275. objects
  276. related to this one via :class:`_schema.ForeignKey` objects, when
  277. :paramref:`_schema.Table.autoload` or
  278. :paramref:`_schema.Table.autoload_with` is
  279. specified. Defaults to True. Set to False to disable reflection of
  280. related tables as :class:`_schema.ForeignKey`
  281. objects are encountered; may be
  282. used either to save on SQL calls or to avoid issues with related tables
  283. that can't be accessed. Note that if a related table is already present
  284. in the :class:`_schema.MetaData` collection, or becomes present later,
  285. a
  286. :class:`_schema.ForeignKey` object associated with this
  287. :class:`_schema.Table` will
  288. resolve to that table normally.
  289. .. versionadded:: 1.3
  290. .. seealso::
  291. :paramref:`.MetaData.reflect.resolve_fks`
  292. :param info: Optional data dictionary which will be populated into the
  293. :attr:`.SchemaItem.info` attribute of this object.
  294. :param keep_existing: When ``True``, indicates that if this Table
  295. is already present in the given :class:`_schema.MetaData`, ignore
  296. further arguments within the constructor to the existing
  297. :class:`_schema.Table`, and return the :class:`_schema.Table`
  298. object as
  299. originally created. This is to allow a function that wishes
  300. to define a new :class:`_schema.Table` on first call, but on
  301. subsequent calls will return the same :class:`_schema.Table`,
  302. without any of the declarations (particularly constraints)
  303. being applied a second time.
  304. If :paramref:`_schema.Table.extend_existing` or
  305. :paramref:`_schema.Table.keep_existing` are not set,
  306. and the given name
  307. of the new :class:`_schema.Table` refers to a :class:`_schema.Table`
  308. that is
  309. already present in the target :class:`_schema.MetaData` collection,
  310. and
  311. this :class:`_schema.Table`
  312. specifies additional columns or other constructs
  313. or flags that modify the table's state, an
  314. error is raised. The purpose of these two mutually-exclusive flags
  315. is to specify what action should be taken when a
  316. :class:`_schema.Table`
  317. is specified that matches an existing :class:`_schema.Table`,
  318. yet specifies
  319. additional constructs.
  320. .. seealso::
  321. :paramref:`_schema.Table.extend_existing`
  322. :param listeners: A list of tuples of the form ``(<eventname>, <fn>)``
  323. which will be passed to :func:`.event.listen` upon construction.
  324. This alternate hook to :func:`.event.listen` allows the establishment
  325. of a listener function specific to this :class:`_schema.Table` before
  326. the "autoload" process begins. Historically this has been intended
  327. for use with the :meth:`.DDLEvents.column_reflect` event, however
  328. note that this event hook may now be associated with the
  329. :class:`_schema.MetaData` object directly::
  330. def listen_for_reflect(table, column_info):
  331. "handle the column reflection event"
  332. # ...
  333. t = Table(
  334. 'sometable',
  335. autoload_with=engine,
  336. listeners=[
  337. ('column_reflect', listen_for_reflect)
  338. ])
  339. .. seealso::
  340. :meth:`_events.DDLEvents.column_reflect`
  341. :param must_exist: When ``True``, indicates that this Table must already
  342. be present in the given :class:`_schema.MetaData` collection, else
  343. an exception is raised.
  344. :param prefixes:
  345. A list of strings to insert after CREATE in the CREATE TABLE
  346. statement. They will be separated by spaces.
  347. :param quote: Force quoting of this table's name on or off, corresponding
  348. to ``True`` or ``False``. When left at its default of ``None``,
  349. the column identifier will be quoted according to whether the name is
  350. case sensitive (identifiers with at least one upper case character are
  351. treated as case sensitive), or if it's a reserved word. This flag
  352. is only needed to force quoting of a reserved word which is not known
  353. by the SQLAlchemy dialect.
  354. :param quote_schema: same as 'quote' but applies to the schema identifier.
  355. :param schema: The schema name for this table, which is required if
  356. the table resides in a schema other than the default selected schema
  357. for the engine's database connection. Defaults to ``None``.
  358. If the owning :class:`_schema.MetaData` of this :class:`_schema.Table`
  359. specifies its
  360. own :paramref:`_schema.MetaData.schema` parameter,
  361. then that schema name will
  362. be applied to this :class:`_schema.Table`
  363. if the schema parameter here is set
  364. to ``None``. To set a blank schema name on a :class:`_schema.Table`
  365. that
  366. would otherwise use the schema set on the owning
  367. :class:`_schema.MetaData`,
  368. specify the special symbol :attr:`.BLANK_SCHEMA`.
  369. .. versionadded:: 1.0.14 Added the :attr:`.BLANK_SCHEMA` symbol to
  370. allow a :class:`_schema.Table`
  371. to have a blank schema name even when the
  372. parent :class:`_schema.MetaData` specifies
  373. :paramref:`_schema.MetaData.schema`.
  374. The quoting rules for the schema name are the same as those for the
  375. ``name`` parameter, in that quoting is applied for reserved words or
  376. case-sensitive names; to enable unconditional quoting for the schema
  377. name, specify the flag ``quote_schema=True`` to the constructor, or use
  378. the :class:`.quoted_name` construct to specify the name.
  379. :param comment: Optional string that will render an SQL comment on table
  380. creation.
  381. .. versionadded:: 1.2 Added the :paramref:`_schema.Table.comment`
  382. parameter
  383. to :class:`_schema.Table`.
  384. :param \**kw: Additional keyword arguments not mentioned above are
  385. dialect specific, and passed in the form ``<dialectname>_<argname>``.
  386. See the documentation regarding an individual dialect at
  387. :ref:`dialect_toplevel` for detail on documented arguments.
  388. """
  389. __visit_name__ = "table"
  390. constraints = None
  391. """A collection of all :class:`_schema.Constraint` objects associated with
  392. this :class:`_schema.Table`.
  393. Includes :class:`_schema.PrimaryKeyConstraint`,
  394. :class:`_schema.ForeignKeyConstraint`, :class:`_schema.UniqueConstraint`,
  395. :class:`_schema.CheckConstraint`. A separate collection
  396. :attr:`_schema.Table.foreign_key_constraints` refers to the collection
  397. of all :class:`_schema.ForeignKeyConstraint` objects, and the
  398. :attr:`_schema.Table.primary_key` attribute refers to the single
  399. :class:`_schema.PrimaryKeyConstraint` associated with the
  400. :class:`_schema.Table`.
  401. .. seealso::
  402. :attr:`_schema.Table.constraints`
  403. :attr:`_schema.Table.primary_key`
  404. :attr:`_schema.Table.foreign_key_constraints`
  405. :attr:`_schema.Table.indexes`
  406. :class:`_reflection.Inspector`
  407. """
  408. indexes = None
  409. """A collection of all :class:`_schema.Index` objects associated with this
  410. :class:`_schema.Table`.
  411. .. seealso::
  412. :meth:`_reflection.Inspector.get_indexes`
  413. """
  414. _traverse_internals = TableClause._traverse_internals + [
  415. ("schema", InternalTraversal.dp_string)
  416. ]
  417. def _gen_cache_key(self, anon_map, bindparams):
  418. if self._annotations:
  419. return (self,) + self._annotations_cache_key
  420. else:
  421. return (self,)
  422. @util.deprecated_params(
  423. mustexist=(
  424. "1.4",
  425. "Deprecated alias of :paramref:`_schema.Table.must_exist`",
  426. ),
  427. autoload=(
  428. "2.0",
  429. "The autoload parameter is deprecated and will be removed in "
  430. "version 2.0. Please use the "
  431. "autoload_with parameter, passing an engine or connection.",
  432. ),
  433. )
  434. def __new__(cls, *args, **kw):
  435. if not args and not kw:
  436. # python3k pickle seems to call this
  437. return object.__new__(cls)
  438. try:
  439. name, metadata, args = args[0], args[1], args[2:]
  440. except IndexError:
  441. raise TypeError(
  442. "Table() takes at least two positional-only "
  443. "arguments 'name' and 'metadata'"
  444. )
  445. schema = kw.get("schema", None)
  446. if schema is None:
  447. schema = metadata.schema
  448. elif schema is BLANK_SCHEMA:
  449. schema = None
  450. keep_existing = kw.get("keep_existing", False)
  451. extend_existing = kw.get("extend_existing", False)
  452. if keep_existing and extend_existing:
  453. msg = "keep_existing and extend_existing are mutually exclusive."
  454. raise exc.ArgumentError(msg)
  455. must_exist = kw.pop("must_exist", kw.pop("mustexist", False))
  456. key = _get_table_key(name, schema)
  457. if key in metadata.tables:
  458. if not keep_existing and not extend_existing and bool(args):
  459. raise exc.InvalidRequestError(
  460. "Table '%s' is already defined for this MetaData "
  461. "instance. Specify 'extend_existing=True' "
  462. "to redefine "
  463. "options and columns on an "
  464. "existing Table object." % key
  465. )
  466. table = metadata.tables[key]
  467. if extend_existing:
  468. table._init_existing(*args, **kw)
  469. return table
  470. else:
  471. if must_exist:
  472. raise exc.InvalidRequestError("Table '%s' not defined" % (key))
  473. table = object.__new__(cls)
  474. table.dispatch.before_parent_attach(table, metadata)
  475. metadata._add_table(name, schema, table)
  476. try:
  477. table._init(name, metadata, *args, **kw)
  478. table.dispatch.after_parent_attach(table, metadata)
  479. return table
  480. except Exception:
  481. with util.safe_reraise():
  482. metadata._remove_table(name, schema)
  483. def __init__(self, *args, **kw):
  484. """Constructor for :class:`_schema.Table`.
  485. This method is a no-op. See the top-level
  486. documentation for :class:`_schema.Table`
  487. for constructor arguments.
  488. """
  489. # __init__ is overridden to prevent __new__ from
  490. # calling the superclass constructor.
  491. def _init(self, name, metadata, *args, **kwargs):
  492. super(Table, self).__init__(
  493. quoted_name(name, kwargs.pop("quote", None))
  494. )
  495. self.metadata = metadata
  496. self.schema = kwargs.pop("schema", None)
  497. if self.schema is None:
  498. self.schema = metadata.schema
  499. elif self.schema is BLANK_SCHEMA:
  500. self.schema = None
  501. else:
  502. quote_schema = kwargs.pop("quote_schema", None)
  503. self.schema = quoted_name(self.schema, quote_schema)
  504. self.indexes = set()
  505. self.constraints = set()
  506. PrimaryKeyConstraint(
  507. _implicit_generated=True
  508. )._set_parent_with_dispatch(self)
  509. self.foreign_keys = set()
  510. self._extra_dependencies = set()
  511. if self.schema is not None:
  512. self.fullname = "%s.%s" % (self.schema, self.name)
  513. else:
  514. self.fullname = self.name
  515. autoload_with = kwargs.pop("autoload_with", None)
  516. autoload = kwargs.pop("autoload", autoload_with is not None)
  517. # this argument is only used with _init_existing()
  518. kwargs.pop("autoload_replace", True)
  519. keep_existing = kwargs.pop("keep_existing", False)
  520. extend_existing = kwargs.pop("extend_existing", False)
  521. _extend_on = kwargs.pop("_extend_on", None)
  522. resolve_fks = kwargs.pop("resolve_fks", True)
  523. include_columns = kwargs.pop("include_columns", None)
  524. self.implicit_returning = kwargs.pop("implicit_returning", True)
  525. self.comment = kwargs.pop("comment", None)
  526. if "info" in kwargs:
  527. self.info = kwargs.pop("info")
  528. if "listeners" in kwargs:
  529. listeners = kwargs.pop("listeners")
  530. for evt, fn in listeners:
  531. event.listen(self, evt, fn)
  532. self._prefixes = kwargs.pop("prefixes", None) or []
  533. self._extra_kwargs(**kwargs)
  534. # load column definitions from the database if 'autoload' is defined
  535. # we do it after the table is in the singleton dictionary to support
  536. # circular foreign keys
  537. if autoload:
  538. self._autoload(
  539. metadata,
  540. autoload_with,
  541. include_columns,
  542. _extend_on=_extend_on,
  543. resolve_fks=resolve_fks,
  544. )
  545. # initialize all the column, etc. objects. done after reflection to
  546. # allow user-overrides
  547. self._init_items(
  548. *args,
  549. allow_replacements=extend_existing or keep_existing or autoload
  550. )
  551. def _autoload(
  552. self,
  553. metadata,
  554. autoload_with,
  555. include_columns,
  556. exclude_columns=(),
  557. resolve_fks=True,
  558. _extend_on=None,
  559. ):
  560. if autoload_with is None:
  561. autoload_with = _bind_or_error(
  562. metadata,
  563. msg="No engine is bound to this Table's MetaData. "
  564. "Pass an engine to the Table via "
  565. "autoload_with=<someengine_or_connection>",
  566. )
  567. insp = inspection.inspect(autoload_with)
  568. with insp._inspection_context() as conn_insp:
  569. conn_insp.reflect_table(
  570. self,
  571. include_columns,
  572. exclude_columns,
  573. resolve_fks,
  574. _extend_on=_extend_on,
  575. )
  576. @property
  577. def _sorted_constraints(self):
  578. """Return the set of constraints as a list, sorted by creation
  579. order.
  580. """
  581. return sorted(self.constraints, key=lambda c: c._creation_order)
  582. @property
  583. def foreign_key_constraints(self):
  584. """:class:`_schema.ForeignKeyConstraint` objects referred to by this
  585. :class:`_schema.Table`.
  586. This list is produced from the collection of
  587. :class:`_schema.ForeignKey`
  588. objects currently associated.
  589. .. seealso::
  590. :attr:`_schema.Table.constraints`
  591. :attr:`_schema.Table.foreign_keys`
  592. :attr:`_schema.Table.indexes`
  593. """
  594. return set(fkc.constraint for fkc in self.foreign_keys)
  595. def _init_existing(self, *args, **kwargs):
  596. autoload_with = kwargs.pop("autoload_with", None)
  597. autoload = kwargs.pop("autoload", autoload_with is not None)
  598. autoload_replace = kwargs.pop("autoload_replace", True)
  599. schema = kwargs.pop("schema", None)
  600. _extend_on = kwargs.pop("_extend_on", None)
  601. # these arguments are only used with _init()
  602. kwargs.pop("extend_existing", False)
  603. kwargs.pop("keep_existing", False)
  604. if schema and schema != self.schema:
  605. raise exc.ArgumentError(
  606. "Can't change schema of existing table from '%s' to '%s'",
  607. (self.schema, schema),
  608. )
  609. include_columns = kwargs.pop("include_columns", None)
  610. resolve_fks = kwargs.pop("resolve_fks", True)
  611. if include_columns is not None:
  612. for c in self.c:
  613. if c.name not in include_columns:
  614. self._columns.remove(c)
  615. for key in ("quote", "quote_schema"):
  616. if key in kwargs:
  617. raise exc.ArgumentError(
  618. "Can't redefine 'quote' or 'quote_schema' arguments"
  619. )
  620. if "comment" in kwargs:
  621. self.comment = kwargs.pop("comment", None)
  622. if "info" in kwargs:
  623. self.info = kwargs.pop("info")
  624. if autoload:
  625. if not autoload_replace:
  626. # don't replace columns already present.
  627. # we'd like to do this for constraints also however we don't
  628. # have simple de-duping for unnamed constraints.
  629. exclude_columns = [c.name for c in self.c]
  630. else:
  631. exclude_columns = ()
  632. self._autoload(
  633. self.metadata,
  634. autoload_with,
  635. include_columns,
  636. exclude_columns,
  637. resolve_fks,
  638. _extend_on=_extend_on,
  639. )
  640. self._extra_kwargs(**kwargs)
  641. self._init_items(*args)
  642. def _extra_kwargs(self, **kwargs):
  643. self._validate_dialect_kwargs(kwargs)
  644. def _init_collections(self):
  645. pass
  646. def _reset_exported(self):
  647. pass
  648. @property
  649. def _autoincrement_column(self):
  650. return self.primary_key._autoincrement_column
  651. @property
  652. def key(self):
  653. """Return the 'key' for this :class:`_schema.Table`.
  654. This value is used as the dictionary key within the
  655. :attr:`_schema.MetaData.tables` collection. It is typically the same
  656. as that of :attr:`_schema.Table.name` for a table with no
  657. :attr:`_schema.Table.schema`
  658. set; otherwise it is typically of the form
  659. ``schemaname.tablename``.
  660. """
  661. return _get_table_key(self.name, self.schema)
  662. def __repr__(self):
  663. return "Table(%s)" % ", ".join(
  664. [repr(self.name)]
  665. + [repr(self.metadata)]
  666. + [repr(x) for x in self.columns]
  667. + ["%s=%s" % (k, repr(getattr(self, k))) for k in ["schema"]]
  668. )
  669. def __str__(self):
  670. return _get_table_key(self.description, self.schema)
  671. @property
  672. def bind(self):
  673. """Return the connectable associated with this Table."""
  674. return self.metadata and self.metadata.bind or None
  675. def add_is_dependent_on(self, table):
  676. """Add a 'dependency' for this Table.
  677. This is another Table object which must be created
  678. first before this one can, or dropped after this one.
  679. Usually, dependencies between tables are determined via
  680. ForeignKey objects. However, for other situations that
  681. create dependencies outside of foreign keys (rules, inheriting),
  682. this method can manually establish such a link.
  683. """
  684. self._extra_dependencies.add(table)
  685. def append_column(self, column, replace_existing=False):
  686. """Append a :class:`_schema.Column` to this :class:`_schema.Table`.
  687. The "key" of the newly added :class:`_schema.Column`, i.e. the
  688. value of its ``.key`` attribute, will then be available
  689. in the ``.c`` collection of this :class:`_schema.Table`, and the
  690. column definition will be included in any CREATE TABLE, SELECT,
  691. UPDATE, etc. statements generated from this :class:`_schema.Table`
  692. construct.
  693. Note that this does **not** change the definition of the table
  694. as it exists within any underlying database, assuming that
  695. table has already been created in the database. Relational
  696. databases support the addition of columns to existing tables
  697. using the SQL ALTER command, which would need to be
  698. emitted for an already-existing table that doesn't contain
  699. the newly added column.
  700. :param replace_existing: When ``True``, allows replacing existing
  701. columns. When ``False``, the default, an warning will be raised
  702. if a column with the same ``.key`` already exists. A future
  703. version of sqlalchemy will instead rise a warning.
  704. .. versionadded:: 1.4.0
  705. """
  706. column._set_parent_with_dispatch(
  707. self, allow_replacements=replace_existing
  708. )
  709. def append_constraint(self, constraint):
  710. """Append a :class:`_schema.Constraint` to this
  711. :class:`_schema.Table`.
  712. This has the effect of the constraint being included in any
  713. future CREATE TABLE statement, assuming specific DDL creation
  714. events have not been associated with the given
  715. :class:`_schema.Constraint` object.
  716. Note that this does **not** produce the constraint within the
  717. relational database automatically, for a table that already exists
  718. in the database. To add a constraint to an
  719. existing relational database table, the SQL ALTER command must
  720. be used. SQLAlchemy also provides the
  721. :class:`.AddConstraint` construct which can produce this SQL when
  722. invoked as an executable clause.
  723. """
  724. constraint._set_parent_with_dispatch(self)
  725. def _set_parent(self, metadata, **kw):
  726. metadata._add_table(self.name, self.schema, self)
  727. self.metadata = metadata
  728. @util.deprecated(
  729. "1.4",
  730. "The :meth:`_schema.Table.exists` method is deprecated and will be "
  731. "removed in a future release. Please refer to "
  732. ":meth:`_reflection.Inspector.has_table`.",
  733. )
  734. def exists(self, bind=None):
  735. """Return True if this table exists."""
  736. if bind is None:
  737. bind = _bind_or_error(self)
  738. insp = inspection.inspect(bind)
  739. return insp.has_table(self.name, schema=self.schema)
  740. def create(self, bind=None, checkfirst=False):
  741. """Issue a ``CREATE`` statement for this
  742. :class:`_schema.Table`, using the given :class:`.Connectable`
  743. for connectivity.
  744. .. note:: the "bind" argument will be required in
  745. SQLAlchemy 2.0.
  746. .. seealso::
  747. :meth:`_schema.MetaData.create_all`.
  748. """
  749. if bind is None:
  750. bind = _bind_or_error(self)
  751. bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
  752. def drop(self, bind=None, checkfirst=False):
  753. """Issue a ``DROP`` statement for this
  754. :class:`_schema.Table`, using the given :class:`.Connectable`
  755. for connectivity.
  756. .. note:: the "bind" argument will be required in
  757. SQLAlchemy 2.0.
  758. .. seealso::
  759. :meth:`_schema.MetaData.drop_all`.
  760. """
  761. if bind is None:
  762. bind = _bind_or_error(self)
  763. bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
  764. @util.deprecated(
  765. "1.4",
  766. ":meth:`_schema.Table.tometadata` is renamed to "
  767. ":meth:`_schema.Table.to_metadata`",
  768. )
  769. def tometadata(
  770. self,
  771. metadata,
  772. schema=RETAIN_SCHEMA,
  773. referred_schema_fn=None,
  774. name=None,
  775. ):
  776. """Return a copy of this :class:`_schema.Table`
  777. associated with a different
  778. :class:`_schema.MetaData`.
  779. See :meth:`_schema.Table.to_metadata` for a full description.
  780. """
  781. return self.to_metadata(
  782. metadata,
  783. schema=schema,
  784. referred_schema_fn=referred_schema_fn,
  785. name=name,
  786. )
  787. def to_metadata(
  788. self,
  789. metadata,
  790. schema=RETAIN_SCHEMA,
  791. referred_schema_fn=None,
  792. name=None,
  793. ):
  794. """Return a copy of this :class:`_schema.Table` associated with a
  795. different :class:`_schema.MetaData`.
  796. E.g.::
  797. m1 = MetaData()
  798. user = Table('user', m1, Column('id', Integer, primary_key=True))
  799. m2 = MetaData()
  800. user_copy = user.to_metadata(m2)
  801. .. versionchanged:: 1.4 The :meth:`_schema.Table.to_metadata` function
  802. was renamed from :meth:`_schema.Table.tometadata`.
  803. :param metadata: Target :class:`_schema.MetaData` object,
  804. into which the
  805. new :class:`_schema.Table` object will be created.
  806. :param schema: optional string name indicating the target schema.
  807. Defaults to the special symbol :attr:`.RETAIN_SCHEMA` which indicates
  808. that no change to the schema name should be made in the new
  809. :class:`_schema.Table`. If set to a string name, the new
  810. :class:`_schema.Table`
  811. will have this new name as the ``.schema``. If set to ``None``, the
  812. schema will be set to that of the schema set on the target
  813. :class:`_schema.MetaData`, which is typically ``None`` as well,
  814. unless
  815. set explicitly::
  816. m2 = MetaData(schema='newschema')
  817. # user_copy_one will have "newschema" as the schema name
  818. user_copy_one = user.to_metadata(m2, schema=None)
  819. m3 = MetaData() # schema defaults to None
  820. # user_copy_two will have None as the schema name
  821. user_copy_two = user.to_metadata(m3, schema=None)
  822. :param referred_schema_fn: optional callable which can be supplied
  823. in order to provide for the schema name that should be assigned
  824. to the referenced table of a :class:`_schema.ForeignKeyConstraint`.
  825. The callable accepts this parent :class:`_schema.Table`, the
  826. target schema that we are changing to, the
  827. :class:`_schema.ForeignKeyConstraint` object, and the existing
  828. "target schema" of that constraint. The function should return the
  829. string schema name that should be applied.
  830. E.g.::
  831. def referred_schema_fn(table, to_schema,
  832. constraint, referred_schema):
  833. if referred_schema == 'base_tables':
  834. return referred_schema
  835. else:
  836. return to_schema
  837. new_table = table.to_metadata(m2, schema="alt_schema",
  838. referred_schema_fn=referred_schema_fn)
  839. .. versionadded:: 0.9.2
  840. :param name: optional string name indicating the target table name.
  841. If not specified or None, the table name is retained. This allows
  842. a :class:`_schema.Table` to be copied to the same
  843. :class:`_schema.MetaData` target
  844. with a new name.
  845. .. versionadded:: 1.0.0
  846. """
  847. if name is None:
  848. name = self.name
  849. if schema is RETAIN_SCHEMA:
  850. schema = self.schema
  851. elif schema is None:
  852. schema = metadata.schema
  853. key = _get_table_key(name, schema)
  854. if key in metadata.tables:
  855. util.warn(
  856. "Table '%s' already exists within the given "
  857. "MetaData - not copying." % self.description
  858. )
  859. return metadata.tables[key]
  860. args = []
  861. for c in self.columns:
  862. args.append(c._copy(schema=schema))
  863. table = Table(
  864. name,
  865. metadata,
  866. schema=schema,
  867. comment=self.comment,
  868. *args,
  869. **self.kwargs
  870. )
  871. for c in self.constraints:
  872. if isinstance(c, ForeignKeyConstraint):
  873. referred_schema = c._referred_schema
  874. if referred_schema_fn:
  875. fk_constraint_schema = referred_schema_fn(
  876. self, schema, c, referred_schema
  877. )
  878. else:
  879. fk_constraint_schema = (
  880. schema if referred_schema == self.schema else None
  881. )
  882. table.append_constraint(
  883. c._copy(schema=fk_constraint_schema, target_table=table)
  884. )
  885. elif not c._type_bound:
  886. # skip unique constraints that would be generated
  887. # by the 'unique' flag on Column
  888. if c._column_flag:
  889. continue
  890. table.append_constraint(
  891. c._copy(schema=schema, target_table=table)
  892. )
  893. for index in self.indexes:
  894. # skip indexes that would be generated
  895. # by the 'index' flag on Column
  896. if index._column_flag:
  897. continue
  898. Index(
  899. index.name,
  900. unique=index.unique,
  901. *[
  902. _copy_expression(expr, self, table)
  903. for expr in index.expressions
  904. ],
  905. _table=table,
  906. **index.kwargs
  907. )
  908. return self._schema_item_copy(table)
  909. class Column(DialectKWArgs, SchemaItem, ColumnClause):
  910. """Represents a column in a database table."""
  911. __visit_name__ = "column"
  912. inherit_cache = True
  913. def __init__(self, *args, **kwargs):
  914. r"""
  915. Construct a new ``Column`` object.
  916. :param name: The name of this column as represented in the database.
  917. This argument may be the first positional argument, or specified
  918. via keyword.
  919. Names which contain no upper case characters
  920. will be treated as case insensitive names, and will not be quoted
  921. unless they are a reserved word. Names with any number of upper
  922. case characters will be quoted and sent exactly. Note that this
  923. behavior applies even for databases which standardize upper
  924. case names as case insensitive such as Oracle.
  925. The name field may be omitted at construction time and applied
  926. later, at any time before the Column is associated with a
  927. :class:`_schema.Table`. This is to support convenient
  928. usage within the :mod:`~sqlalchemy.ext.declarative` extension.
  929. :param type\_: The column's type, indicated using an instance which
  930. subclasses :class:`~sqlalchemy.types.TypeEngine`. If no arguments
  931. are required for the type, the class of the type can be sent
  932. as well, e.g.::
  933. # use a type with arguments
  934. Column('data', String(50))
  935. # use no arguments
  936. Column('level', Integer)
  937. The ``type`` argument may be the second positional argument
  938. or specified by keyword.
  939. If the ``type`` is ``None`` or is omitted, it will first default to
  940. the special type :class:`.NullType`. If and when this
  941. :class:`_schema.Column` is made to refer to another column using
  942. :class:`_schema.ForeignKey` and/or
  943. :class:`_schema.ForeignKeyConstraint`, the type
  944. of the remote-referenced column will be copied to this column as
  945. well, at the moment that the foreign key is resolved against that
  946. remote :class:`_schema.Column` object.
  947. .. versionchanged:: 0.9.0
  948. Support for propagation of type to a :class:`_schema.Column`
  949. from its
  950. :class:`_schema.ForeignKey` object has been improved and should be
  951. more reliable and timely.
  952. :param \*args: Additional positional arguments include various
  953. :class:`.SchemaItem` derived constructs which will be applied
  954. as options to the column. These include instances of
  955. :class:`.Constraint`, :class:`_schema.ForeignKey`,
  956. :class:`.ColumnDefault`, :class:`.Sequence`, :class:`.Computed`
  957. :class:`.Identity`. In some cases an
  958. equivalent keyword argument is available such as ``server_default``,
  959. ``default`` and ``unique``.
  960. :param autoincrement: Set up "auto increment" semantics for an integer
  961. primary key column. The default value is the string ``"auto"``
  962. which indicates that a single-column primary key that is of
  963. an INTEGER type with no stated client-side or python-side defaults
  964. should receive auto increment semantics automatically;
  965. all other varieties of primary key columns will not. This
  966. includes that :term:`DDL` such as PostgreSQL SERIAL or MySQL
  967. AUTO_INCREMENT will be emitted for this column during a table
  968. create, as well as that the column is assumed to generate new
  969. integer primary key values when an INSERT statement invokes which
  970. will be retrieved by the dialect. When used in conjunction with
  971. :class:`.Identity` on a dialect that supports it, this parameter
  972. has no effect.
  973. The flag may be set to ``True`` to indicate that a column which
  974. is part of a composite (e.g. multi-column) primary key should
  975. have autoincrement semantics, though note that only one column
  976. within a primary key may have this setting. It can also
  977. be set to ``True`` to indicate autoincrement semantics on a
  978. column that has a client-side or server-side default configured,
  979. however note that not all dialects can accommodate all styles
  980. of default as an "autoincrement". It can also be
  981. set to ``False`` on a single-column primary key that has a
  982. datatype of INTEGER in order to disable auto increment semantics
  983. for that column.
  984. .. versionchanged:: 1.1 The autoincrement flag now defaults to
  985. ``"auto"`` which indicates autoincrement semantics by default
  986. for single-column integer primary keys only; for composite
  987. (multi-column) primary keys, autoincrement is never implicitly
  988. enabled; as always, ``autoincrement=True`` will allow for
  989. at most one of those columns to be an "autoincrement" column.
  990. ``autoincrement=True`` may also be set on a
  991. :class:`_schema.Column`
  992. that has an explicit client-side or server-side default,
  993. subject to limitations of the backend database and dialect.
  994. The setting *only* has an effect for columns which are:
  995. * Integer derived (i.e. INT, SMALLINT, BIGINT).
  996. * Part of the primary key
  997. * Not referring to another column via :class:`_schema.ForeignKey`,
  998. unless
  999. the value is specified as ``'ignore_fk'``::
  1000. # turn on autoincrement for this column despite
  1001. # the ForeignKey()
  1002. Column('id', ForeignKey('other.id'),
  1003. primary_key=True, autoincrement='ignore_fk')
  1004. It is typically not desirable to have "autoincrement" enabled on a
  1005. column that refers to another via foreign key, as such a column is
  1006. required to refer to a value that originates from elsewhere.
  1007. The setting has these two effects on columns that meet the
  1008. above criteria:
  1009. * DDL issued for the column will include database-specific
  1010. keywords intended to signify this column as an
  1011. "autoincrement" column, such as AUTO INCREMENT on MySQL,
  1012. SERIAL on PostgreSQL, and IDENTITY on MS-SQL. It does
  1013. *not* issue AUTOINCREMENT for SQLite since this is a
  1014. special SQLite flag that is not required for autoincrementing
  1015. behavior.
  1016. .. seealso::
  1017. :ref:`sqlite_autoincrement`
  1018. * The column will be considered to be available using an
  1019. "autoincrement" method specific to the backend database, such
  1020. as calling upon ``cursor.lastrowid``, using RETURNING in an
  1021. INSERT statement to get at a sequence-generated value, or using
  1022. special functions such as "SELECT scope_identity()".
  1023. These methods are highly specific to the DBAPIs and databases in
  1024. use and vary greatly, so care should be taken when associating
  1025. ``autoincrement=True`` with a custom default generation function.
  1026. :param default: A scalar, Python callable, or
  1027. :class:`_expression.ColumnElement` expression representing the
  1028. *default value* for this column, which will be invoked upon insert
  1029. if this column is otherwise not specified in the VALUES clause of
  1030. the insert. This is a shortcut to using :class:`.ColumnDefault` as
  1031. a positional argument; see that class for full detail on the
  1032. structure of the argument.
  1033. Contrast this argument to
  1034. :paramref:`_schema.Column.server_default`
  1035. which creates a default generator on the database side.
  1036. .. seealso::
  1037. :ref:`metadata_defaults_toplevel`
  1038. :param doc: optional String that can be used by the ORM or similar
  1039. to document attributes on the Python side. This attribute does
  1040. **not** render SQL comments; use the
  1041. :paramref:`_schema.Column.comment`
  1042. parameter for this purpose.
  1043. :param key: An optional string identifier which will identify this
  1044. ``Column`` object on the :class:`_schema.Table`.
  1045. When a key is provided,
  1046. this is the only identifier referencing the ``Column`` within the
  1047. application, including ORM attribute mapping; the ``name`` field
  1048. is used only when rendering SQL.
  1049. :param index: When ``True``, indicates that a :class:`_schema.Index`
  1050. construct will be automatically generated for this
  1051. :class:`_schema.Column`, which will result in a "CREATE INDEX"
  1052. statement being emitted for the :class:`_schema.Table` when the DDL
  1053. create operation is invoked.
  1054. Using this flag is equivalent to making use of the
  1055. :class:`_schema.Index` construct explicitly at the level of the
  1056. :class:`_schema.Table` construct itself::
  1057. Table(
  1058. "some_table",
  1059. metadata,
  1060. Column("x", Integer),
  1061. Index("ix_some_table_x", "x")
  1062. )
  1063. To add the :paramref:`_schema.Index.unique` flag to the
  1064. :class:`_schema.Index`, set both the
  1065. :paramref:`_schema.Column.unique` and
  1066. :paramref:`_schema.Column.index` flags to True simultaneously,
  1067. which will have the effect of rendering the "CREATE UNIQUE INDEX"
  1068. DDL instruction instead of "CREATE INDEX".
  1069. The name of the index is generated using the
  1070. :ref:`default naming convention <constraint_default_naming_convention>`
  1071. which for the :class:`_schema.Index` construct is of the form
  1072. ``ix_<tablename>_<columnname>``.
  1073. As this flag is intended only as a convenience for the common case
  1074. of adding a single-column, default configured index to a table
  1075. definition, explicit use of the :class:`_schema.Index` construct
  1076. should be preferred for most use cases, including composite indexes
  1077. that encompass more than one column, indexes with SQL expressions
  1078. or ordering, backend-specific index configuration options, and
  1079. indexes that use a specific name.
  1080. .. note:: the :attr:`_schema.Column.index` attribute on
  1081. :class:`_schema.Column`
  1082. **does not indicate** if this column is indexed or not, only
  1083. if this flag was explicitly set here. To view indexes on
  1084. a column, view the :attr:`_schema.Table.indexes` collection
  1085. or use :meth:`_reflection.Inspector.get_indexes`.
  1086. .. seealso::
  1087. :ref:`schema_indexes`
  1088. :ref:`constraint_naming_conventions`
  1089. :paramref:`_schema.Column.unique`
  1090. :param info: Optional data dictionary which will be populated into the
  1091. :attr:`.SchemaItem.info` attribute of this object.
  1092. :param nullable: When set to ``False``, will cause the "NOT NULL"
  1093. phrase to be added when generating DDL for the column. When
  1094. ``True``, will normally generate nothing (in SQL this defaults to
  1095. "NULL"), except in some very specific backend-specific edge cases
  1096. where "NULL" may render explicitly.
  1097. Defaults to ``True`` unless :paramref:`_schema.Column.primary_key`
  1098. is also ``True`` or the column specifies a :class:`_sql.Identity`,
  1099. in which case it defaults to ``False``.
  1100. This parameter is only used when issuing CREATE TABLE statements.
  1101. .. note::
  1102. When the column specifies a :class:`_sql.Identity` this
  1103. parameter is in general ignored by the DDL compiler. The
  1104. PostgreSQL database allows nullable identity column by
  1105. setting this parameter to ``True`` explicitly.
  1106. :param onupdate: A scalar, Python callable, or
  1107. :class:`~sqlalchemy.sql.expression.ClauseElement` representing a
  1108. default value to be applied to the column within UPDATE
  1109. statements, which will be invoked upon update if this column is not
  1110. present in the SET clause of the update. This is a shortcut to
  1111. using :class:`.ColumnDefault` as a positional argument with
  1112. ``for_update=True``.
  1113. .. seealso::
  1114. :ref:`metadata_defaults` - complete discussion of onupdate
  1115. :param primary_key: If ``True``, marks this column as a primary key
  1116. column. Multiple columns can have this flag set to specify
  1117. composite primary keys. As an alternative, the primary key of a
  1118. :class:`_schema.Table` can be specified via an explicit
  1119. :class:`.PrimaryKeyConstraint` object.
  1120. :param server_default: A :class:`.FetchedValue` instance, str, Unicode
  1121. or :func:`~sqlalchemy.sql.expression.text` construct representing
  1122. the DDL DEFAULT value for the column.
  1123. String types will be emitted as-is, surrounded by single quotes::
  1124. Column('x', Text, server_default="val")
  1125. x TEXT DEFAULT 'val'
  1126. A :func:`~sqlalchemy.sql.expression.text` expression will be
  1127. rendered as-is, without quotes::
  1128. Column('y', DateTime, server_default=text('NOW()'))
  1129. y DATETIME DEFAULT NOW()
  1130. Strings and text() will be converted into a
  1131. :class:`.DefaultClause` object upon initialization.
  1132. Use :class:`.FetchedValue` to indicate that an already-existing
  1133. column will generate a default value on the database side which
  1134. will be available to SQLAlchemy for post-fetch after inserts. This
  1135. construct does not specify any DDL and the implementation is left
  1136. to the database, such as via a trigger.
  1137. .. seealso::
  1138. :ref:`server_defaults` - complete discussion of server side
  1139. defaults
  1140. :param server_onupdate: A :class:`.FetchedValue` instance
  1141. representing a database-side default generation function,
  1142. such as a trigger. This
  1143. indicates to SQLAlchemy that a newly generated value will be
  1144. available after updates. This construct does not actually
  1145. implement any kind of generation function within the database,
  1146. which instead must be specified separately.
  1147. .. warning:: This directive **does not** currently produce MySQL's
  1148. "ON UPDATE CURRENT_TIMESTAMP()" clause. See
  1149. :ref:`mysql_timestamp_onupdate` for background on how to
  1150. produce this clause.
  1151. .. seealso::
  1152. :ref:`triggered_columns`
  1153. :param quote: Force quoting of this column's name on or off,
  1154. corresponding to ``True`` or ``False``. When left at its default
  1155. of ``None``, the column identifier will be quoted according to
  1156. whether the name is case sensitive (identifiers with at least one
  1157. upper case character are treated as case sensitive), or if it's a
  1158. reserved word. This flag is only needed to force quoting of a
  1159. reserved word which is not known by the SQLAlchemy dialect.
  1160. :param unique: When ``True``, and the :paramref:`_schema.Column.index`
  1161. parameter is left at its default value of ``False``,
  1162. indicates that a :class:`_schema.UniqueConstraint`
  1163. construct will be automatically generated for this
  1164. :class:`_schema.Column`,
  1165. which will result in a "UNIQUE CONSTRAINT" clause referring
  1166. to this column being included
  1167. in the ``CREATE TABLE`` statement emitted, when the DDL create
  1168. operation for the :class:`_schema.Table` object is invoked.
  1169. When this flag is ``True`` while the
  1170. :paramref:`_schema.Column.index` parameter is simultaneously
  1171. set to ``True``, the effect instead is that a
  1172. :class:`_schema.Index` construct which includes the
  1173. :paramref:`_schema.Index.unique` parameter set to ``True``
  1174. is generated. See the documentation for
  1175. :paramref:`_schema.Column.index` for additional detail.
  1176. Using this flag is equivalent to making use of the
  1177. :class:`_schema.UniqueConstraint` construct explicitly at the
  1178. level of the :class:`_schema.Table` construct itself::
  1179. Table(
  1180. "some_table",
  1181. metadata,
  1182. Column("x", Integer),
  1183. UniqueConstraint("x")
  1184. )
  1185. The :paramref:`_schema.UniqueConstraint.name` parameter
  1186. of the unique constraint object is left at its default value
  1187. of ``None``; in the absence of a :ref:`naming convention <constraint_naming_conventions>`
  1188. for the enclosing :class:`_schema.MetaData`, the UNIQUE CONSTRAINT
  1189. construct will be emitted as unnamed, which typically invokes
  1190. a database-specific naming convention to take place.
  1191. As this flag is intended only as a convenience for the common case
  1192. of adding a single-column, default configured unique constraint to a table
  1193. definition, explicit use of the :class:`_schema.UniqueConstraint` construct
  1194. should be preferred for most use cases, including composite constraints
  1195. that encompass more than one column, backend-specific index configuration options, and
  1196. constraints that use a specific name.
  1197. .. note:: the :attr:`_schema.Column.unique` attribute on
  1198. :class:`_schema.Column`
  1199. **does not indicate** if this column has a unique constraint or
  1200. not, only if this flag was explicitly set here. To view
  1201. indexes and unique constraints that may involve this column,
  1202. view the
  1203. :attr:`_schema.Table.indexes` and/or
  1204. :attr:`_schema.Table.constraints` collections or use
  1205. :meth:`_reflection.Inspector.get_indexes` and/or
  1206. :meth:`_reflection.Inspector.get_unique_constraints`
  1207. .. seealso::
  1208. :ref:`schema_unique_constraint`
  1209. :ref:`constraint_naming_conventions`
  1210. :paramref:`_schema.Column.index`
  1211. :param system: When ``True``, indicates this is a "system" column,
  1212. that is a column which is automatically made available by the
  1213. database, and should not be included in the columns list for a
  1214. ``CREATE TABLE`` statement.
  1215. For more elaborate scenarios where columns should be
  1216. conditionally rendered differently on different backends,
  1217. consider custom compilation rules for :class:`.CreateColumn`.
  1218. :param comment: Optional string that will render an SQL comment on
  1219. table creation.
  1220. .. versionadded:: 1.2 Added the
  1221. :paramref:`_schema.Column.comment`
  1222. parameter to :class:`_schema.Column`.
  1223. """ # noqa E501
  1224. name = kwargs.pop("name", None)
  1225. type_ = kwargs.pop("type_", None)
  1226. args = list(args)
  1227. if args:
  1228. if isinstance(args[0], util.string_types):
  1229. if name is not None:
  1230. raise exc.ArgumentError(
  1231. "May not pass name positionally and as a keyword."
  1232. )
  1233. name = args.pop(0)
  1234. if args:
  1235. coltype = args[0]
  1236. if hasattr(coltype, "_sqla_type"):
  1237. if type_ is not None:
  1238. raise exc.ArgumentError(
  1239. "May not pass type_ positionally and as a keyword."
  1240. )
  1241. type_ = args.pop(0)
  1242. if name is not None:
  1243. name = quoted_name(name, kwargs.pop("quote", None))
  1244. elif "quote" in kwargs:
  1245. raise exc.ArgumentError(
  1246. "Explicit 'name' is required when " "sending 'quote' argument"
  1247. )
  1248. super(Column, self).__init__(name, type_)
  1249. self.key = kwargs.pop("key", name)
  1250. self.primary_key = primary_key = kwargs.pop("primary_key", False)
  1251. self._user_defined_nullable = udn = kwargs.pop(
  1252. "nullable", NULL_UNSPECIFIED
  1253. )
  1254. if udn is not NULL_UNSPECIFIED:
  1255. self.nullable = udn
  1256. else:
  1257. self.nullable = not primary_key
  1258. self.default = kwargs.pop("default", None)
  1259. self.server_default = kwargs.pop("server_default", None)
  1260. self.server_onupdate = kwargs.pop("server_onupdate", None)
  1261. # these default to None because .index and .unique is *not*
  1262. # an informational flag about Column - there can still be an
  1263. # Index or UniqueConstraint referring to this Column.
  1264. self.index = kwargs.pop("index", None)
  1265. self.unique = kwargs.pop("unique", None)
  1266. self.system = kwargs.pop("system", False)
  1267. self.doc = kwargs.pop("doc", None)
  1268. self.onupdate = kwargs.pop("onupdate", None)
  1269. self.autoincrement = kwargs.pop("autoincrement", "auto")
  1270. self.constraints = set()
  1271. self.foreign_keys = set()
  1272. self.comment = kwargs.pop("comment", None)
  1273. self.computed = None
  1274. self.identity = None
  1275. # check if this Column is proxying another column
  1276. if "_proxies" in kwargs:
  1277. self._proxies = kwargs.pop("_proxies")
  1278. # otherwise, add DDL-related events
  1279. elif isinstance(self.type, SchemaEventTarget):
  1280. self.type._set_parent_with_dispatch(self)
  1281. if self.default is not None:
  1282. if isinstance(self.default, (ColumnDefault, Sequence)):
  1283. args.append(self.default)
  1284. else:
  1285. if getattr(self.type, "_warn_on_bytestring", False):
  1286. if isinstance(self.default, util.binary_type):
  1287. util.warn(
  1288. "Unicode column '%s' has non-unicode "
  1289. "default value %r specified."
  1290. % (self.key, self.default)
  1291. )
  1292. args.append(ColumnDefault(self.default))
  1293. if self.server_default is not None:
  1294. if isinstance(self.server_default, FetchedValue):
  1295. args.append(self.server_default._as_for_update(False))
  1296. else:
  1297. args.append(DefaultClause(self.server_default))
  1298. if self.onupdate is not None:
  1299. if isinstance(self.onupdate, (ColumnDefault, Sequence)):
  1300. args.append(self.onupdate)
  1301. else:
  1302. args.append(ColumnDefault(self.onupdate, for_update=True))
  1303. if self.server_onupdate is not None:
  1304. if isinstance(self.server_onupdate, FetchedValue):
  1305. args.append(self.server_onupdate._as_for_update(True))
  1306. else:
  1307. args.append(
  1308. DefaultClause(self.server_onupdate, for_update=True)
  1309. )
  1310. self._init_items(*args)
  1311. util.set_creation_order(self)
  1312. if "info" in kwargs:
  1313. self.info = kwargs.pop("info")
  1314. self._extra_kwargs(**kwargs)
  1315. foreign_keys = None
  1316. """A collection of all :class:`_schema.ForeignKey` marker objects
  1317. associated with this :class:`_schema.Column`.
  1318. Each object is a member of a :class:`_schema.Table`-wide
  1319. :class:`_schema.ForeignKeyConstraint`.
  1320. .. seealso::
  1321. :attr:`_schema.Table.foreign_keys`
  1322. """
  1323. index = None
  1324. """The value of the :paramref:`_schema.Column.index` parameter.
  1325. Does not indicate if this :class:`_schema.Column` is actually indexed
  1326. or not; use :attr:`_schema.Table.indexes`.
  1327. .. seealso::
  1328. :attr:`_schema.Table.indexes`
  1329. """
  1330. unique = None
  1331. """The value of the :paramref:`_schema.Column.unique` parameter.
  1332. Does not indicate if this :class:`_schema.Column` is actually subject to
  1333. a unique constraint or not; use :attr:`_schema.Table.indexes` and
  1334. :attr:`_schema.Table.constraints`.
  1335. .. seealso::
  1336. :attr:`_schema.Table.indexes`
  1337. :attr:`_schema.Table.constraints`.
  1338. """
  1339. def _extra_kwargs(self, **kwargs):
  1340. self._validate_dialect_kwargs(kwargs)
  1341. def __str__(self):
  1342. if self.name is None:
  1343. return "(no name)"
  1344. elif self.table is not None:
  1345. if self.table.named_with_column:
  1346. return self.table.description + "." + self.description
  1347. else:
  1348. return self.description
  1349. else:
  1350. return self.description
  1351. def references(self, column):
  1352. """Return True if this Column references the given column via foreign
  1353. key."""
  1354. for fk in self.foreign_keys:
  1355. if fk.column.proxy_set.intersection(column.proxy_set):
  1356. return True
  1357. else:
  1358. return False
  1359. def append_foreign_key(self, fk):
  1360. fk._set_parent_with_dispatch(self)
  1361. def __repr__(self):
  1362. kwarg = []
  1363. if self.key != self.name:
  1364. kwarg.append("key")
  1365. if self.primary_key:
  1366. kwarg.append("primary_key")
  1367. if not self.nullable:
  1368. kwarg.append("nullable")
  1369. if self.onupdate:
  1370. kwarg.append("onupdate")
  1371. if self.default:
  1372. kwarg.append("default")
  1373. if self.server_default:
  1374. kwarg.append("server_default")
  1375. if self.comment:
  1376. kwarg.append("comment")
  1377. return "Column(%s)" % ", ".join(
  1378. [repr(self.name)]
  1379. + [repr(self.type)]
  1380. + [repr(x) for x in self.foreign_keys if x is not None]
  1381. + [repr(x) for x in self.constraints]
  1382. + [
  1383. (
  1384. self.table is not None
  1385. and "table=<%s>" % self.table.description
  1386. or "table=None"
  1387. )
  1388. ]
  1389. + ["%s=%s" % (k, repr(getattr(self, k))) for k in kwarg]
  1390. )
  1391. def _set_parent(self, table, allow_replacements=True):
  1392. if not self.name:
  1393. raise exc.ArgumentError(
  1394. "Column must be constructed with a non-blank name or "
  1395. "assign a non-blank .name before adding to a Table."
  1396. )
  1397. self._reset_memoizations()
  1398. if self.key is None:
  1399. self.key = self.name
  1400. existing = getattr(self, "table", None)
  1401. if existing is not None and existing is not table:
  1402. raise exc.ArgumentError(
  1403. "Column object '%s' already assigned to Table '%s'"
  1404. % (self.key, existing.description)
  1405. )
  1406. if self.key in table._columns:
  1407. col = table._columns.get(self.key)
  1408. if col is not self:
  1409. if not allow_replacements:
  1410. util.warn_deprecated(
  1411. "A column with name '%s' is already present "
  1412. "in table '%s'. Please use method "
  1413. ":meth:`_schema.Table.append_column` with the "
  1414. "parameter ``replace_existing=True`` to replace an "
  1415. "existing column." % (self.key, table.name),
  1416. "1.4",
  1417. )
  1418. for fk in col.foreign_keys:
  1419. table.foreign_keys.remove(fk)
  1420. if fk.constraint in table.constraints:
  1421. # this might have been removed
  1422. # already, if it's a composite constraint
  1423. # and more than one col being replaced
  1424. table.constraints.remove(fk.constraint)
  1425. table._columns.replace(self)
  1426. self.table = table
  1427. if self.primary_key:
  1428. table.primary_key._replace(self)
  1429. elif self.key in table.primary_key:
  1430. raise exc.ArgumentError(
  1431. "Trying to redefine primary-key column '%s' as a "
  1432. "non-primary-key column on table '%s'"
  1433. % (self.key, table.fullname)
  1434. )
  1435. if self.index:
  1436. if isinstance(self.index, util.string_types):
  1437. raise exc.ArgumentError(
  1438. "The 'index' keyword argument on Column is boolean only. "
  1439. "To create indexes with a specific name, create an "
  1440. "explicit Index object external to the Table."
  1441. )
  1442. table.append_constraint(
  1443. Index(
  1444. None, self.key, unique=bool(self.unique), _column_flag=True
  1445. )
  1446. )
  1447. elif self.unique:
  1448. if isinstance(self.unique, util.string_types):
  1449. raise exc.ArgumentError(
  1450. "The 'unique' keyword argument on Column is boolean "
  1451. "only. To create unique constraints or indexes with a "
  1452. "specific name, append an explicit UniqueConstraint to "
  1453. "the Table's list of elements, or create an explicit "
  1454. "Index object external to the Table."
  1455. )
  1456. table.append_constraint(
  1457. UniqueConstraint(self.key, _column_flag=True)
  1458. )
  1459. self._setup_on_memoized_fks(lambda fk: fk._set_remote_table(table))
  1460. if self.identity and (
  1461. isinstance(self.default, Sequence)
  1462. or isinstance(self.onupdate, Sequence)
  1463. ):
  1464. raise exc.ArgumentError(
  1465. "An column cannot specify both Identity and Sequence."
  1466. )
  1467. def _setup_on_memoized_fks(self, fn):
  1468. fk_keys = [
  1469. ((self.table.key, self.key), False),
  1470. ((self.table.key, self.name), True),
  1471. ]
  1472. for fk_key, link_to_name in fk_keys:
  1473. if fk_key in self.table.metadata._fk_memos:
  1474. for fk in self.table.metadata._fk_memos[fk_key]:
  1475. if fk.link_to_name is link_to_name:
  1476. fn(fk)
  1477. def _on_table_attach(self, fn):
  1478. if self.table is not None:
  1479. fn(self, self.table)
  1480. else:
  1481. event.listen(self, "after_parent_attach", fn)
  1482. @util.deprecated(
  1483. "1.4",
  1484. "The :meth:`_schema.Column.copy` method is deprecated "
  1485. "and will be removed in a future release.",
  1486. )
  1487. def copy(self, **kw):
  1488. return self._copy(**kw)
  1489. def _copy(self, **kw):
  1490. """Create a copy of this ``Column``, uninitialized.
  1491. This is used in :meth:`_schema.Table.to_metadata`.
  1492. """
  1493. # Constraint objects plus non-constraint-bound ForeignKey objects
  1494. args = [
  1495. c._copy(**kw) for c in self.constraints if not c._type_bound
  1496. ] + [c._copy(**kw) for c in self.foreign_keys if not c.constraint]
  1497. # ticket #5276
  1498. column_kwargs = {}
  1499. for dialect_name in self.dialect_options:
  1500. dialect_options = self.dialect_options[dialect_name]._non_defaults
  1501. for (
  1502. dialect_option_key,
  1503. dialect_option_value,
  1504. ) in dialect_options.items():
  1505. column_kwargs[
  1506. dialect_name + "_" + dialect_option_key
  1507. ] = dialect_option_value
  1508. server_default = self.server_default
  1509. server_onupdate = self.server_onupdate
  1510. if isinstance(server_default, (Computed, Identity)):
  1511. server_default = server_onupdate = None
  1512. args.append(self.server_default._copy(**kw))
  1513. type_ = self.type
  1514. if isinstance(type_, SchemaEventTarget):
  1515. type_ = type_.copy(**kw)
  1516. if self._user_defined_nullable is not NULL_UNSPECIFIED:
  1517. column_kwargs["nullable"] = self._user_defined_nullable
  1518. c = self._constructor(
  1519. name=self.name,
  1520. type_=type_,
  1521. key=self.key,
  1522. primary_key=self.primary_key,
  1523. unique=self.unique,
  1524. system=self.system,
  1525. # quote=self.quote, # disabled 2013-08-27 (commit 031ef080)
  1526. index=self.index,
  1527. autoincrement=self.autoincrement,
  1528. default=self.default,
  1529. server_default=server_default,
  1530. onupdate=self.onupdate,
  1531. server_onupdate=server_onupdate,
  1532. doc=self.doc,
  1533. comment=self.comment,
  1534. *args,
  1535. **column_kwargs
  1536. )
  1537. return self._schema_item_copy(c)
  1538. def _make_proxy(
  1539. self, selectable, name=None, key=None, name_is_truncatable=False, **kw
  1540. ):
  1541. """Create a *proxy* for this column.
  1542. This is a copy of this ``Column`` referenced by a different parent
  1543. (such as an alias or select statement). The column should
  1544. be used only in select scenarios, as its full DDL/default
  1545. information is not transferred.
  1546. """
  1547. fk = [
  1548. ForeignKey(f.column, _constraint=f.constraint)
  1549. for f in self.foreign_keys
  1550. ]
  1551. if name is None and self.name is None:
  1552. raise exc.InvalidRequestError(
  1553. "Cannot initialize a sub-selectable"
  1554. " with this Column object until its 'name' has "
  1555. "been assigned."
  1556. )
  1557. try:
  1558. c = self._constructor(
  1559. coercions.expect(
  1560. roles.TruncatedLabelRole, name if name else self.name
  1561. )
  1562. if name_is_truncatable
  1563. else (name or self.name),
  1564. self.type,
  1565. # this may actually be ._proxy_key when the key is incoming
  1566. key=key if key else name if name else self.key,
  1567. primary_key=self.primary_key,
  1568. nullable=self.nullable,
  1569. _proxies=[self],
  1570. *fk
  1571. )
  1572. except TypeError as err:
  1573. util.raise_(
  1574. TypeError(
  1575. "Could not create a copy of this %r object. "
  1576. "Ensure the class includes a _constructor() "
  1577. "attribute or method which accepts the "
  1578. "standard Column constructor arguments, or "
  1579. "references the Column class itself." % self.__class__
  1580. ),
  1581. from_=err,
  1582. )
  1583. c.table = selectable
  1584. c._propagate_attrs = selectable._propagate_attrs
  1585. if selectable._is_clone_of is not None:
  1586. c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
  1587. if self.primary_key:
  1588. selectable.primary_key.add(c)
  1589. if fk:
  1590. selectable.foreign_keys.update(fk)
  1591. return c.key, c
  1592. class ForeignKey(DialectKWArgs, SchemaItem):
  1593. """Defines a dependency between two columns.
  1594. ``ForeignKey`` is specified as an argument to a :class:`_schema.Column`
  1595. object,
  1596. e.g.::
  1597. t = Table("remote_table", metadata,
  1598. Column("remote_id", ForeignKey("main_table.id"))
  1599. )
  1600. Note that ``ForeignKey`` is only a marker object that defines
  1601. a dependency between two columns. The actual constraint
  1602. is in all cases represented by the :class:`_schema.ForeignKeyConstraint`
  1603. object. This object will be generated automatically when
  1604. a ``ForeignKey`` is associated with a :class:`_schema.Column` which
  1605. in turn is associated with a :class:`_schema.Table`. Conversely,
  1606. when :class:`_schema.ForeignKeyConstraint` is applied to a
  1607. :class:`_schema.Table`,
  1608. ``ForeignKey`` markers are automatically generated to be
  1609. present on each associated :class:`_schema.Column`, which are also
  1610. associated with the constraint object.
  1611. Note that you cannot define a "composite" foreign key constraint,
  1612. that is a constraint between a grouping of multiple parent/child
  1613. columns, using ``ForeignKey`` objects. To define this grouping,
  1614. the :class:`_schema.ForeignKeyConstraint` object must be used, and applied
  1615. to the :class:`_schema.Table`. The associated ``ForeignKey`` objects
  1616. are created automatically.
  1617. The ``ForeignKey`` objects associated with an individual
  1618. :class:`_schema.Column`
  1619. object are available in the `foreign_keys` collection
  1620. of that column.
  1621. Further examples of foreign key configuration are in
  1622. :ref:`metadata_foreignkeys`.
  1623. """
  1624. __visit_name__ = "foreign_key"
  1625. def __init__(
  1626. self,
  1627. column,
  1628. _constraint=None,
  1629. use_alter=False,
  1630. name=None,
  1631. onupdate=None,
  1632. ondelete=None,
  1633. deferrable=None,
  1634. initially=None,
  1635. link_to_name=False,
  1636. match=None,
  1637. info=None,
  1638. **dialect_kw
  1639. ):
  1640. r"""
  1641. Construct a column-level FOREIGN KEY.
  1642. The :class:`_schema.ForeignKey` object when constructed generates a
  1643. :class:`_schema.ForeignKeyConstraint`
  1644. which is associated with the parent
  1645. :class:`_schema.Table` object's collection of constraints.
  1646. :param column: A single target column for the key relationship. A
  1647. :class:`_schema.Column` object or a column name as a string:
  1648. ``tablename.columnkey`` or ``schema.tablename.columnkey``.
  1649. ``columnkey`` is the ``key`` which has been assigned to the column
  1650. (defaults to the column name itself), unless ``link_to_name`` is
  1651. ``True`` in which case the rendered name of the column is used.
  1652. :param name: Optional string. An in-database name for the key if
  1653. `constraint` is not provided.
  1654. :param onupdate: Optional string. If set, emit ON UPDATE <value> when
  1655. issuing DDL for this constraint. Typical values include CASCADE,
  1656. DELETE and RESTRICT.
  1657. :param ondelete: Optional string. If set, emit ON DELETE <value> when
  1658. issuing DDL for this constraint. Typical values include CASCADE,
  1659. DELETE and RESTRICT.
  1660. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT
  1661. DEFERRABLE when issuing DDL for this constraint.
  1662. :param initially: Optional string. If set, emit INITIALLY <value> when
  1663. issuing DDL for this constraint.
  1664. :param link_to_name: if True, the string name given in ``column`` is
  1665. the rendered name of the referenced column, not its locally
  1666. assigned ``key``.
  1667. :param use_alter: passed to the underlying
  1668. :class:`_schema.ForeignKeyConstraint`
  1669. to indicate the constraint should
  1670. be generated/dropped externally from the CREATE TABLE/ DROP TABLE
  1671. statement. See :paramref:`_schema.ForeignKeyConstraint.use_alter`
  1672. for further description.
  1673. .. seealso::
  1674. :paramref:`_schema.ForeignKeyConstraint.use_alter`
  1675. :ref:`use_alter`
  1676. :param match: Optional string. If set, emit MATCH <value> when issuing
  1677. DDL for this constraint. Typical values include SIMPLE, PARTIAL
  1678. and FULL.
  1679. :param info: Optional data dictionary which will be populated into the
  1680. :attr:`.SchemaItem.info` attribute of this object.
  1681. .. versionadded:: 1.0.0
  1682. :param \**dialect_kw: Additional keyword arguments are dialect
  1683. specific, and passed in the form ``<dialectname>_<argname>``. The
  1684. arguments are ultimately handled by a corresponding
  1685. :class:`_schema.ForeignKeyConstraint`.
  1686. See the documentation regarding
  1687. an individual dialect at :ref:`dialect_toplevel` for detail on
  1688. documented arguments.
  1689. .. versionadded:: 0.9.2
  1690. """
  1691. self._colspec = coercions.expect(roles.DDLReferredColumnRole, column)
  1692. if isinstance(self._colspec, util.string_types):
  1693. self._table_column = None
  1694. else:
  1695. self._table_column = self._colspec
  1696. if not isinstance(
  1697. self._table_column.table, (util.NoneType, TableClause)
  1698. ):
  1699. raise exc.ArgumentError(
  1700. "ForeignKey received Column not bound "
  1701. "to a Table, got: %r" % self._table_column.table
  1702. )
  1703. # the linked ForeignKeyConstraint.
  1704. # ForeignKey will create this when parent Column
  1705. # is attached to a Table, *or* ForeignKeyConstraint
  1706. # object passes itself in when creating ForeignKey
  1707. # markers.
  1708. self.constraint = _constraint
  1709. self.parent = None
  1710. self.use_alter = use_alter
  1711. self.name = name
  1712. self.onupdate = onupdate
  1713. self.ondelete = ondelete
  1714. self.deferrable = deferrable
  1715. self.initially = initially
  1716. self.link_to_name = link_to_name
  1717. self.match = match
  1718. if info:
  1719. self.info = info
  1720. self._unvalidated_dialect_kw = dialect_kw
  1721. def __repr__(self):
  1722. return "ForeignKey(%r)" % self._get_colspec()
  1723. @util.deprecated(
  1724. "1.4",
  1725. "The :meth:`_schema.ForeignKey.copy` method is deprecated "
  1726. "and will be removed in a future release.",
  1727. )
  1728. def copy(self, schema=None, **kw):
  1729. return self._copy(schema=schema, **kw)
  1730. def _copy(self, schema=None, **kw):
  1731. """Produce a copy of this :class:`_schema.ForeignKey` object.
  1732. The new :class:`_schema.ForeignKey` will not be bound
  1733. to any :class:`_schema.Column`.
  1734. This method is usually used by the internal
  1735. copy procedures of :class:`_schema.Column`, :class:`_schema.Table`,
  1736. and :class:`_schema.MetaData`.
  1737. :param schema: The returned :class:`_schema.ForeignKey` will
  1738. reference the original table and column name, qualified
  1739. by the given string schema name.
  1740. """
  1741. fk = ForeignKey(
  1742. self._get_colspec(schema=schema),
  1743. use_alter=self.use_alter,
  1744. name=self.name,
  1745. onupdate=self.onupdate,
  1746. ondelete=self.ondelete,
  1747. deferrable=self.deferrable,
  1748. initially=self.initially,
  1749. link_to_name=self.link_to_name,
  1750. match=self.match,
  1751. **self._unvalidated_dialect_kw
  1752. )
  1753. return self._schema_item_copy(fk)
  1754. def _get_colspec(self, schema=None, table_name=None):
  1755. """Return a string based 'column specification' for this
  1756. :class:`_schema.ForeignKey`.
  1757. This is usually the equivalent of the string-based "tablename.colname"
  1758. argument first passed to the object's constructor.
  1759. """
  1760. if schema:
  1761. _schema, tname, colname = self._column_tokens
  1762. if table_name is not None:
  1763. tname = table_name
  1764. return "%s.%s.%s" % (schema, tname, colname)
  1765. elif table_name:
  1766. schema, tname, colname = self._column_tokens
  1767. if schema:
  1768. return "%s.%s.%s" % (schema, table_name, colname)
  1769. else:
  1770. return "%s.%s" % (table_name, colname)
  1771. elif self._table_column is not None:
  1772. return "%s.%s" % (
  1773. self._table_column.table.fullname,
  1774. self._table_column.key,
  1775. )
  1776. else:
  1777. return self._colspec
  1778. @property
  1779. def _referred_schema(self):
  1780. return self._column_tokens[0]
  1781. def _table_key(self):
  1782. if self._table_column is not None:
  1783. if self._table_column.table is None:
  1784. return None
  1785. else:
  1786. return self._table_column.table.key
  1787. else:
  1788. schema, tname, colname = self._column_tokens
  1789. return _get_table_key(tname, schema)
  1790. target_fullname = property(_get_colspec)
  1791. def references(self, table):
  1792. """Return True if the given :class:`_schema.Table`
  1793. is referenced by this
  1794. :class:`_schema.ForeignKey`."""
  1795. return table.corresponding_column(self.column) is not None
  1796. def get_referent(self, table):
  1797. """Return the :class:`_schema.Column` in the given
  1798. :class:`_schema.Table`
  1799. referenced by this :class:`_schema.ForeignKey`.
  1800. Returns None if this :class:`_schema.ForeignKey`
  1801. does not reference the given
  1802. :class:`_schema.Table`.
  1803. """
  1804. return table.corresponding_column(self.column)
  1805. @util.memoized_property
  1806. def _column_tokens(self):
  1807. """parse a string-based _colspec into its component parts."""
  1808. m = self._get_colspec().split(".")
  1809. if m is None:
  1810. raise exc.ArgumentError(
  1811. "Invalid foreign key column specification: %s" % self._colspec
  1812. )
  1813. if len(m) == 1:
  1814. tname = m.pop()
  1815. colname = None
  1816. else:
  1817. colname = m.pop()
  1818. tname = m.pop()
  1819. # A FK between column 'bar' and table 'foo' can be
  1820. # specified as 'foo', 'foo.bar', 'dbo.foo.bar',
  1821. # 'otherdb.dbo.foo.bar'. Once we have the column name and
  1822. # the table name, treat everything else as the schema
  1823. # name. Some databases (e.g. Sybase) support
  1824. # inter-database foreign keys. See tickets#1341 and --
  1825. # indirectly related -- Ticket #594. This assumes that '.'
  1826. # will never appear *within* any component of the FK.
  1827. if len(m) > 0:
  1828. schema = ".".join(m)
  1829. else:
  1830. schema = None
  1831. return schema, tname, colname
  1832. def _resolve_col_tokens(self):
  1833. if self.parent is None:
  1834. raise exc.InvalidRequestError(
  1835. "this ForeignKey object does not yet have a "
  1836. "parent Column associated with it."
  1837. )
  1838. elif self.parent.table is None:
  1839. raise exc.InvalidRequestError(
  1840. "this ForeignKey's parent column is not yet associated "
  1841. "with a Table."
  1842. )
  1843. parenttable = self.parent.table
  1844. # assertion
  1845. # basically Column._make_proxy() sends the actual
  1846. # target Column to the ForeignKey object, so the
  1847. # string resolution here is never called.
  1848. for c in self.parent.base_columns:
  1849. if isinstance(c, Column):
  1850. assert c.table is parenttable
  1851. break
  1852. else:
  1853. assert False
  1854. ######################
  1855. schema, tname, colname = self._column_tokens
  1856. if schema is None and parenttable.metadata.schema is not None:
  1857. schema = parenttable.metadata.schema
  1858. tablekey = _get_table_key(tname, schema)
  1859. return parenttable, tablekey, colname
  1860. def _link_to_col_by_colstring(self, parenttable, table, colname):
  1861. if not hasattr(self.constraint, "_referred_table"):
  1862. self.constraint._referred_table = table
  1863. else:
  1864. assert self.constraint._referred_table is table
  1865. _column = None
  1866. if colname is None:
  1867. # colname is None in the case that ForeignKey argument
  1868. # was specified as table name only, in which case we
  1869. # match the column name to the same column on the
  1870. # parent.
  1871. key = self.parent
  1872. _column = table.c.get(self.parent.key, None)
  1873. elif self.link_to_name:
  1874. key = colname
  1875. for c in table.c:
  1876. if c.name == colname:
  1877. _column = c
  1878. else:
  1879. key = colname
  1880. _column = table.c.get(colname, None)
  1881. if _column is None:
  1882. raise exc.NoReferencedColumnError(
  1883. "Could not initialize target column "
  1884. "for ForeignKey '%s' on table '%s': "
  1885. "table '%s' has no column named '%s'"
  1886. % (self._colspec, parenttable.name, table.name, key),
  1887. table.name,
  1888. key,
  1889. )
  1890. self._set_target_column(_column)
  1891. def _set_target_column(self, column):
  1892. assert isinstance(self.parent.table, Table)
  1893. # propagate TypeEngine to parent if it didn't have one
  1894. if self.parent.type._isnull:
  1895. self.parent.type = column.type
  1896. # super-edgy case, if other FKs point to our column,
  1897. # they'd get the type propagated out also.
  1898. def set_type(fk):
  1899. if fk.parent.type._isnull:
  1900. fk.parent.type = column.type
  1901. self.parent._setup_on_memoized_fks(set_type)
  1902. self.column = column
  1903. @util.memoized_property
  1904. def column(self):
  1905. """Return the target :class:`_schema.Column` referenced by this
  1906. :class:`_schema.ForeignKey`.
  1907. If no target column has been established, an exception
  1908. is raised.
  1909. .. versionchanged:: 0.9.0
  1910. Foreign key target column resolution now occurs as soon as both
  1911. the ForeignKey object and the remote Column to which it refers
  1912. are both associated with the same MetaData object.
  1913. """
  1914. if isinstance(self._colspec, util.string_types):
  1915. parenttable, tablekey, colname = self._resolve_col_tokens()
  1916. if tablekey not in parenttable.metadata:
  1917. raise exc.NoReferencedTableError(
  1918. "Foreign key associated with column '%s' could not find "
  1919. "table '%s' with which to generate a "
  1920. "foreign key to target column '%s'"
  1921. % (self.parent, tablekey, colname),
  1922. tablekey,
  1923. )
  1924. elif parenttable.key not in parenttable.metadata:
  1925. raise exc.InvalidRequestError(
  1926. "Table %s is no longer associated with its "
  1927. "parent MetaData" % parenttable
  1928. )
  1929. else:
  1930. raise exc.NoReferencedColumnError(
  1931. "Could not initialize target column for "
  1932. "ForeignKey '%s' on table '%s': "
  1933. "table '%s' has no column named '%s'"
  1934. % (self._colspec, parenttable.name, tablekey, colname),
  1935. tablekey,
  1936. colname,
  1937. )
  1938. elif hasattr(self._colspec, "__clause_element__"):
  1939. _column = self._colspec.__clause_element__()
  1940. return _column
  1941. else:
  1942. _column = self._colspec
  1943. return _column
  1944. def _set_parent(self, column, **kw):
  1945. if self.parent is not None and self.parent is not column:
  1946. raise exc.InvalidRequestError(
  1947. "This ForeignKey already has a parent !"
  1948. )
  1949. self.parent = column
  1950. self.parent.foreign_keys.add(self)
  1951. self.parent._on_table_attach(self._set_table)
  1952. def _set_remote_table(self, table):
  1953. parenttable, tablekey, colname = self._resolve_col_tokens()
  1954. self._link_to_col_by_colstring(parenttable, table, colname)
  1955. self.constraint._validate_dest_table(table)
  1956. def _remove_from_metadata(self, metadata):
  1957. parenttable, table_key, colname = self._resolve_col_tokens()
  1958. fk_key = (table_key, colname)
  1959. if self in metadata._fk_memos[fk_key]:
  1960. # TODO: no test coverage for self not in memos
  1961. metadata._fk_memos[fk_key].remove(self)
  1962. def _set_table(self, column, table):
  1963. # standalone ForeignKey - create ForeignKeyConstraint
  1964. # on the hosting Table when attached to the Table.
  1965. assert isinstance(table, Table)
  1966. if self.constraint is None:
  1967. self.constraint = ForeignKeyConstraint(
  1968. [],
  1969. [],
  1970. use_alter=self.use_alter,
  1971. name=self.name,
  1972. onupdate=self.onupdate,
  1973. ondelete=self.ondelete,
  1974. deferrable=self.deferrable,
  1975. initially=self.initially,
  1976. match=self.match,
  1977. **self._unvalidated_dialect_kw
  1978. )
  1979. self.constraint._append_element(column, self)
  1980. self.constraint._set_parent_with_dispatch(table)
  1981. table.foreign_keys.add(self)
  1982. # set up remote ".column" attribute, or a note to pick it
  1983. # up when the other Table/Column shows up
  1984. if isinstance(self._colspec, util.string_types):
  1985. parenttable, table_key, colname = self._resolve_col_tokens()
  1986. fk_key = (table_key, colname)
  1987. if table_key in parenttable.metadata.tables:
  1988. table = parenttable.metadata.tables[table_key]
  1989. try:
  1990. self._link_to_col_by_colstring(parenttable, table, colname)
  1991. except exc.NoReferencedColumnError:
  1992. # this is OK, we'll try later
  1993. pass
  1994. parenttable.metadata._fk_memos[fk_key].append(self)
  1995. elif hasattr(self._colspec, "__clause_element__"):
  1996. _column = self._colspec.__clause_element__()
  1997. self._set_target_column(_column)
  1998. else:
  1999. _column = self._colspec
  2000. self._set_target_column(_column)
  2001. class DefaultGenerator(Executable, SchemaItem):
  2002. """Base class for column *default* values."""
  2003. __visit_name__ = "default_generator"
  2004. is_sequence = False
  2005. is_server_default = False
  2006. column = None
  2007. def __init__(self, for_update=False):
  2008. self.for_update = for_update
  2009. def _set_parent(self, column, **kw):
  2010. self.column = column
  2011. if self.for_update:
  2012. self.column.onupdate = self
  2013. else:
  2014. self.column.default = self
  2015. @util.deprecated_20(
  2016. ":meth:`.DefaultGenerator.execute`",
  2017. alternative="All statement execution in SQLAlchemy 2.0 is performed "
  2018. "by the :meth:`_engine.Connection.execute` method of "
  2019. ":class:`_engine.Connection`, "
  2020. "or in the ORM by the :meth:`.Session.execute` method of "
  2021. ":class:`.Session`.",
  2022. )
  2023. def execute(self, bind=None):
  2024. if bind is None:
  2025. bind = _bind_or_error(self)
  2026. return bind._execute_default(self, (), util.EMPTY_DICT)
  2027. def _execute_on_connection(
  2028. self, connection, multiparams, params, execution_options
  2029. ):
  2030. return connection._execute_default(
  2031. self, multiparams, params, execution_options
  2032. )
  2033. @property
  2034. def bind(self):
  2035. """Return the connectable associated with this default."""
  2036. if getattr(self, "column", None) is not None:
  2037. return self.column.table.bind
  2038. else:
  2039. return None
  2040. class ColumnDefault(DefaultGenerator):
  2041. """A plain default value on a column.
  2042. This could correspond to a constant, a callable function,
  2043. or a SQL clause.
  2044. :class:`.ColumnDefault` is generated automatically
  2045. whenever the ``default``, ``onupdate`` arguments of
  2046. :class:`_schema.Column` are used. A :class:`.ColumnDefault`
  2047. can be passed positionally as well.
  2048. For example, the following::
  2049. Column('foo', Integer, default=50)
  2050. Is equivalent to::
  2051. Column('foo', Integer, ColumnDefault(50))
  2052. """
  2053. def __init__(self, arg, **kwargs):
  2054. """Construct a new :class:`.ColumnDefault`.
  2055. :param arg: argument representing the default value.
  2056. May be one of the following:
  2057. * a plain non-callable Python value, such as a
  2058. string, integer, boolean, or other simple type.
  2059. The default value will be used as is each time.
  2060. * a SQL expression, that is one which derives from
  2061. :class:`_expression.ColumnElement`. The SQL expression will
  2062. be rendered into the INSERT or UPDATE statement,
  2063. or in the case of a primary key column when
  2064. RETURNING is not used may be
  2065. pre-executed before an INSERT within a SELECT.
  2066. * A Python callable. The function will be invoked for each
  2067. new row subject to an INSERT or UPDATE.
  2068. The callable must accept exactly
  2069. zero or one positional arguments. The one-argument form
  2070. will receive an instance of the :class:`.ExecutionContext`,
  2071. which provides contextual information as to the current
  2072. :class:`_engine.Connection` in use as well as the current
  2073. statement and parameters.
  2074. """
  2075. super(ColumnDefault, self).__init__(**kwargs)
  2076. if isinstance(arg, FetchedValue):
  2077. raise exc.ArgumentError(
  2078. "ColumnDefault may not be a server-side default type."
  2079. )
  2080. if callable(arg):
  2081. arg = self._maybe_wrap_callable(arg)
  2082. self.arg = arg
  2083. @util.memoized_property
  2084. def is_callable(self):
  2085. return callable(self.arg)
  2086. @util.memoized_property
  2087. def is_clause_element(self):
  2088. return isinstance(self.arg, ClauseElement)
  2089. @util.memoized_property
  2090. def is_scalar(self):
  2091. return (
  2092. not self.is_callable
  2093. and not self.is_clause_element
  2094. and not self.is_sequence
  2095. )
  2096. @util.memoized_property
  2097. @util.preload_module("sqlalchemy.sql.sqltypes")
  2098. def _arg_is_typed(self):
  2099. sqltypes = util.preloaded.sql_sqltypes
  2100. if self.is_clause_element:
  2101. return not isinstance(self.arg.type, sqltypes.NullType)
  2102. else:
  2103. return False
  2104. def _maybe_wrap_callable(self, fn):
  2105. """Wrap callables that don't accept a context.
  2106. This is to allow easy compatibility with default callables
  2107. that aren't specific to accepting of a context.
  2108. """
  2109. try:
  2110. argspec = util.get_callable_argspec(fn, no_self=True)
  2111. except TypeError:
  2112. return util.wrap_callable(lambda ctx: fn(), fn)
  2113. defaulted = argspec[3] is not None and len(argspec[3]) or 0
  2114. positionals = len(argspec[0]) - defaulted
  2115. if positionals == 0:
  2116. return util.wrap_callable(lambda ctx: fn(), fn)
  2117. elif positionals == 1:
  2118. return fn
  2119. else:
  2120. raise exc.ArgumentError(
  2121. "ColumnDefault Python function takes zero or one "
  2122. "positional arguments"
  2123. )
  2124. def __repr__(self):
  2125. return "ColumnDefault(%r)" % (self.arg,)
  2126. class IdentityOptions(object):
  2127. """Defines options for a named database sequence or an identity column.
  2128. .. versionadded:: 1.3.18
  2129. .. seealso::
  2130. :class:`.Sequence`
  2131. """
  2132. def __init__(
  2133. self,
  2134. start=None,
  2135. increment=None,
  2136. minvalue=None,
  2137. maxvalue=None,
  2138. nominvalue=None,
  2139. nomaxvalue=None,
  2140. cycle=None,
  2141. cache=None,
  2142. order=None,
  2143. ):
  2144. """Construct a :class:`.IdentityOptions` object.
  2145. See the :class:`.Sequence` documentation for a complete description
  2146. of the parameters.
  2147. :param start: the starting index of the sequence.
  2148. :param increment: the increment value of the sequence.
  2149. :param minvalue: the minimum value of the sequence.
  2150. :param maxvalue: the maximum value of the sequence.
  2151. :param nominvalue: no minimum value of the sequence.
  2152. :param nomaxvalue: no maximum value of the sequence.
  2153. :param cycle: allows the sequence to wrap around when the maxvalue
  2154. or minvalue has been reached.
  2155. :param cache: optional integer value; number of future values in the
  2156. sequence which are calculated in advance.
  2157. :param order: optional boolean value; if ``True``, renders the
  2158. ORDER keyword.
  2159. """
  2160. self.start = start
  2161. self.increment = increment
  2162. self.minvalue = minvalue
  2163. self.maxvalue = maxvalue
  2164. self.nominvalue = nominvalue
  2165. self.nomaxvalue = nomaxvalue
  2166. self.cycle = cycle
  2167. self.cache = cache
  2168. self.order = order
  2169. class Sequence(IdentityOptions, DefaultGenerator):
  2170. """Represents a named database sequence.
  2171. The :class:`.Sequence` object represents the name and configurational
  2172. parameters of a database sequence. It also represents
  2173. a construct that can be "executed" by a SQLAlchemy :class:`_engine.Engine`
  2174. or :class:`_engine.Connection`,
  2175. rendering the appropriate "next value" function
  2176. for the target database and returning a result.
  2177. The :class:`.Sequence` is typically associated with a primary key column::
  2178. some_table = Table(
  2179. 'some_table', metadata,
  2180. Column('id', Integer, Sequence('some_table_seq'),
  2181. primary_key=True)
  2182. )
  2183. When CREATE TABLE is emitted for the above :class:`_schema.Table`, if the
  2184. target platform supports sequences, a CREATE SEQUENCE statement will
  2185. be emitted as well. For platforms that don't support sequences,
  2186. the :class:`.Sequence` construct is ignored.
  2187. .. seealso::
  2188. :ref:`defaults_sequences`
  2189. :class:`.CreateSequence`
  2190. :class:`.DropSequence`
  2191. """
  2192. __visit_name__ = "sequence"
  2193. is_sequence = True
  2194. def __init__(
  2195. self,
  2196. name,
  2197. start=None,
  2198. increment=None,
  2199. minvalue=None,
  2200. maxvalue=None,
  2201. nominvalue=None,
  2202. nomaxvalue=None,
  2203. cycle=None,
  2204. schema=None,
  2205. cache=None,
  2206. order=None,
  2207. data_type=None,
  2208. optional=False,
  2209. quote=None,
  2210. metadata=None,
  2211. quote_schema=None,
  2212. for_update=False,
  2213. ):
  2214. """Construct a :class:`.Sequence` object.
  2215. :param name: the name of the sequence.
  2216. :param start: the starting index of the sequence. This value is
  2217. used when the CREATE SEQUENCE command is emitted to the database
  2218. as the value of the "START WITH" clause. If ``None``, the
  2219. clause is omitted, which on most platforms indicates a starting
  2220. value of 1.
  2221. :param increment: the increment value of the sequence. This
  2222. value is used when the CREATE SEQUENCE command is emitted to
  2223. the database as the value of the "INCREMENT BY" clause. If ``None``,
  2224. the clause is omitted, which on most platforms indicates an
  2225. increment of 1.
  2226. :param minvalue: the minimum value of the sequence. This
  2227. value is used when the CREATE SEQUENCE command is emitted to
  2228. the database as the value of the "MINVALUE" clause. If ``None``,
  2229. the clause is omitted, which on most platforms indicates a
  2230. minvalue of 1 and -2^63-1 for ascending and descending sequences,
  2231. respectively.
  2232. .. versionadded:: 1.0.7
  2233. :param maxvalue: the maximum value of the sequence. This
  2234. value is used when the CREATE SEQUENCE command is emitted to
  2235. the database as the value of the "MAXVALUE" clause. If ``None``,
  2236. the clause is omitted, which on most platforms indicates a
  2237. maxvalue of 2^63-1 and -1 for ascending and descending sequences,
  2238. respectively.
  2239. .. versionadded:: 1.0.7
  2240. :param nominvalue: no minimum value of the sequence. This
  2241. value is used when the CREATE SEQUENCE command is emitted to
  2242. the database as the value of the "NO MINVALUE" clause. If ``None``,
  2243. the clause is omitted, which on most platforms indicates a
  2244. minvalue of 1 and -2^63-1 for ascending and descending sequences,
  2245. respectively.
  2246. .. versionadded:: 1.0.7
  2247. :param nomaxvalue: no maximum value of the sequence. This
  2248. value is used when the CREATE SEQUENCE command is emitted to
  2249. the database as the value of the "NO MAXVALUE" clause. If ``None``,
  2250. the clause is omitted, which on most platforms indicates a
  2251. maxvalue of 2^63-1 and -1 for ascending and descending sequences,
  2252. respectively.
  2253. .. versionadded:: 1.0.7
  2254. :param cycle: allows the sequence to wrap around when the maxvalue
  2255. or minvalue has been reached by an ascending or descending sequence
  2256. respectively. This value is used when the CREATE SEQUENCE command
  2257. is emitted to the database as the "CYCLE" clause. If the limit is
  2258. reached, the next number generated will be the minvalue or maxvalue,
  2259. respectively. If cycle=False (the default) any calls to nextval
  2260. after the sequence has reached its maximum value will return an
  2261. error.
  2262. .. versionadded:: 1.0.7
  2263. :param schema: optional schema name for the sequence, if located
  2264. in a schema other than the default. The rules for selecting the
  2265. schema name when a :class:`_schema.MetaData`
  2266. is also present are the same
  2267. as that of :paramref:`_schema.Table.schema`.
  2268. :param cache: optional integer value; number of future values in the
  2269. sequence which are calculated in advance. Renders the CACHE keyword
  2270. understood by Oracle and PostgreSQL.
  2271. .. versionadded:: 1.1.12
  2272. :param order: optional boolean value; if ``True``, renders the
  2273. ORDER keyword, understood by Oracle, indicating the sequence is
  2274. definitively ordered. May be necessary to provide deterministic
  2275. ordering using Oracle RAC.
  2276. .. versionadded:: 1.1.12
  2277. :param data_type: The type to be returned by the sequence, for
  2278. dialects that allow us to choose between INTEGER, BIGINT, etc.
  2279. (e.g., mssql).
  2280. .. versionadded:: 1.4.0
  2281. :param optional: boolean value, when ``True``, indicates that this
  2282. :class:`.Sequence` object only needs to be explicitly generated
  2283. on backends that don't provide another way to generate primary
  2284. key identifiers. Currently, it essentially means, "don't create
  2285. this sequence on the PostgreSQL backend, where the SERIAL keyword
  2286. creates a sequence for us automatically".
  2287. :param quote: boolean value, when ``True`` or ``False``, explicitly
  2288. forces quoting of the :paramref:`_schema.Sequence.name` on or off.
  2289. When left at its default of ``None``, normal quoting rules based
  2290. on casing and reserved words take place.
  2291. :param quote_schema: Set the quoting preferences for the ``schema``
  2292. name.
  2293. :param metadata: optional :class:`_schema.MetaData` object which this
  2294. :class:`.Sequence` will be associated with. A :class:`.Sequence`
  2295. that is associated with a :class:`_schema.MetaData`
  2296. gains the following
  2297. capabilities:
  2298. * The :class:`.Sequence` will inherit the
  2299. :paramref:`_schema.MetaData.schema`
  2300. parameter specified to the target :class:`_schema.MetaData`, which
  2301. affects the production of CREATE / DROP DDL, if any.
  2302. * The :meth:`.Sequence.create` and :meth:`.Sequence.drop` methods
  2303. automatically use the engine bound to the :class:`_schema.MetaData`
  2304. object, if any.
  2305. * The :meth:`_schema.MetaData.create_all` and
  2306. :meth:`_schema.MetaData.drop_all`
  2307. methods will emit CREATE / DROP for this :class:`.Sequence`,
  2308. even if the :class:`.Sequence` is not associated with any
  2309. :class:`_schema.Table` / :class:`_schema.Column`
  2310. that's a member of this
  2311. :class:`_schema.MetaData`.
  2312. The above behaviors can only occur if the :class:`.Sequence` is
  2313. explicitly associated with the :class:`_schema.MetaData`
  2314. via this parameter.
  2315. .. seealso::
  2316. :ref:`sequence_metadata` - full discussion of the
  2317. :paramref:`.Sequence.metadata` parameter.
  2318. :param for_update: Indicates this :class:`.Sequence`, when associated
  2319. with a :class:`_schema.Column`,
  2320. should be invoked for UPDATE statements
  2321. on that column's table, rather than for INSERT statements, when
  2322. no value is otherwise present for that column in the statement.
  2323. """
  2324. DefaultGenerator.__init__(self, for_update=for_update)
  2325. IdentityOptions.__init__(
  2326. self,
  2327. start=start,
  2328. increment=increment,
  2329. minvalue=minvalue,
  2330. maxvalue=maxvalue,
  2331. nominvalue=nominvalue,
  2332. nomaxvalue=nomaxvalue,
  2333. cycle=cycle,
  2334. cache=cache,
  2335. order=order,
  2336. )
  2337. self.name = quoted_name(name, quote)
  2338. self.optional = optional
  2339. if schema is BLANK_SCHEMA:
  2340. self.schema = schema = None
  2341. elif metadata is not None and schema is None and metadata.schema:
  2342. self.schema = schema = metadata.schema
  2343. else:
  2344. self.schema = quoted_name(schema, quote_schema)
  2345. self.metadata = metadata
  2346. self._key = _get_table_key(name, schema)
  2347. if metadata:
  2348. self._set_metadata(metadata)
  2349. if data_type is not None:
  2350. self.data_type = to_instance(data_type)
  2351. else:
  2352. self.data_type = None
  2353. @util.memoized_property
  2354. def is_callable(self):
  2355. return False
  2356. @util.memoized_property
  2357. def is_clause_element(self):
  2358. return False
  2359. @util.preload_module("sqlalchemy.sql.functions")
  2360. def next_value(self):
  2361. """Return a :class:`.next_value` function element
  2362. which will render the appropriate increment function
  2363. for this :class:`.Sequence` within any SQL expression.
  2364. """
  2365. if self.bind:
  2366. return util.preloaded.sql_functions.func.next_value(
  2367. self, bind=self.bind
  2368. )
  2369. else:
  2370. return util.preloaded.sql_functions.func.next_value(self)
  2371. def _set_parent(self, column, **kw):
  2372. super(Sequence, self)._set_parent(column)
  2373. column._on_table_attach(self._set_table)
  2374. def _set_table(self, column, table):
  2375. self._set_metadata(table.metadata)
  2376. def _set_metadata(self, metadata):
  2377. self.metadata = metadata
  2378. self.metadata._sequences[self._key] = self
  2379. @property
  2380. def bind(self):
  2381. if self.metadata:
  2382. return self.metadata.bind
  2383. else:
  2384. return None
  2385. def create(self, bind=None, checkfirst=True):
  2386. """Creates this sequence in the database.
  2387. .. note:: the "bind" argument will be required in
  2388. SQLAlchemy 2.0.
  2389. """
  2390. if bind is None:
  2391. bind = _bind_or_error(self)
  2392. bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
  2393. def drop(self, bind=None, checkfirst=True):
  2394. """Drops this sequence from the database.
  2395. .. note:: the "bind" argument will be required in
  2396. SQLAlchemy 2.0.
  2397. """
  2398. if bind is None:
  2399. bind = _bind_or_error(self)
  2400. bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
  2401. def _not_a_column_expr(self):
  2402. raise exc.InvalidRequestError(
  2403. "This %s cannot be used directly "
  2404. "as a column expression. Use func.next_value(sequence) "
  2405. "to produce a 'next value' function that's usable "
  2406. "as a column element." % self.__class__.__name__
  2407. )
  2408. @inspection._self_inspects
  2409. class FetchedValue(SchemaEventTarget):
  2410. """A marker for a transparent database-side default.
  2411. Use :class:`.FetchedValue` when the database is configured
  2412. to provide some automatic default for a column.
  2413. E.g.::
  2414. Column('foo', Integer, FetchedValue())
  2415. Would indicate that some trigger or default generator
  2416. will create a new value for the ``foo`` column during an
  2417. INSERT.
  2418. .. seealso::
  2419. :ref:`triggered_columns`
  2420. """
  2421. is_server_default = True
  2422. reflected = False
  2423. has_argument = False
  2424. is_clause_element = False
  2425. def __init__(self, for_update=False):
  2426. self.for_update = for_update
  2427. def _as_for_update(self, for_update):
  2428. if for_update == self.for_update:
  2429. return self
  2430. else:
  2431. return self._clone(for_update)
  2432. def _clone(self, for_update):
  2433. n = self.__class__.__new__(self.__class__)
  2434. n.__dict__.update(self.__dict__)
  2435. n.__dict__.pop("column", None)
  2436. n.for_update = for_update
  2437. return n
  2438. def _set_parent(self, column, **kw):
  2439. self.column = column
  2440. if self.for_update:
  2441. self.column.server_onupdate = self
  2442. else:
  2443. self.column.server_default = self
  2444. def __repr__(self):
  2445. return util.generic_repr(self)
  2446. class DefaultClause(FetchedValue):
  2447. """A DDL-specified DEFAULT column value.
  2448. :class:`.DefaultClause` is a :class:`.FetchedValue`
  2449. that also generates a "DEFAULT" clause when
  2450. "CREATE TABLE" is emitted.
  2451. :class:`.DefaultClause` is generated automatically
  2452. whenever the ``server_default``, ``server_onupdate`` arguments of
  2453. :class:`_schema.Column` are used. A :class:`.DefaultClause`
  2454. can be passed positionally as well.
  2455. For example, the following::
  2456. Column('foo', Integer, server_default="50")
  2457. Is equivalent to::
  2458. Column('foo', Integer, DefaultClause("50"))
  2459. """
  2460. has_argument = True
  2461. def __init__(self, arg, for_update=False, _reflected=False):
  2462. util.assert_arg_type(
  2463. arg, (util.string_types[0], ClauseElement, TextClause), "arg"
  2464. )
  2465. super(DefaultClause, self).__init__(for_update)
  2466. self.arg = arg
  2467. self.reflected = _reflected
  2468. def __repr__(self):
  2469. return "DefaultClause(%r, for_update=%r)" % (self.arg, self.for_update)
  2470. class Constraint(DialectKWArgs, SchemaItem):
  2471. """A table-level SQL constraint.
  2472. :class:`_schema.Constraint` serves as the base class for the series of
  2473. constraint objects that can be associated with :class:`_schema.Table`
  2474. objects, including :class:`_schema.PrimaryKeyConstraint`,
  2475. :class:`_schema.ForeignKeyConstraint`
  2476. :class:`_schema.UniqueConstraint`, and
  2477. :class:`_schema.CheckConstraint`.
  2478. """
  2479. __visit_name__ = "constraint"
  2480. def __init__(
  2481. self,
  2482. name=None,
  2483. deferrable=None,
  2484. initially=None,
  2485. _create_rule=None,
  2486. info=None,
  2487. _type_bound=False,
  2488. **dialect_kw
  2489. ):
  2490. r"""Create a SQL constraint.
  2491. :param name:
  2492. Optional, the in-database name of this ``Constraint``.
  2493. :param deferrable:
  2494. Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
  2495. issuing DDL for this constraint.
  2496. :param initially:
  2497. Optional string. If set, emit INITIALLY <value> when issuing DDL
  2498. for this constraint.
  2499. :param info: Optional data dictionary which will be populated into the
  2500. :attr:`.SchemaItem.info` attribute of this object.
  2501. .. versionadded:: 1.0.0
  2502. :param \**dialect_kw: Additional keyword arguments are dialect
  2503. specific, and passed in the form ``<dialectname>_<argname>``. See
  2504. the documentation regarding an individual dialect at
  2505. :ref:`dialect_toplevel` for detail on documented arguments.
  2506. :param _create_rule:
  2507. used internally by some datatypes that also create constraints.
  2508. :param _type_bound:
  2509. used internally to indicate that this constraint is associated with
  2510. a specific datatype.
  2511. """
  2512. self.name = name
  2513. self.deferrable = deferrable
  2514. self.initially = initially
  2515. if info:
  2516. self.info = info
  2517. self._create_rule = _create_rule
  2518. self._type_bound = _type_bound
  2519. util.set_creation_order(self)
  2520. self._validate_dialect_kwargs(dialect_kw)
  2521. @property
  2522. def table(self):
  2523. try:
  2524. if isinstance(self.parent, Table):
  2525. return self.parent
  2526. except AttributeError:
  2527. pass
  2528. raise exc.InvalidRequestError(
  2529. "This constraint is not bound to a table. Did you "
  2530. "mean to call table.append_constraint(constraint) ?"
  2531. )
  2532. def _set_parent(self, parent, **kw):
  2533. self.parent = parent
  2534. parent.constraints.add(self)
  2535. @util.deprecated(
  2536. "1.4",
  2537. "The :meth:`_schema.Constraint.copy` method is deprecated "
  2538. "and will be removed in a future release.",
  2539. )
  2540. def copy(self, **kw):
  2541. return self._copy(**kw)
  2542. def _copy(self, **kw):
  2543. raise NotImplementedError()
  2544. class ColumnCollectionMixin(object):
  2545. columns = None
  2546. """A :class:`_expression.ColumnCollection` of :class:`_schema.Column`
  2547. objects.
  2548. This collection represents the columns which are referred to by
  2549. this object.
  2550. """
  2551. _allow_multiple_tables = False
  2552. def __init__(self, *columns, **kw):
  2553. _autoattach = kw.pop("_autoattach", True)
  2554. self._column_flag = kw.pop("_column_flag", False)
  2555. self.columns = DedupeColumnCollection()
  2556. processed_expressions = kw.pop("_gather_expressions", None)
  2557. if processed_expressions is not None:
  2558. self._pending_colargs = []
  2559. for (
  2560. expr,
  2561. column,
  2562. strname,
  2563. add_element,
  2564. ) in coercions.expect_col_expression_collection(
  2565. roles.DDLConstraintColumnRole, columns
  2566. ):
  2567. self._pending_colargs.append(add_element)
  2568. processed_expressions.append(expr)
  2569. else:
  2570. self._pending_colargs = [
  2571. coercions.expect(roles.DDLConstraintColumnRole, column)
  2572. for column in columns
  2573. ]
  2574. if _autoattach and self._pending_colargs:
  2575. self._check_attach()
  2576. def _check_attach(self, evt=False):
  2577. col_objs = [c for c in self._pending_colargs if isinstance(c, Column)]
  2578. cols_w_table = [c for c in col_objs if isinstance(c.table, Table)]
  2579. cols_wo_table = set(col_objs).difference(cols_w_table)
  2580. if cols_wo_table:
  2581. # feature #3341 - place event listeners for Column objects
  2582. # such that when all those cols are attached, we autoattach.
  2583. assert not evt, "Should not reach here on event call"
  2584. # issue #3411 - don't do the per-column auto-attach if some of the
  2585. # columns are specified as strings.
  2586. has_string_cols = set(
  2587. c for c in self._pending_colargs if c is not None
  2588. ).difference(col_objs)
  2589. if not has_string_cols:
  2590. def _col_attached(column, table):
  2591. # this isinstance() corresponds with the
  2592. # isinstance() above; only want to count Table-bound
  2593. # columns
  2594. if isinstance(table, Table):
  2595. cols_wo_table.discard(column)
  2596. if not cols_wo_table:
  2597. self._check_attach(evt=True)
  2598. self._cols_wo_table = cols_wo_table
  2599. for col in cols_wo_table:
  2600. col._on_table_attach(_col_attached)
  2601. return
  2602. columns = cols_w_table
  2603. tables = {c.table for c in columns}
  2604. if len(tables) == 1:
  2605. self._set_parent_with_dispatch(tables.pop())
  2606. elif len(tables) > 1 and not self._allow_multiple_tables:
  2607. table = columns[0].table
  2608. others = [c for c in columns[1:] if c.table is not table]
  2609. if others:
  2610. raise exc.ArgumentError(
  2611. "Column(s) %s are not part of table '%s'."
  2612. % (
  2613. ", ".join("'%s'" % c for c in others),
  2614. table.description,
  2615. )
  2616. )
  2617. def _col_expressions(self, table):
  2618. return [
  2619. table.c[col] if isinstance(col, util.string_types) else col
  2620. for col in self._pending_colargs
  2621. ]
  2622. def _set_parent(self, table, **kw):
  2623. for col in self._col_expressions(table):
  2624. if col is not None:
  2625. self.columns.add(col)
  2626. class ColumnCollectionConstraint(ColumnCollectionMixin, Constraint):
  2627. """A constraint that proxies a ColumnCollection."""
  2628. def __init__(self, *columns, **kw):
  2629. r"""
  2630. :param \*columns:
  2631. A sequence of column names or Column objects.
  2632. :param name:
  2633. Optional, the in-database name of this constraint.
  2634. :param deferrable:
  2635. Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
  2636. issuing DDL for this constraint.
  2637. :param initially:
  2638. Optional string. If set, emit INITIALLY <value> when issuing DDL
  2639. for this constraint.
  2640. :param \**kw: other keyword arguments including dialect-specific
  2641. arguments are propagated to the :class:`.Constraint` superclass.
  2642. """
  2643. _autoattach = kw.pop("_autoattach", True)
  2644. _column_flag = kw.pop("_column_flag", False)
  2645. Constraint.__init__(self, **kw)
  2646. ColumnCollectionMixin.__init__(
  2647. self, *columns, _autoattach=_autoattach, _column_flag=_column_flag
  2648. )
  2649. columns = None
  2650. """A :class:`_expression.ColumnCollection` representing the set of columns
  2651. for this constraint.
  2652. """
  2653. def _set_parent(self, table, **kw):
  2654. Constraint._set_parent(self, table)
  2655. ColumnCollectionMixin._set_parent(self, table)
  2656. def __contains__(self, x):
  2657. return x in self.columns
  2658. @util.deprecated(
  2659. "1.4",
  2660. "The :meth:`_schema.ColumnCollectionConstraint.copy` method "
  2661. "is deprecated and will be removed in a future release.",
  2662. )
  2663. def copy(self, target_table=None, **kw):
  2664. return self._copy(target_table=target_table, **kw)
  2665. def _copy(self, target_table=None, **kw):
  2666. # ticket #5276
  2667. constraint_kwargs = {}
  2668. for dialect_name in self.dialect_options:
  2669. dialect_options = self.dialect_options[dialect_name]._non_defaults
  2670. for (
  2671. dialect_option_key,
  2672. dialect_option_value,
  2673. ) in dialect_options.items():
  2674. constraint_kwargs[
  2675. dialect_name + "_" + dialect_option_key
  2676. ] = dialect_option_value
  2677. c = self.__class__(
  2678. name=self.name,
  2679. deferrable=self.deferrable,
  2680. initially=self.initially,
  2681. *[
  2682. _copy_expression(expr, self.parent, target_table)
  2683. for expr in self.columns
  2684. ],
  2685. **constraint_kwargs
  2686. )
  2687. return self._schema_item_copy(c)
  2688. def contains_column(self, col):
  2689. """Return True if this constraint contains the given column.
  2690. Note that this object also contains an attribute ``.columns``
  2691. which is a :class:`_expression.ColumnCollection` of
  2692. :class:`_schema.Column` objects.
  2693. """
  2694. return self.columns.contains_column(col)
  2695. def __iter__(self):
  2696. return iter(self.columns)
  2697. def __len__(self):
  2698. return len(self.columns)
  2699. class CheckConstraint(ColumnCollectionConstraint):
  2700. """A table- or column-level CHECK constraint.
  2701. Can be included in the definition of a Table or Column.
  2702. """
  2703. _allow_multiple_tables = True
  2704. __visit_name__ = "table_or_column_check_constraint"
  2705. @_document_text_coercion(
  2706. "sqltext",
  2707. ":class:`.CheckConstraint`",
  2708. ":paramref:`.CheckConstraint.sqltext`",
  2709. )
  2710. def __init__(
  2711. self,
  2712. sqltext,
  2713. name=None,
  2714. deferrable=None,
  2715. initially=None,
  2716. table=None,
  2717. info=None,
  2718. _create_rule=None,
  2719. _autoattach=True,
  2720. _type_bound=False,
  2721. **kw
  2722. ):
  2723. r"""Construct a CHECK constraint.
  2724. :param sqltext:
  2725. A string containing the constraint definition, which will be used
  2726. verbatim, or a SQL expression construct. If given as a string,
  2727. the object is converted to a :func:`_expression.text` object.
  2728. If the textual
  2729. string includes a colon character, escape this using a backslash::
  2730. CheckConstraint(r"foo ~ E'a(?\:b|c)d")
  2731. :param name:
  2732. Optional, the in-database name of the constraint.
  2733. :param deferrable:
  2734. Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
  2735. issuing DDL for this constraint.
  2736. :param initially:
  2737. Optional string. If set, emit INITIALLY <value> when issuing DDL
  2738. for this constraint.
  2739. :param info: Optional data dictionary which will be populated into the
  2740. :attr:`.SchemaItem.info` attribute of this object.
  2741. .. versionadded:: 1.0.0
  2742. """
  2743. self.sqltext = coercions.expect(roles.DDLExpressionRole, sqltext)
  2744. columns = []
  2745. visitors.traverse(self.sqltext, {}, {"column": columns.append})
  2746. super(CheckConstraint, self).__init__(
  2747. name=name,
  2748. deferrable=deferrable,
  2749. initially=initially,
  2750. _create_rule=_create_rule,
  2751. info=info,
  2752. _type_bound=_type_bound,
  2753. _autoattach=_autoattach,
  2754. *columns,
  2755. **kw
  2756. )
  2757. if table is not None:
  2758. self._set_parent_with_dispatch(table)
  2759. @property
  2760. def is_column_level(self):
  2761. return not isinstance(self.parent, Table)
  2762. @util.deprecated(
  2763. "1.4",
  2764. "The :meth:`_schema.CheckConstraint.copy` method is deprecated "
  2765. "and will be removed in a future release.",
  2766. )
  2767. def copy(self, target_table=None, **kw):
  2768. return self._copy(target_table=target_table, **kw)
  2769. def _copy(self, target_table=None, **kw):
  2770. if target_table is not None:
  2771. # note that target_table is None for the copy process of
  2772. # a column-bound CheckConstraint, so this path is not reached
  2773. # in that case.
  2774. sqltext = _copy_expression(self.sqltext, self.table, target_table)
  2775. else:
  2776. sqltext = self.sqltext
  2777. c = CheckConstraint(
  2778. sqltext,
  2779. name=self.name,
  2780. initially=self.initially,
  2781. deferrable=self.deferrable,
  2782. _create_rule=self._create_rule,
  2783. table=target_table,
  2784. _autoattach=False,
  2785. _type_bound=self._type_bound,
  2786. )
  2787. return self._schema_item_copy(c)
  2788. class ForeignKeyConstraint(ColumnCollectionConstraint):
  2789. """A table-level FOREIGN KEY constraint.
  2790. Defines a single column or composite FOREIGN KEY ... REFERENCES
  2791. constraint. For a no-frills, single column foreign key, adding a
  2792. :class:`_schema.ForeignKey` to the definition of a :class:`_schema.Column`
  2793. is a
  2794. shorthand equivalent for an unnamed, single column
  2795. :class:`_schema.ForeignKeyConstraint`.
  2796. Examples of foreign key configuration are in :ref:`metadata_foreignkeys`.
  2797. """
  2798. __visit_name__ = "foreign_key_constraint"
  2799. def __init__(
  2800. self,
  2801. columns,
  2802. refcolumns,
  2803. name=None,
  2804. onupdate=None,
  2805. ondelete=None,
  2806. deferrable=None,
  2807. initially=None,
  2808. use_alter=False,
  2809. link_to_name=False,
  2810. match=None,
  2811. table=None,
  2812. info=None,
  2813. **dialect_kw
  2814. ):
  2815. r"""Construct a composite-capable FOREIGN KEY.
  2816. :param columns: A sequence of local column names. The named columns
  2817. must be defined and present in the parent Table. The names should
  2818. match the ``key`` given to each column (defaults to the name) unless
  2819. ``link_to_name`` is True.
  2820. :param refcolumns: A sequence of foreign column names or Column
  2821. objects. The columns must all be located within the same Table.
  2822. :param name: Optional, the in-database name of the key.
  2823. :param onupdate: Optional string. If set, emit ON UPDATE <value> when
  2824. issuing DDL for this constraint. Typical values include CASCADE,
  2825. DELETE and RESTRICT.
  2826. :param ondelete: Optional string. If set, emit ON DELETE <value> when
  2827. issuing DDL for this constraint. Typical values include CASCADE,
  2828. DELETE and RESTRICT.
  2829. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT
  2830. DEFERRABLE when issuing DDL for this constraint.
  2831. :param initially: Optional string. If set, emit INITIALLY <value> when
  2832. issuing DDL for this constraint.
  2833. :param link_to_name: if True, the string name given in ``column`` is
  2834. the rendered name of the referenced column, not its locally assigned
  2835. ``key``.
  2836. :param use_alter: If True, do not emit the DDL for this constraint as
  2837. part of the CREATE TABLE definition. Instead, generate it via an
  2838. ALTER TABLE statement issued after the full collection of tables
  2839. have been created, and drop it via an ALTER TABLE statement before
  2840. the full collection of tables are dropped.
  2841. The use of :paramref:`_schema.ForeignKeyConstraint.use_alter` is
  2842. particularly geared towards the case where two or more tables
  2843. are established within a mutually-dependent foreign key constraint
  2844. relationship; however, the :meth:`_schema.MetaData.create_all` and
  2845. :meth:`_schema.MetaData.drop_all`
  2846. methods will perform this resolution
  2847. automatically, so the flag is normally not needed.
  2848. .. versionchanged:: 1.0.0 Automatic resolution of foreign key
  2849. cycles has been added, removing the need to use the
  2850. :paramref:`_schema.ForeignKeyConstraint.use_alter` in typical use
  2851. cases.
  2852. .. seealso::
  2853. :ref:`use_alter`
  2854. :param match: Optional string. If set, emit MATCH <value> when issuing
  2855. DDL for this constraint. Typical values include SIMPLE, PARTIAL
  2856. and FULL.
  2857. :param info: Optional data dictionary which will be populated into the
  2858. :attr:`.SchemaItem.info` attribute of this object.
  2859. .. versionadded:: 1.0.0
  2860. :param \**dialect_kw: Additional keyword arguments are dialect
  2861. specific, and passed in the form ``<dialectname>_<argname>``. See
  2862. the documentation regarding an individual dialect at
  2863. :ref:`dialect_toplevel` for detail on documented arguments.
  2864. .. versionadded:: 0.9.2
  2865. """
  2866. Constraint.__init__(
  2867. self,
  2868. name=name,
  2869. deferrable=deferrable,
  2870. initially=initially,
  2871. info=info,
  2872. **dialect_kw
  2873. )
  2874. self.onupdate = onupdate
  2875. self.ondelete = ondelete
  2876. self.link_to_name = link_to_name
  2877. self.use_alter = use_alter
  2878. self.match = match
  2879. if len(set(columns)) != len(refcolumns):
  2880. if len(set(columns)) != len(columns):
  2881. # e.g. FOREIGN KEY (a, a) REFERENCES r (b, c)
  2882. raise exc.ArgumentError(
  2883. "ForeignKeyConstraint with duplicate source column "
  2884. "references are not supported."
  2885. )
  2886. else:
  2887. # e.g. FOREIGN KEY (a) REFERENCES r (b, c)
  2888. # paraphrasing https://www.postgresql.org/docs/9.2/static/\
  2889. # ddl-constraints.html
  2890. raise exc.ArgumentError(
  2891. "ForeignKeyConstraint number "
  2892. "of constrained columns must match the number of "
  2893. "referenced columns."
  2894. )
  2895. # standalone ForeignKeyConstraint - create
  2896. # associated ForeignKey objects which will be applied to hosted
  2897. # Column objects (in col.foreign_keys), either now or when attached
  2898. # to the Table for string-specified names
  2899. self.elements = [
  2900. ForeignKey(
  2901. refcol,
  2902. _constraint=self,
  2903. name=self.name,
  2904. onupdate=self.onupdate,
  2905. ondelete=self.ondelete,
  2906. use_alter=self.use_alter,
  2907. link_to_name=self.link_to_name,
  2908. match=self.match,
  2909. deferrable=self.deferrable,
  2910. initially=self.initially,
  2911. **self.dialect_kwargs
  2912. )
  2913. for refcol in refcolumns
  2914. ]
  2915. ColumnCollectionMixin.__init__(self, *columns)
  2916. if table is not None:
  2917. if hasattr(self, "parent"):
  2918. assert table is self.parent
  2919. self._set_parent_with_dispatch(table)
  2920. def _append_element(self, column, fk):
  2921. self.columns.add(column)
  2922. self.elements.append(fk)
  2923. columns = None
  2924. """A :class:`_expression.ColumnCollection` representing the set of columns
  2925. for this constraint.
  2926. """
  2927. elements = None
  2928. """A sequence of :class:`_schema.ForeignKey` objects.
  2929. Each :class:`_schema.ForeignKey`
  2930. represents a single referring column/referred
  2931. column pair.
  2932. This collection is intended to be read-only.
  2933. """
  2934. @property
  2935. def _elements(self):
  2936. # legacy - provide a dictionary view of (column_key, fk)
  2937. return util.OrderedDict(zip(self.column_keys, self.elements))
  2938. @property
  2939. def _referred_schema(self):
  2940. for elem in self.elements:
  2941. return elem._referred_schema
  2942. else:
  2943. return None
  2944. @property
  2945. def referred_table(self):
  2946. """The :class:`_schema.Table` object to which this
  2947. :class:`_schema.ForeignKeyConstraint` references.
  2948. This is a dynamically calculated attribute which may not be available
  2949. if the constraint and/or parent table is not yet associated with
  2950. a metadata collection that contains the referred table.
  2951. .. versionadded:: 1.0.0
  2952. """
  2953. return self.elements[0].column.table
  2954. def _validate_dest_table(self, table):
  2955. table_keys = set([elem._table_key() for elem in self.elements])
  2956. if None not in table_keys and len(table_keys) > 1:
  2957. elem0, elem1 = sorted(table_keys)[0:2]
  2958. raise exc.ArgumentError(
  2959. "ForeignKeyConstraint on %s(%s) refers to "
  2960. "multiple remote tables: %s and %s"
  2961. % (table.fullname, self._col_description, elem0, elem1)
  2962. )
  2963. @property
  2964. def column_keys(self):
  2965. """Return a list of string keys representing the local
  2966. columns in this :class:`_schema.ForeignKeyConstraint`.
  2967. This list is either the original string arguments sent
  2968. to the constructor of the :class:`_schema.ForeignKeyConstraint`,
  2969. or if the constraint has been initialized with :class:`_schema.Column`
  2970. objects, is the string ``.key`` of each element.
  2971. .. versionadded:: 1.0.0
  2972. """
  2973. if hasattr(self, "parent"):
  2974. return self.columns.keys()
  2975. else:
  2976. return [
  2977. col.key if isinstance(col, ColumnElement) else str(col)
  2978. for col in self._pending_colargs
  2979. ]
  2980. @property
  2981. def _col_description(self):
  2982. return ", ".join(self.column_keys)
  2983. def _set_parent(self, table, **kw):
  2984. Constraint._set_parent(self, table)
  2985. try:
  2986. ColumnCollectionConstraint._set_parent(self, table)
  2987. except KeyError as ke:
  2988. util.raise_(
  2989. exc.ArgumentError(
  2990. "Can't create ForeignKeyConstraint "
  2991. "on table '%s': no column "
  2992. "named '%s' is present." % (table.description, ke.args[0])
  2993. ),
  2994. from_=ke,
  2995. )
  2996. for col, fk in zip(self.columns, self.elements):
  2997. if not hasattr(fk, "parent") or fk.parent is not col:
  2998. fk._set_parent_with_dispatch(col)
  2999. self._validate_dest_table(table)
  3000. @util.deprecated(
  3001. "1.4",
  3002. "The :meth:`_schema.ForeignKeyConstraint.copy` method is deprecated "
  3003. "and will be removed in a future release.",
  3004. )
  3005. def copy(self, schema=None, target_table=None, **kw):
  3006. return self._copy(schema=schema, target_table=target_table, **kw)
  3007. def _copy(self, schema=None, target_table=None, **kw):
  3008. fkc = ForeignKeyConstraint(
  3009. [x.parent.key for x in self.elements],
  3010. [
  3011. x._get_colspec(
  3012. schema=schema,
  3013. table_name=target_table.name
  3014. if target_table is not None
  3015. and x._table_key() == x.parent.table.key
  3016. else None,
  3017. )
  3018. for x in self.elements
  3019. ],
  3020. name=self.name,
  3021. onupdate=self.onupdate,
  3022. ondelete=self.ondelete,
  3023. use_alter=self.use_alter,
  3024. deferrable=self.deferrable,
  3025. initially=self.initially,
  3026. link_to_name=self.link_to_name,
  3027. match=self.match,
  3028. )
  3029. for self_fk, other_fk in zip(self.elements, fkc.elements):
  3030. self_fk._schema_item_copy(other_fk)
  3031. return self._schema_item_copy(fkc)
  3032. class PrimaryKeyConstraint(ColumnCollectionConstraint):
  3033. """A table-level PRIMARY KEY constraint.
  3034. The :class:`.PrimaryKeyConstraint` object is present automatically
  3035. on any :class:`_schema.Table` object; it is assigned a set of
  3036. :class:`_schema.Column` objects corresponding to those marked with
  3037. the :paramref:`_schema.Column.primary_key` flag::
  3038. >>> my_table = Table('mytable', metadata,
  3039. ... Column('id', Integer, primary_key=True),
  3040. ... Column('version_id', Integer, primary_key=True),
  3041. ... Column('data', String(50))
  3042. ... )
  3043. >>> my_table.primary_key
  3044. PrimaryKeyConstraint(
  3045. Column('id', Integer(), table=<mytable>,
  3046. primary_key=True, nullable=False),
  3047. Column('version_id', Integer(), table=<mytable>,
  3048. primary_key=True, nullable=False)
  3049. )
  3050. The primary key of a :class:`_schema.Table` can also be specified by using
  3051. a :class:`.PrimaryKeyConstraint` object explicitly; in this mode of usage,
  3052. the "name" of the constraint can also be specified, as well as other
  3053. options which may be recognized by dialects::
  3054. my_table = Table('mytable', metadata,
  3055. Column('id', Integer),
  3056. Column('version_id', Integer),
  3057. Column('data', String(50)),
  3058. PrimaryKeyConstraint('id', 'version_id',
  3059. name='mytable_pk')
  3060. )
  3061. The two styles of column-specification should generally not be mixed.
  3062. An warning is emitted if the columns present in the
  3063. :class:`.PrimaryKeyConstraint`
  3064. don't match the columns that were marked as ``primary_key=True``, if both
  3065. are present; in this case, the columns are taken strictly from the
  3066. :class:`.PrimaryKeyConstraint` declaration, and those columns otherwise
  3067. marked as ``primary_key=True`` are ignored. This behavior is intended to
  3068. be backwards compatible with previous behavior.
  3069. .. versionchanged:: 0.9.2 Using a mixture of columns within a
  3070. :class:`.PrimaryKeyConstraint` in addition to columns marked as
  3071. ``primary_key=True`` now emits a warning if the lists don't match.
  3072. The ultimate behavior of ignoring those columns marked with the flag
  3073. only is currently maintained for backwards compatibility; this warning
  3074. may raise an exception in a future release.
  3075. For the use case where specific options are to be specified on the
  3076. :class:`.PrimaryKeyConstraint`, but the usual style of using
  3077. ``primary_key=True`` flags is still desirable, an empty
  3078. :class:`.PrimaryKeyConstraint` may be specified, which will take on the
  3079. primary key column collection from the :class:`_schema.Table` based on the
  3080. flags::
  3081. my_table = Table('mytable', metadata,
  3082. Column('id', Integer, primary_key=True),
  3083. Column('version_id', Integer, primary_key=True),
  3084. Column('data', String(50)),
  3085. PrimaryKeyConstraint(name='mytable_pk',
  3086. mssql_clustered=True)
  3087. )
  3088. .. versionadded:: 0.9.2 an empty :class:`.PrimaryKeyConstraint` may now
  3089. be specified for the purposes of establishing keyword arguments with
  3090. the constraint, independently of the specification of "primary key"
  3091. columns within the :class:`_schema.Table` itself; columns marked as
  3092. ``primary_key=True`` will be gathered into the empty constraint's
  3093. column collection.
  3094. """
  3095. __visit_name__ = "primary_key_constraint"
  3096. def __init__(self, *columns, **kw):
  3097. self._implicit_generated = kw.pop("_implicit_generated", False)
  3098. super(PrimaryKeyConstraint, self).__init__(*columns, **kw)
  3099. def _set_parent(self, table, **kw):
  3100. super(PrimaryKeyConstraint, self)._set_parent(table)
  3101. if table.primary_key is not self:
  3102. table.constraints.discard(table.primary_key)
  3103. table.primary_key = self
  3104. table.constraints.add(self)
  3105. table_pks = [c for c in table.c if c.primary_key]
  3106. if self.columns and table_pks and set(table_pks) != set(self.columns):
  3107. util.warn(
  3108. "Table '%s' specifies columns %s as primary_key=True, "
  3109. "not matching locally specified columns %s; setting the "
  3110. "current primary key columns to %s. This warning "
  3111. "may become an exception in a future release"
  3112. % (
  3113. table.name,
  3114. ", ".join("'%s'" % c.name for c in table_pks),
  3115. ", ".join("'%s'" % c.name for c in self.columns),
  3116. ", ".join("'%s'" % c.name for c in self.columns),
  3117. )
  3118. )
  3119. table_pks[:] = []
  3120. for c in self.columns:
  3121. c.primary_key = True
  3122. if c._user_defined_nullable is NULL_UNSPECIFIED:
  3123. c.nullable = False
  3124. if table_pks:
  3125. self.columns.extend(table_pks)
  3126. def _reload(self, columns):
  3127. """repopulate this :class:`.PrimaryKeyConstraint` given
  3128. a set of columns.
  3129. Existing columns in the table that are marked as primary_key=True
  3130. are maintained.
  3131. Also fires a new event.
  3132. This is basically like putting a whole new
  3133. :class:`.PrimaryKeyConstraint` object on the parent
  3134. :class:`_schema.Table` object without actually replacing the object.
  3135. The ordering of the given list of columns is also maintained; these
  3136. columns will be appended to the list of columns after any which
  3137. are already present.
  3138. """
  3139. # set the primary key flag on new columns.
  3140. # note any existing PK cols on the table also have their
  3141. # flag still set.
  3142. for col in columns:
  3143. col.primary_key = True
  3144. self.columns.extend(columns)
  3145. PrimaryKeyConstraint._autoincrement_column._reset(self)
  3146. self._set_parent_with_dispatch(self.table)
  3147. def _replace(self, col):
  3148. PrimaryKeyConstraint._autoincrement_column._reset(self)
  3149. self.columns.replace(col)
  3150. self.dispatch._sa_event_column_added_to_pk_constraint(self, col)
  3151. @property
  3152. def columns_autoinc_first(self):
  3153. autoinc = self._autoincrement_column
  3154. if autoinc is not None:
  3155. return [autoinc] + [c for c in self.columns if c is not autoinc]
  3156. else:
  3157. return list(self.columns)
  3158. @util.memoized_property
  3159. def _autoincrement_column(self):
  3160. def _validate_autoinc(col, autoinc_true):
  3161. if col.type._type_affinity is None or not issubclass(
  3162. col.type._type_affinity, type_api.INTEGERTYPE._type_affinity
  3163. ):
  3164. if autoinc_true:
  3165. raise exc.ArgumentError(
  3166. "Column type %s on column '%s' is not "
  3167. "compatible with autoincrement=True" % (col.type, col)
  3168. )
  3169. else:
  3170. return False
  3171. elif (
  3172. not isinstance(col.default, (type(None), Sequence))
  3173. and not autoinc_true
  3174. ):
  3175. return False
  3176. elif (
  3177. col.server_default is not None
  3178. and not isinstance(col.server_default, Identity)
  3179. and not autoinc_true
  3180. ):
  3181. return False
  3182. elif col.foreign_keys and col.autoincrement not in (
  3183. True,
  3184. "ignore_fk",
  3185. ):
  3186. return False
  3187. return True
  3188. if len(self.columns) == 1:
  3189. col = list(self.columns)[0]
  3190. if col.autoincrement is True:
  3191. _validate_autoinc(col, True)
  3192. return col
  3193. elif (
  3194. col.autoincrement
  3195. in (
  3196. "auto",
  3197. "ignore_fk",
  3198. )
  3199. and _validate_autoinc(col, False)
  3200. ):
  3201. return col
  3202. else:
  3203. autoinc = None
  3204. for col in self.columns:
  3205. if col.autoincrement is True:
  3206. _validate_autoinc(col, True)
  3207. if autoinc is not None:
  3208. raise exc.ArgumentError(
  3209. "Only one Column may be marked "
  3210. "autoincrement=True, found both %s and %s."
  3211. % (col.name, autoinc.name)
  3212. )
  3213. else:
  3214. autoinc = col
  3215. return autoinc
  3216. class UniqueConstraint(ColumnCollectionConstraint):
  3217. """A table-level UNIQUE constraint.
  3218. Defines a single column or composite UNIQUE constraint. For a no-frills,
  3219. single column constraint, adding ``unique=True`` to the ``Column``
  3220. definition is a shorthand equivalent for an unnamed, single column
  3221. UniqueConstraint.
  3222. """
  3223. __visit_name__ = "unique_constraint"
  3224. class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem):
  3225. """A table-level INDEX.
  3226. Defines a composite (one or more column) INDEX.
  3227. E.g.::
  3228. sometable = Table("sometable", metadata,
  3229. Column("name", String(50)),
  3230. Column("address", String(100))
  3231. )
  3232. Index("some_index", sometable.c.name)
  3233. For a no-frills, single column index, adding
  3234. :class:`_schema.Column` also supports ``index=True``::
  3235. sometable = Table("sometable", metadata,
  3236. Column("name", String(50), index=True)
  3237. )
  3238. For a composite index, multiple columns can be specified::
  3239. Index("some_index", sometable.c.name, sometable.c.address)
  3240. Functional indexes are supported as well, typically by using the
  3241. :data:`.func` construct in conjunction with table-bound
  3242. :class:`_schema.Column` objects::
  3243. Index("some_index", func.lower(sometable.c.name))
  3244. An :class:`.Index` can also be manually associated with a
  3245. :class:`_schema.Table`,
  3246. either through inline declaration or using
  3247. :meth:`_schema.Table.append_constraint`. When this approach is used,
  3248. the names
  3249. of the indexed columns can be specified as strings::
  3250. Table("sometable", metadata,
  3251. Column("name", String(50)),
  3252. Column("address", String(100)),
  3253. Index("some_index", "name", "address")
  3254. )
  3255. To support functional or expression-based indexes in this form, the
  3256. :func:`_expression.text` construct may be used::
  3257. from sqlalchemy import text
  3258. Table("sometable", metadata,
  3259. Column("name", String(50)),
  3260. Column("address", String(100)),
  3261. Index("some_index", text("lower(name)"))
  3262. )
  3263. .. versionadded:: 0.9.5 the :func:`_expression.text`
  3264. construct may be used to
  3265. specify :class:`.Index` expressions, provided the :class:`.Index`
  3266. is explicitly associated with the :class:`_schema.Table`.
  3267. .. seealso::
  3268. :ref:`schema_indexes` - General information on :class:`.Index`.
  3269. :ref:`postgresql_indexes` - PostgreSQL-specific options available for
  3270. the :class:`.Index` construct.
  3271. :ref:`mysql_indexes` - MySQL-specific options available for the
  3272. :class:`.Index` construct.
  3273. :ref:`mssql_indexes` - MSSQL-specific options available for the
  3274. :class:`.Index` construct.
  3275. """
  3276. __visit_name__ = "index"
  3277. def __init__(self, name, *expressions, **kw):
  3278. r"""Construct an index object.
  3279. :param name:
  3280. The name of the index
  3281. :param \*expressions:
  3282. Column expressions to include in the index. The expressions
  3283. are normally instances of :class:`_schema.Column`, but may also
  3284. be arbitrary SQL expressions which ultimately refer to a
  3285. :class:`_schema.Column`.
  3286. :param unique=False:
  3287. Keyword only argument; if True, create a unique index.
  3288. :param quote=None:
  3289. Keyword only argument; whether to apply quoting to the name of
  3290. the index. Works in the same manner as that of
  3291. :paramref:`_schema.Column.quote`.
  3292. :param info=None: Optional data dictionary which will be populated
  3293. into the :attr:`.SchemaItem.info` attribute of this object.
  3294. .. versionadded:: 1.0.0
  3295. :param \**kw: Additional keyword arguments not mentioned above are
  3296. dialect specific, and passed in the form
  3297. ``<dialectname>_<argname>``. See the documentation regarding an
  3298. individual dialect at :ref:`dialect_toplevel` for detail on
  3299. documented arguments.
  3300. """
  3301. self.table = table = None
  3302. self.name = quoted_name(name, kw.pop("quote", None))
  3303. self.unique = kw.pop("unique", False)
  3304. _column_flag = kw.pop("_column_flag", False)
  3305. if "info" in kw:
  3306. self.info = kw.pop("info")
  3307. # TODO: consider "table" argument being public, but for
  3308. # the purpose of the fix here, it starts as private.
  3309. if "_table" in kw:
  3310. table = kw.pop("_table")
  3311. self._validate_dialect_kwargs(kw)
  3312. self.expressions = []
  3313. # will call _set_parent() if table-bound column
  3314. # objects are present
  3315. ColumnCollectionMixin.__init__(
  3316. self,
  3317. *expressions,
  3318. _column_flag=_column_flag,
  3319. _gather_expressions=self.expressions
  3320. )
  3321. if table is not None:
  3322. self._set_parent(table)
  3323. def _set_parent(self, table, **kw):
  3324. ColumnCollectionMixin._set_parent(self, table)
  3325. if self.table is not None and table is not self.table:
  3326. raise exc.ArgumentError(
  3327. "Index '%s' is against table '%s', and "
  3328. "cannot be associated with table '%s'."
  3329. % (self.name, self.table.description, table.description)
  3330. )
  3331. self.table = table
  3332. table.indexes.add(self)
  3333. expressions = self.expressions
  3334. col_expressions = self._col_expressions(table)
  3335. assert len(expressions) == len(col_expressions)
  3336. self.expressions = [
  3337. expr if isinstance(expr, ClauseElement) else colexpr
  3338. for expr, colexpr in zip(expressions, col_expressions)
  3339. ]
  3340. @property
  3341. def bind(self):
  3342. """Return the connectable associated with this Index."""
  3343. return self.table.bind
  3344. def create(self, bind=None, checkfirst=False):
  3345. """Issue a ``CREATE`` statement for this
  3346. :class:`.Index`, using the given :class:`.Connectable`
  3347. for connectivity.
  3348. .. seealso::
  3349. :meth:`_schema.MetaData.create_all`.
  3350. """
  3351. if bind is None:
  3352. bind = _bind_or_error(self)
  3353. bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
  3354. return self
  3355. def drop(self, bind=None, checkfirst=False):
  3356. """Issue a ``DROP`` statement for this
  3357. :class:`.Index`, using the given :class:`.Connectable`
  3358. for connectivity.
  3359. .. seealso::
  3360. :meth:`_schema.MetaData.drop_all`.
  3361. """
  3362. if bind is None:
  3363. bind = _bind_or_error(self)
  3364. bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
  3365. def __repr__(self):
  3366. return "Index(%s)" % (
  3367. ", ".join(
  3368. [repr(self.name)]
  3369. + [repr(e) for e in self.expressions]
  3370. + (self.unique and ["unique=True"] or [])
  3371. )
  3372. )
  3373. DEFAULT_NAMING_CONVENTION = util.immutabledict({"ix": "ix_%(column_0_label)s"})
  3374. class MetaData(SchemaItem):
  3375. """A collection of :class:`_schema.Table`
  3376. objects and their associated schema
  3377. constructs.
  3378. Holds a collection of :class:`_schema.Table` objects as well as
  3379. an optional binding to an :class:`_engine.Engine` or
  3380. :class:`_engine.Connection`. If bound, the :class:`_schema.Table` objects
  3381. in the collection and their columns may participate in implicit SQL
  3382. execution.
  3383. The :class:`_schema.Table` objects themselves are stored in the
  3384. :attr:`_schema.MetaData.tables` dictionary.
  3385. :class:`_schema.MetaData` is a thread-safe object for read operations.
  3386. Construction of new tables within a single :class:`_schema.MetaData`
  3387. object,
  3388. either explicitly or via reflection, may not be completely thread-safe.
  3389. .. seealso::
  3390. :ref:`metadata_describing` - Introduction to database metadata
  3391. """
  3392. __visit_name__ = "metadata"
  3393. @util.deprecated_params(
  3394. bind=(
  3395. "2.0",
  3396. "The :paramref:`_schema.MetaData.bind` argument is deprecated and "
  3397. "will be removed in SQLAlchemy 2.0.",
  3398. ),
  3399. )
  3400. def __init__(
  3401. self,
  3402. bind=None,
  3403. schema=None,
  3404. quote_schema=None,
  3405. naming_convention=None,
  3406. info=None,
  3407. ):
  3408. """Create a new MetaData object.
  3409. :param bind:
  3410. An Engine or Connection to bind to. May also be a string or URL
  3411. instance, these are passed to :func:`_sa.create_engine` and
  3412. this :class:`_schema.MetaData` will
  3413. be bound to the resulting engine.
  3414. :param schema:
  3415. The default schema to use for the :class:`_schema.Table`,
  3416. :class:`.Sequence`, and potentially other objects associated with
  3417. this :class:`_schema.MetaData`. Defaults to ``None``.
  3418. .. seealso::
  3419. :ref:`schema_metadata_schema_name` - details on how the
  3420. :paramref:`_schema.MetaData.schema` parameter is used.
  3421. :paramref:`_schema.Table.schema`
  3422. :paramref:`.Sequence.schema`
  3423. :param quote_schema:
  3424. Sets the ``quote_schema`` flag for those :class:`_schema.Table`,
  3425. :class:`.Sequence`, and other objects which make usage of the
  3426. local ``schema`` name.
  3427. :param info: Optional data dictionary which will be populated into the
  3428. :attr:`.SchemaItem.info` attribute of this object.
  3429. .. versionadded:: 1.0.0
  3430. :param naming_convention: a dictionary referring to values which
  3431. will establish default naming conventions for :class:`.Constraint`
  3432. and :class:`.Index` objects, for those objects which are not given
  3433. a name explicitly.
  3434. The keys of this dictionary may be:
  3435. * a constraint or Index class, e.g. the :class:`.UniqueConstraint`,
  3436. :class:`_schema.ForeignKeyConstraint` class, the :class:`.Index`
  3437. class
  3438. * a string mnemonic for one of the known constraint classes;
  3439. ``"fk"``, ``"pk"``, ``"ix"``, ``"ck"``, ``"uq"`` for foreign key,
  3440. primary key, index, check, and unique constraint, respectively.
  3441. * the string name of a user-defined "token" that can be used
  3442. to define new naming tokens.
  3443. The values associated with each "constraint class" or "constraint
  3444. mnemonic" key are string naming templates, such as
  3445. ``"uq_%(table_name)s_%(column_0_name)s"``,
  3446. which describe how the name should be composed. The values
  3447. associated with user-defined "token" keys should be callables of the
  3448. form ``fn(constraint, table)``, which accepts the constraint/index
  3449. object and :class:`_schema.Table` as arguments, returning a string
  3450. result.
  3451. The built-in names are as follows, some of which may only be
  3452. available for certain types of constraint:
  3453. * ``%(table_name)s`` - the name of the :class:`_schema.Table`
  3454. object
  3455. associated with the constraint.
  3456. * ``%(referred_table_name)s`` - the name of the
  3457. :class:`_schema.Table`
  3458. object associated with the referencing target of a
  3459. :class:`_schema.ForeignKeyConstraint`.
  3460. * ``%(column_0_name)s`` - the name of the :class:`_schema.Column`
  3461. at
  3462. index position "0" within the constraint.
  3463. * ``%(column_0N_name)s`` - the name of all :class:`_schema.Column`
  3464. objects in order within the constraint, joined without a
  3465. separator.
  3466. * ``%(column_0_N_name)s`` - the name of all
  3467. :class:`_schema.Column`
  3468. objects in order within the constraint, joined with an
  3469. underscore as a separator.
  3470. * ``%(column_0_label)s``, ``%(column_0N_label)s``,
  3471. ``%(column_0_N_label)s`` - the label of either the zeroth
  3472. :class:`_schema.Column` or all :class:`.Columns`, separated with
  3473. or without an underscore
  3474. * ``%(column_0_key)s``, ``%(column_0N_key)s``,
  3475. ``%(column_0_N_key)s`` - the key of either the zeroth
  3476. :class:`_schema.Column` or all :class:`.Columns`, separated with
  3477. or without an underscore
  3478. * ``%(referred_column_0_name)s``, ``%(referred_column_0N_name)s``
  3479. ``%(referred_column_0_N_name)s``, ``%(referred_column_0_key)s``,
  3480. ``%(referred_column_0N_key)s``, ... column tokens which
  3481. render the names/keys/labels of columns that are referenced
  3482. by a :class:`_schema.ForeignKeyConstraint`.
  3483. * ``%(constraint_name)s`` - a special key that refers to the
  3484. existing name given to the constraint. When this key is
  3485. present, the :class:`.Constraint` object's existing name will be
  3486. replaced with one that is composed from template string that
  3487. uses this token. When this token is present, it is required that
  3488. the :class:`.Constraint` is given an explicit name ahead of time.
  3489. * user-defined: any additional token may be implemented by passing
  3490. it along with a ``fn(constraint, table)`` callable to the
  3491. naming_convention dictionary.
  3492. .. versionadded:: 1.3.0 - added new ``%(column_0N_name)s``,
  3493. ``%(column_0_N_name)s``, and related tokens that produce
  3494. concatenations of names, keys, or labels for all columns referred
  3495. to by a given constraint.
  3496. .. seealso::
  3497. :ref:`constraint_naming_conventions` - for detailed usage
  3498. examples.
  3499. """
  3500. self.tables = util.FacadeDict()
  3501. self.schema = quoted_name(schema, quote_schema)
  3502. self.naming_convention = (
  3503. naming_convention
  3504. if naming_convention
  3505. else DEFAULT_NAMING_CONVENTION
  3506. )
  3507. if info:
  3508. self.info = info
  3509. self._schemas = set()
  3510. self._sequences = {}
  3511. self._fk_memos = collections.defaultdict(list)
  3512. self.bind = bind
  3513. tables = None
  3514. """A dictionary of :class:`_schema.Table`
  3515. objects keyed to their name or "table key".
  3516. The exact key is that determined by the :attr:`_schema.Table.key`
  3517. attribute;
  3518. for a table with no :attr:`_schema.Table.schema` attribute,
  3519. this is the same
  3520. as :attr:`_schema.Table.name`. For a table with a schema,
  3521. it is typically of the
  3522. form ``schemaname.tablename``.
  3523. .. seealso::
  3524. :attr:`_schema.MetaData.sorted_tables`
  3525. """
  3526. def __repr__(self):
  3527. if self.bind:
  3528. return "MetaData(bind=%r)" % self.bind
  3529. else:
  3530. return "MetaData()"
  3531. def __contains__(self, table_or_key):
  3532. if not isinstance(table_or_key, util.string_types):
  3533. table_or_key = table_or_key.key
  3534. return table_or_key in self.tables
  3535. def _add_table(self, name, schema, table):
  3536. key = _get_table_key(name, schema)
  3537. self.tables._insert_item(key, table)
  3538. if schema:
  3539. self._schemas.add(schema)
  3540. def _remove_table(self, name, schema):
  3541. key = _get_table_key(name, schema)
  3542. removed = dict.pop(self.tables, key, None)
  3543. if removed is not None:
  3544. for fk in removed.foreign_keys:
  3545. fk._remove_from_metadata(self)
  3546. if self._schemas:
  3547. self._schemas = set(
  3548. [
  3549. t.schema
  3550. for t in self.tables.values()
  3551. if t.schema is not None
  3552. ]
  3553. )
  3554. def __getstate__(self):
  3555. return {
  3556. "tables": self.tables,
  3557. "schema": self.schema,
  3558. "schemas": self._schemas,
  3559. "sequences": self._sequences,
  3560. "fk_memos": self._fk_memos,
  3561. "naming_convention": self.naming_convention,
  3562. }
  3563. def __setstate__(self, state):
  3564. self.tables = state["tables"]
  3565. self.schema = state["schema"]
  3566. self.naming_convention = state["naming_convention"]
  3567. self._bind = None
  3568. self._sequences = state["sequences"]
  3569. self._schemas = state["schemas"]
  3570. self._fk_memos = state["fk_memos"]
  3571. def is_bound(self):
  3572. """True if this MetaData is bound to an Engine or Connection."""
  3573. return self._bind is not None
  3574. def bind(self):
  3575. """An :class:`_engine.Engine` or :class:`_engine.Connection`
  3576. to which this
  3577. :class:`_schema.MetaData` is bound.
  3578. Typically, a :class:`_engine.Engine` is assigned to this attribute
  3579. so that "implicit execution" may be used, or alternatively
  3580. as a means of providing engine binding information to an
  3581. ORM :class:`.Session` object::
  3582. engine = create_engine("someurl://")
  3583. metadata.bind = engine
  3584. .. seealso::
  3585. :ref:`dbengine_implicit` - background on "bound metadata"
  3586. """
  3587. return self._bind
  3588. @util.preload_module("sqlalchemy.engine.url")
  3589. def _bind_to(self, bind):
  3590. """Bind this MetaData to an Engine, Connection, string or URL."""
  3591. url = util.preloaded.engine_url
  3592. if isinstance(bind, util.string_types + (url.URL,)):
  3593. self._bind = sqlalchemy.create_engine(bind)
  3594. else:
  3595. self._bind = bind
  3596. bind = property(bind, _bind_to)
  3597. def clear(self):
  3598. """Clear all Table objects from this MetaData."""
  3599. dict.clear(self.tables)
  3600. self._schemas.clear()
  3601. self._fk_memos.clear()
  3602. def remove(self, table):
  3603. """Remove the given Table object from this MetaData."""
  3604. self._remove_table(table.name, table.schema)
  3605. @property
  3606. def sorted_tables(self):
  3607. """Returns a list of :class:`_schema.Table` objects sorted in order of
  3608. foreign key dependency.
  3609. The sorting will place :class:`_schema.Table`
  3610. objects that have dependencies
  3611. first, before the dependencies themselves, representing the
  3612. order in which they can be created. To get the order in which
  3613. the tables would be dropped, use the ``reversed()`` Python built-in.
  3614. .. warning::
  3615. The :attr:`.MetaData.sorted_tables` attribute cannot by itself
  3616. accommodate automatic resolution of dependency cycles between
  3617. tables, which are usually caused by mutually dependent foreign key
  3618. constraints. When these cycles are detected, the foreign keys
  3619. of these tables are omitted from consideration in the sort.
  3620. A warning is emitted when this condition occurs, which will be an
  3621. exception raise in a future release. Tables which are not part
  3622. of the cycle will still be returned in dependency order.
  3623. To resolve these cycles, the
  3624. :paramref:`_schema.ForeignKeyConstraint.use_alter` parameter may be
  3625. applied to those constraints which create a cycle. Alternatively,
  3626. the :func:`_schema.sort_tables_and_constraints` function will
  3627. automatically return foreign key constraints in a separate
  3628. collection when cycles are detected so that they may be applied
  3629. to a schema separately.
  3630. .. versionchanged:: 1.3.17 - a warning is emitted when
  3631. :attr:`.MetaData.sorted_tables` cannot perform a proper sort
  3632. due to cyclical dependencies. This will be an exception in a
  3633. future release. Additionally, the sort will continue to return
  3634. other tables not involved in the cycle in dependency order which
  3635. was not the case previously.
  3636. .. seealso::
  3637. :func:`_schema.sort_tables`
  3638. :func:`_schema.sort_tables_and_constraints`
  3639. :attr:`_schema.MetaData.tables`
  3640. :meth:`_reflection.Inspector.get_table_names`
  3641. :meth:`_reflection.Inspector.get_sorted_table_and_fkc_names`
  3642. """
  3643. return ddl.sort_tables(
  3644. sorted(self.tables.values(), key=lambda t: t.key)
  3645. )
  3646. def reflect(
  3647. self,
  3648. bind=None,
  3649. schema=None,
  3650. views=False,
  3651. only=None,
  3652. extend_existing=False,
  3653. autoload_replace=True,
  3654. resolve_fks=True,
  3655. **dialect_kwargs
  3656. ):
  3657. r"""Load all available table definitions from the database.
  3658. Automatically creates ``Table`` entries in this ``MetaData`` for any
  3659. table available in the database but not yet present in the
  3660. ``MetaData``. May be called multiple times to pick up tables recently
  3661. added to the database, however no special action is taken if a table
  3662. in this ``MetaData`` no longer exists in the database.
  3663. :param bind:
  3664. A :class:`.Connectable` used to access the database; if None, uses
  3665. the existing bind on this ``MetaData``, if any.
  3666. .. note:: the "bind" argument will be required in
  3667. SQLAlchemy 2.0.
  3668. :param schema:
  3669. Optional, query and reflect tables from an alternate schema.
  3670. If None, the schema associated with this :class:`_schema.MetaData`
  3671. is used, if any.
  3672. :param views:
  3673. If True, also reflect views.
  3674. :param only:
  3675. Optional. Load only a sub-set of available named tables. May be
  3676. specified as a sequence of names or a callable.
  3677. If a sequence of names is provided, only those tables will be
  3678. reflected. An error is raised if a table is requested but not
  3679. available. Named tables already present in this ``MetaData`` are
  3680. ignored.
  3681. If a callable is provided, it will be used as a boolean predicate to
  3682. filter the list of potential table names. The callable is called
  3683. with a table name and this ``MetaData`` instance as positional
  3684. arguments and should return a true value for any table to reflect.
  3685. :param extend_existing: Passed along to each :class:`_schema.Table` as
  3686. :paramref:`_schema.Table.extend_existing`.
  3687. .. versionadded:: 0.9.1
  3688. :param autoload_replace: Passed along to each :class:`_schema.Table`
  3689. as
  3690. :paramref:`_schema.Table.autoload_replace`.
  3691. .. versionadded:: 0.9.1
  3692. :param resolve_fks: if True, reflect :class:`_schema.Table`
  3693. objects linked
  3694. to :class:`_schema.ForeignKey` objects located in each
  3695. :class:`_schema.Table`.
  3696. For :meth:`_schema.MetaData.reflect`,
  3697. this has the effect of reflecting
  3698. related tables that might otherwise not be in the list of tables
  3699. being reflected, for example if the referenced table is in a
  3700. different schema or is omitted via the
  3701. :paramref:`.MetaData.reflect.only` parameter. When False,
  3702. :class:`_schema.ForeignKey` objects are not followed to the
  3703. :class:`_schema.Table`
  3704. in which they link, however if the related table is also part of the
  3705. list of tables that would be reflected in any case, the
  3706. :class:`_schema.ForeignKey` object will still resolve to its related
  3707. :class:`_schema.Table` after the :meth:`_schema.MetaData.reflect`
  3708. operation is
  3709. complete. Defaults to True.
  3710. .. versionadded:: 1.3.0
  3711. .. seealso::
  3712. :paramref:`_schema.Table.resolve_fks`
  3713. :param \**dialect_kwargs: Additional keyword arguments not mentioned
  3714. above are dialect specific, and passed in the form
  3715. ``<dialectname>_<argname>``. See the documentation regarding an
  3716. individual dialect at :ref:`dialect_toplevel` for detail on
  3717. documented arguments.
  3718. .. versionadded:: 0.9.2 - Added
  3719. :paramref:`.MetaData.reflect.**dialect_kwargs` to support
  3720. dialect-level reflection options for all :class:`_schema.Table`
  3721. objects reflected.
  3722. """
  3723. if bind is None:
  3724. bind = _bind_or_error(self)
  3725. with inspection.inspect(bind)._inspection_context() as insp:
  3726. reflect_opts = {
  3727. "autoload_with": insp,
  3728. "extend_existing": extend_existing,
  3729. "autoload_replace": autoload_replace,
  3730. "resolve_fks": resolve_fks,
  3731. "_extend_on": set(),
  3732. }
  3733. reflect_opts.update(dialect_kwargs)
  3734. if schema is None:
  3735. schema = self.schema
  3736. if schema is not None:
  3737. reflect_opts["schema"] = schema
  3738. available = util.OrderedSet(insp.get_table_names(schema))
  3739. if views:
  3740. available.update(insp.get_view_names(schema))
  3741. if schema is not None:
  3742. available_w_schema = util.OrderedSet(
  3743. ["%s.%s" % (schema, name) for name in available]
  3744. )
  3745. else:
  3746. available_w_schema = available
  3747. current = set(self.tables)
  3748. if only is None:
  3749. load = [
  3750. name
  3751. for name, schname in zip(available, available_w_schema)
  3752. if extend_existing or schname not in current
  3753. ]
  3754. elif callable(only):
  3755. load = [
  3756. name
  3757. for name, schname in zip(available, available_w_schema)
  3758. if (extend_existing or schname not in current)
  3759. and only(name, self)
  3760. ]
  3761. else:
  3762. missing = [name for name in only if name not in available]
  3763. if missing:
  3764. s = schema and (" schema '%s'" % schema) or ""
  3765. raise exc.InvalidRequestError(
  3766. "Could not reflect: requested table(s) not available "
  3767. "in %r%s: (%s)" % (bind.engine, s, ", ".join(missing))
  3768. )
  3769. load = [
  3770. name
  3771. for name in only
  3772. if extend_existing or name not in current
  3773. ]
  3774. for name in load:
  3775. try:
  3776. Table(name, self, **reflect_opts)
  3777. except exc.UnreflectableTableError as uerr:
  3778. util.warn("Skipping table %s: %s" % (name, uerr))
  3779. def create_all(self, bind=None, tables=None, checkfirst=True):
  3780. """Create all tables stored in this metadata.
  3781. Conditional by default, will not attempt to recreate tables already
  3782. present in the target database.
  3783. :param bind:
  3784. A :class:`.Connectable` used to access the
  3785. database; if None, uses the existing bind on this ``MetaData``, if
  3786. any.
  3787. .. note:: the "bind" argument will be required in
  3788. SQLAlchemy 2.0.
  3789. :param tables:
  3790. Optional list of ``Table`` objects, which is a subset of the total
  3791. tables in the ``MetaData`` (others are ignored).
  3792. :param checkfirst:
  3793. Defaults to True, don't issue CREATEs for tables already present
  3794. in the target database.
  3795. """
  3796. if bind is None:
  3797. bind = _bind_or_error(self)
  3798. bind._run_ddl_visitor(
  3799. ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables
  3800. )
  3801. def drop_all(self, bind=None, tables=None, checkfirst=True):
  3802. """Drop all tables stored in this metadata.
  3803. Conditional by default, will not attempt to drop tables not present in
  3804. the target database.
  3805. :param bind:
  3806. A :class:`.Connectable` used to access the
  3807. database; if None, uses the existing bind on this ``MetaData``, if
  3808. any.
  3809. .. note:: the "bind" argument will be required in
  3810. SQLAlchemy 2.0.
  3811. :param tables:
  3812. Optional list of ``Table`` objects, which is a subset of the
  3813. total tables in the ``MetaData`` (others are ignored).
  3814. :param checkfirst:
  3815. Defaults to True, only issue DROPs for tables confirmed to be
  3816. present in the target database.
  3817. """
  3818. if bind is None:
  3819. bind = _bind_or_error(self)
  3820. bind._run_ddl_visitor(
  3821. ddl.SchemaDropper, self, checkfirst=checkfirst, tables=tables
  3822. )
  3823. @util.deprecated_cls(
  3824. "1.4",
  3825. ":class:`.ThreadLocalMetaData` is deprecated and will be removed "
  3826. "in a future release.",
  3827. constructor="__init__",
  3828. )
  3829. class ThreadLocalMetaData(MetaData):
  3830. """A MetaData variant that presents a different ``bind`` in every thread.
  3831. Makes the ``bind`` property of the MetaData a thread-local value, allowing
  3832. this collection of tables to be bound to different ``Engine``
  3833. implementations or connections in each thread.
  3834. The ThreadLocalMetaData starts off bound to None in each thread. Binds
  3835. must be made explicitly by assigning to the ``bind`` property or using
  3836. ``connect()``. You can also re-bind dynamically multiple times per
  3837. thread, just like a regular ``MetaData``.
  3838. """
  3839. __visit_name__ = "metadata"
  3840. def __init__(self):
  3841. """Construct a ThreadLocalMetaData."""
  3842. self.context = util.threading.local()
  3843. self.__engines = {}
  3844. super(ThreadLocalMetaData, self).__init__()
  3845. def bind(self):
  3846. """The bound Engine or Connection for this thread.
  3847. This property may be assigned an Engine or Connection, or assigned a
  3848. string or URL to automatically create a basic Engine for this bind
  3849. with ``create_engine()``."""
  3850. return getattr(self.context, "_engine", None)
  3851. @util.preload_module("sqlalchemy.engine.url")
  3852. def _bind_to(self, bind):
  3853. """Bind to a Connectable in the caller's thread."""
  3854. url = util.preloaded.engine_url
  3855. if isinstance(bind, util.string_types + (url.URL,)):
  3856. try:
  3857. self.context._engine = self.__engines[bind]
  3858. except KeyError:
  3859. e = sqlalchemy.create_engine(bind)
  3860. self.__engines[bind] = e
  3861. self.context._engine = e
  3862. else:
  3863. # TODO: this is squirrely. we shouldn't have to hold onto engines
  3864. # in a case like this
  3865. if bind not in self.__engines:
  3866. self.__engines[bind] = bind
  3867. self.context._engine = bind
  3868. bind = property(bind, _bind_to)
  3869. def is_bound(self):
  3870. """True if there is a bind for this thread."""
  3871. return (
  3872. hasattr(self.context, "_engine")
  3873. and self.context._engine is not None
  3874. )
  3875. def dispose(self):
  3876. """Dispose all bound engines, in all thread contexts."""
  3877. for e in self.__engines.values():
  3878. if hasattr(e, "dispose"):
  3879. e.dispose()
  3880. class Computed(FetchedValue, SchemaItem):
  3881. """Defines a generated column, i.e. "GENERATED ALWAYS AS" syntax.
  3882. The :class:`.Computed` construct is an inline construct added to the
  3883. argument list of a :class:`_schema.Column` object::
  3884. from sqlalchemy import Computed
  3885. Table('square', meta,
  3886. Column('side', Float, nullable=False),
  3887. Column('area', Float, Computed('side * side'))
  3888. )
  3889. See the linked documentation below for complete details.
  3890. .. versionadded:: 1.3.11
  3891. .. seealso::
  3892. :ref:`computed_ddl`
  3893. """
  3894. __visit_name__ = "computed_column"
  3895. @_document_text_coercion(
  3896. "sqltext", ":class:`.Computed`", ":paramref:`.Computed.sqltext`"
  3897. )
  3898. def __init__(self, sqltext, persisted=None):
  3899. """Construct a GENERATED ALWAYS AS DDL construct to accompany a
  3900. :class:`_schema.Column`.
  3901. :param sqltext:
  3902. A string containing the column generation expression, which will be
  3903. used verbatim, or a SQL expression construct, such as a
  3904. :func:`_expression.text`
  3905. object. If given as a string, the object is converted to a
  3906. :func:`_expression.text` object.
  3907. :param persisted:
  3908. Optional, controls how this column should be persisted by the
  3909. database. Possible values are:
  3910. * ``None``, the default, it will use the default persistence
  3911. defined by the database.
  3912. * ``True``, will render ``GENERATED ALWAYS AS ... STORED``, or the
  3913. equivalent for the target database if supported.
  3914. * ``False``, will render ``GENERATED ALWAYS AS ... VIRTUAL``, or
  3915. the equivalent for the target database if supported.
  3916. Specifying ``True`` or ``False`` may raise an error when the DDL
  3917. is emitted to the target database if the database does not support
  3918. that persistence option. Leaving this parameter at its default
  3919. of ``None`` is guaranteed to succeed for all databases that support
  3920. ``GENERATED ALWAYS AS``.
  3921. """
  3922. self.sqltext = coercions.expect(roles.DDLExpressionRole, sqltext)
  3923. self.persisted = persisted
  3924. self.column = None
  3925. def _set_parent(self, parent, **kw):
  3926. if not isinstance(
  3927. parent.server_default, (type(None), Computed)
  3928. ) or not isinstance(parent.server_onupdate, (type(None), Computed)):
  3929. raise exc.ArgumentError(
  3930. "A generated column cannot specify a server_default or a "
  3931. "server_onupdate argument"
  3932. )
  3933. self.column = parent
  3934. parent.computed = self
  3935. self.column.server_onupdate = self
  3936. self.column.server_default = self
  3937. def _as_for_update(self, for_update):
  3938. return self
  3939. @util.deprecated(
  3940. "1.4",
  3941. "The :meth:`_schema.Computed.copy` method is deprecated "
  3942. "and will be removed in a future release.",
  3943. )
  3944. def copy(self, target_table=None, **kw):
  3945. return self._copy(target_table, **kw)
  3946. def _copy(self, target_table=None, **kw):
  3947. sqltext = _copy_expression(
  3948. self.sqltext,
  3949. self.column.table if self.column is not None else None,
  3950. target_table,
  3951. )
  3952. g = Computed(sqltext, persisted=self.persisted)
  3953. return self._schema_item_copy(g)
  3954. class Identity(IdentityOptions, FetchedValue, SchemaItem):
  3955. """Defines an identity column, i.e. "GENERATED { ALWAYS | BY DEFAULT }
  3956. AS IDENTITY" syntax.
  3957. The :class:`.Identity` construct is an inline construct added to the
  3958. argument list of a :class:`_schema.Column` object::
  3959. from sqlalchemy import Identity
  3960. Table('foo', meta,
  3961. Column('id', Integer, Identity())
  3962. Column('description', Text),
  3963. )
  3964. See the linked documentation below for complete details.
  3965. .. versionadded:: 1.4
  3966. .. seealso::
  3967. :ref:`identity_ddl`
  3968. """
  3969. __visit_name__ = "identity_column"
  3970. def __init__(
  3971. self,
  3972. always=False,
  3973. on_null=None,
  3974. start=None,
  3975. increment=None,
  3976. minvalue=None,
  3977. maxvalue=None,
  3978. nominvalue=None,
  3979. nomaxvalue=None,
  3980. cycle=None,
  3981. cache=None,
  3982. order=None,
  3983. ):
  3984. """Construct a GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY DDL
  3985. construct to accompany a :class:`_schema.Column`.
  3986. See the :class:`.Sequence` documentation for a complete description
  3987. of most parameters.
  3988. .. note::
  3989. MSSQL supports this construct as the preferred alternative to
  3990. generate an IDENTITY on a column, but it uses non standard
  3991. syntax that only support :paramref:`_schema.Identity.start`
  3992. and :paramref:`_schema.Identity.increment`.
  3993. All other parameters are ignored.
  3994. :param always:
  3995. A boolean, that indicates the type of identity column.
  3996. If ``False`` is specified, the default, then the user-specified
  3997. value takes precedence.
  3998. If ``True`` is specified, a user-specified value is not accepted (
  3999. on some backends, like PostgreSQL, OVERRIDING SYSTEM VALUE, or
  4000. similar, may be specified in an INSERT to override the sequence
  4001. value).
  4002. Some backends also have a default value for this parameter,
  4003. ``None`` can be used to omit rendering this part in the DDL. It
  4004. will be treated as ``False`` if a backend does not have a default
  4005. value.
  4006. :param on_null:
  4007. Set to ``True`` to specify ON NULL in conjunction with a
  4008. ``always=False`` identity column. This option is only supported on
  4009. some backends, like Oracle.
  4010. :param start: the starting index of the sequence.
  4011. :param increment: the increment value of the sequence.
  4012. :param minvalue: the minimum value of the sequence.
  4013. :param maxvalue: the maximum value of the sequence.
  4014. :param nominvalue: no minimum value of the sequence.
  4015. :param nomaxvalue: no maximum value of the sequence.
  4016. :param cycle: allows the sequence to wrap around when the maxvalue
  4017. or minvalue has been reached.
  4018. :param cache: optional integer value; number of future values in the
  4019. sequence which are calculated in advance.
  4020. :param order: optional boolean value; if true, renders the
  4021. ORDER keyword.
  4022. """
  4023. IdentityOptions.__init__(
  4024. self,
  4025. start=start,
  4026. increment=increment,
  4027. minvalue=minvalue,
  4028. maxvalue=maxvalue,
  4029. nominvalue=nominvalue,
  4030. nomaxvalue=nomaxvalue,
  4031. cycle=cycle,
  4032. cache=cache,
  4033. order=order,
  4034. )
  4035. self.always = always
  4036. self.on_null = on_null
  4037. self.column = None
  4038. def _set_parent(self, parent, **kw):
  4039. if not isinstance(
  4040. parent.server_default, (type(None), Identity)
  4041. ) or not isinstance(parent.server_onupdate, type(None)):
  4042. raise exc.ArgumentError(
  4043. "A column with an Identity object cannot specify a "
  4044. "server_default or a server_onupdate argument"
  4045. )
  4046. if parent.autoincrement is False:
  4047. raise exc.ArgumentError(
  4048. "A column with an Identity object cannot specify "
  4049. "autoincrement=False"
  4050. )
  4051. self.column = parent
  4052. parent.identity = self
  4053. if parent._user_defined_nullable is NULL_UNSPECIFIED:
  4054. parent.nullable = False
  4055. parent.server_default = self
  4056. def _as_for_update(self, for_update):
  4057. return self
  4058. @util.deprecated(
  4059. "1.4",
  4060. "The :meth:`_schema.Identity.copy` method is deprecated "
  4061. "and will be removed in a future release.",
  4062. )
  4063. def copy(self, **kw):
  4064. return self._copy(**kw)
  4065. def _copy(self, **kw):
  4066. i = Identity(
  4067. always=self.always,
  4068. on_null=self.on_null,
  4069. start=self.start,
  4070. increment=self.increment,
  4071. minvalue=self.minvalue,
  4072. maxvalue=self.maxvalue,
  4073. nominvalue=self.nominvalue,
  4074. nomaxvalue=self.nomaxvalue,
  4075. cycle=self.cycle,
  4076. cache=self.cache,
  4077. order=self.order,
  4078. )
  4079. return self._schema_item_copy(i)