U a@sdZddlmZddlZddlZddlmZddlmZddlmZddlm Z dd lm Z dd l m Z dd l m Z dd l mZdd l mZddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl mZddl mZddlmZddlmZddlmZddlmZe dZ!e ddZ"e d d!Z#d"d#Z$d$d%Z%ej&Gd&d'd'ee j'Z(Gd(d)d)ee(eZ)Gd*d+d+ee(eZ*Gd,d-d-ee(Z+Gd.d/d/ee(Z,Gd0d1d1e,Z-Gd2d3d3e.Z/Gd4d5d5e/e,Z0ej&Gd6d7d7eZ1Gd8d9d9e1Z2Gd:d;d;ee(Z3Gdd?d?e4e3Z5Gd@dAdAe5Z6GdBdCdCe5Z7GdDdEdEe5Z8GdFdGdGe5Z9GdHdIdIee4e(Z:e;dJdKiZdNdOdPdQGdRdSdSe=Z?GdTdUdUe1e(Z@GdVdWdWe/e1e(ZAdS)Xa/The schema module provides the building blocks for database metadata. Each element within this module describes a database entity which can be created and dropped, or is otherwise part of such an entity. Examples include tables, columns, sequences, and indexes. All entities are subclasses of :class:`~sqlalchemy.schema.SchemaItem`, and as defined in this module they are intended to be agnostic of any vendor-specific constructs. A collection of entities are grouped into a unit called :class:`~sqlalchemy.schema.MetaData`. MetaData serves as a logical grouping of schema elements, and can also be associated with an actual database connection such that operations involving the contained elements can contact the database as needed. Two of the elements here also build upon their "syntactic" counterparts, which are defined in :class:`~sqlalchemy.sql.expression.`, specifically :class:`~sqlalchemy.schema.Table` and :class:`~sqlalchemy.schema.Column`. Since these objects are part of the SQL expression language, they are usable as components in SQL expressions. )absolute_importN) coercions)ddl)roles)type_api)visitors)_bind_or_error)DedupeColumnCollection) DialectKWArgs) Executable)SchemaEventTarget)_document_text_coercion) ClauseElement) ColumnClause) ColumnElement) quoted_name) TextClause) TableClause) to_instance)InternalTraversal)event)exc) inspection)utilZ retain_schemaZ blank_schemazSymbol indicating that a :class:`_schema.Table` or :class:`.Sequence` should have 'None' for its schema, even if the parent :class:`_schema.MetaData` has specified a schema. .. versionadded:: 1.0.14 NULL_UNSPECIFIEDzSymbol indicating the "nullable" keyword was not passed to a Column. Normally we would expect None to be acceptable for this but some backends such as that of SQL Server place special signficance on a "nullability" value of None. cCs|dkr |S|d|SdS)N.)nameschemarrVC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\sql\schema.py_get_table_keyVsr"cs0dksdkr|Sfdd}t|i|S)Ncs4t|tr,|jkr,|jjkr,j|jSdSdSN) isinstanceColumntablekeyc)col source_table target_tablerr!replacecs  z!_copy_expression..replace)rZreplacement_traverse)Z expressionr+r,r-rr*r!_copy_expression_s r.c@sBeZdZdZdZdZddZddZej dd Z d d Z d Z d S) SchemaItemz3Base class for items that define a database schema. schema_itemdefaultc Osh|D]^}|dk rz |j}Wn:tk rT}ztjtd||dW5d}~XYqX||f|qdS)z7Initialize the list of child items for this SchemaItem.NzJ'SchemaItem' object, such as a 'Column' or a 'Constraint' expected, got %r)Zreplace_context)_set_parent_with_dispatchAttributeErrorrraise_r ArgumentError)selfargskwitemZspwderrrrr! _init_itemsxs zSchemaItem._init_itemscCstj|dgdS)Ninfo)Z omit_kwargrZ generic_reprr6rrr!__repr__szSchemaItem.__repr__cCsiS)aZInfo dictionary associated with the object, allowing user-defined data to be associated with this :class:`.SchemaItem`. The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as :class:`_schema.Table` and :class:`_schema.Column`. rr>rrr!r<s zSchemaItem.infocCs(d|jkr|j|_|j|j|S)Nr<)__dict__r<copydispatch_update)r6r0rrr!_schema_item_copys  zSchemaItem._schema_item_copyTN) __name__ __module__ __qualname____doc____visit_name__Zcreate_drop_stringify_dialectr;r?rmemoized_propertyr<rDZ_use_schema_maprrrr!r/ps r/csReZdZdZdZdZdZejde j fgZddZ e j ddd d d Zd d ZfddZd@ddZeddZeddZddZddZddZddZed d!Zed"d#Zd$d%Zd&d'Zed(d)Zd*d+ZdAd-d.Zd/d0Z d1d2Z!e "d3d4dBd5d6Z#dCd7d8Z$dDd9d:Z%e "d3d;e&ddfdd?Z(Z)S)ETablea7Represent a table in a database. e.g.:: mytable = Table("mytable", metadata, Column('mytable_id', Integer, primary_key=True), Column('value', String(50)) ) The :class:`_schema.Table` object constructs a unique instance of itself based on its name and optional schema name within the given :class:`_schema.MetaData` object. Calling the :class:`_schema.Table` constructor with the same name and same :class:`_schema.MetaData` argument a second time will return the *same* :class:`_schema.Table` object - in this way the :class:`_schema.Table` constructor acts as a registry function. .. seealso:: :ref:`metadata_describing` - Introduction to database metadata Constructor arguments are as follows: :param name: The name of this table as represented in the database. The table name, along with the value of the ``schema`` parameter, forms a key which uniquely identifies this :class:`_schema.Table` within the owning :class:`_schema.MetaData` collection. Additional calls to :class:`_schema.Table` with the same name, metadata, and schema name will return the same :class:`_schema.Table` object. Names which contain no upper case characters will be treated as case insensitive names, and will not be quoted unless they are a reserved word or contain special characters. A name with any number of upper case characters is considered to be case sensitive, and will be sent as quoted. To enable unconditional quoting for the table name, specify the flag ``quote=True`` to the constructor, or use the :class:`.quoted_name` construct to specify the name. :param metadata: a :class:`_schema.MetaData` object which will contain this table. The metadata is used as a point of association of this table with other tables which are referenced via foreign key. It also may be used to associate this table with a particular :class:`.Connectable`. :param \*args: Additional positional arguments are used primarily to add the list of :class:`_schema.Column` objects contained within this table. Similar to the style of a CREATE TABLE statement, other :class:`.SchemaItem` constructs may be added here, including :class:`.PrimaryKeyConstraint`, and :class:`_schema.ForeignKeyConstraint`. :param autoload: Defaults to ``False``, unless :paramref:`_schema.Table.autoload_with` is set in which case it defaults to ``True``; :class:`_schema.Column` objects for this table should be reflected from the database, possibly augmenting objects that were explicitly specified. :class:`_schema.Column` and other objects explicitly set on the table will replace corresponding reflected objects. .. deprecated:: 1.4 The autoload parameter is deprecated and will be removed in version 2.0. Please use the :paramref:`_schema.Table.autoload_with` parameter, passing an engine or connection. .. seealso:: :ref:`metadata_reflection_toplevel` :param autoload_replace: Defaults to ``True``; when using :paramref:`_schema.Table.autoload` in conjunction with :paramref:`_schema.Table.extend_existing`, indicates that :class:`_schema.Column` objects present in the already-existing :class:`_schema.Table` object should be replaced with columns of the same name retrieved from the autoload process. When ``False``, columns already present under existing names will be omitted from the reflection process. Note that this setting does not impact :class:`_schema.Column` objects specified programmatically within the call to :class:`_schema.Table` that also is autoloading; those :class:`_schema.Column` objects will always replace existing columns of the same name when :paramref:`_schema.Table.extend_existing` is ``True``. .. seealso:: :paramref:`_schema.Table.autoload` :paramref:`_schema.Table.extend_existing` :param autoload_with: An :class:`_engine.Engine` or :class:`_engine.Connection` object, or a :class:`_reflection.Inspector` object as returned by :func:`_sa.inspect` against one, with which this :class:`_schema.Table` object will be reflected. When set to a non-None value, the autoload process will take place for this table against the given engine or connection. :param extend_existing: When ``True``, indicates that if this :class:`_schema.Table` is already present in the given :class:`_schema.MetaData`, apply further arguments within the constructor to the existing :class:`_schema.Table`. If :paramref:`_schema.Table.extend_existing` or :paramref:`_schema.Table.keep_existing` are not set, and the given name of the new :class:`_schema.Table` refers to a :class:`_schema.Table` that is already present in the target :class:`_schema.MetaData` collection, and this :class:`_schema.Table` specifies additional columns or other constructs or flags that modify the table's state, an error is raised. The purpose of these two mutually-exclusive flags is to specify what action should be taken when a :class:`_schema.Table` is specified that matches an existing :class:`_schema.Table`, yet specifies additional constructs. :paramref:`_schema.Table.extend_existing` will also work in conjunction with :paramref:`_schema.Table.autoload` to run a new reflection operation against the database, even if a :class:`_schema.Table` of the same name is already present in the target :class:`_schema.MetaData`; newly reflected :class:`_schema.Column` objects and other options will be added into the state of the :class:`_schema.Table`, potentially overwriting existing columns and options of the same name. As is always the case with :paramref:`_schema.Table.autoload`, :class:`_schema.Column` objects can be specified in the same :class:`_schema.Table` constructor, which will take precedence. Below, the existing table ``mytable`` will be augmented with :class:`_schema.Column` objects both reflected from the database, as well as the given :class:`_schema.Column` named "y":: Table("mytable", metadata, Column('y', Integer), extend_existing=True, autoload_with=engine ) .. seealso:: :paramref:`_schema.Table.autoload` :paramref:`_schema.Table.autoload_replace` :paramref:`_schema.Table.keep_existing` :param implicit_returning: True by default - indicates that RETURNING can be used by default to fetch newly inserted primary key values, for backends which support this. Note that :func:`_sa.create_engine` also provides an ``implicit_returning`` flag. :param include_columns: A list of strings indicating a subset of columns to be loaded via the ``autoload`` operation; table columns who aren't present in this list will not be represented on the resulting ``Table`` object. Defaults to ``None`` which indicates all columns should be reflected. :param resolve_fks: Whether or not to reflect :class:`_schema.Table` objects related to this one via :class:`_schema.ForeignKey` objects, when :paramref:`_schema.Table.autoload` or :paramref:`_schema.Table.autoload_with` is specified. Defaults to True. Set to False to disable reflection of related tables as :class:`_schema.ForeignKey` objects are encountered; may be used either to save on SQL calls or to avoid issues with related tables that can't be accessed. Note that if a related table is already present in the :class:`_schema.MetaData` collection, or becomes present later, a :class:`_schema.ForeignKey` object associated with this :class:`_schema.Table` will resolve to that table normally. .. versionadded:: 1.3 .. seealso:: :paramref:`.MetaData.reflect.resolve_fks` :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. :param keep_existing: When ``True``, indicates that if this Table is already present in the given :class:`_schema.MetaData`, ignore further arguments within the constructor to the existing :class:`_schema.Table`, and return the :class:`_schema.Table` object as originally created. This is to allow a function that wishes to define a new :class:`_schema.Table` on first call, but on subsequent calls will return the same :class:`_schema.Table`, without any of the declarations (particularly constraints) being applied a second time. If :paramref:`_schema.Table.extend_existing` or :paramref:`_schema.Table.keep_existing` are not set, and the given name of the new :class:`_schema.Table` refers to a :class:`_schema.Table` that is already present in the target :class:`_schema.MetaData` collection, and this :class:`_schema.Table` specifies additional columns or other constructs or flags that modify the table's state, an error is raised. The purpose of these two mutually-exclusive flags is to specify what action should be taken when a :class:`_schema.Table` is specified that matches an existing :class:`_schema.Table`, yet specifies additional constructs. .. seealso:: :paramref:`_schema.Table.extend_existing` :param listeners: A list of tuples of the form ``(, )`` which will be passed to :func:`.event.listen` upon construction. This alternate hook to :func:`.event.listen` allows the establishment of a listener function specific to this :class:`_schema.Table` before the "autoload" process begins. Historically this has been intended for use with the :meth:`.DDLEvents.column_reflect` event, however note that this event hook may now be associated with the :class:`_schema.MetaData` object directly:: def listen_for_reflect(table, column_info): "handle the column reflection event" # ... t = Table( 'sometable', autoload_with=engine, listeners=[ ('column_reflect', listen_for_reflect) ]) .. seealso:: :meth:`_events.DDLEvents.column_reflect` :param must_exist: When ``True``, indicates that this Table must already be present in the given :class:`_schema.MetaData` collection, else an exception is raised. :param prefixes: A list of strings to insert after CREATE in the CREATE TABLE statement. They will be separated by spaces. :param quote: Force quoting of this table's name on or off, corresponding to ``True`` or ``False``. When left at its default of ``None``, the column identifier will be quoted according to whether the name is case sensitive (identifiers with at least one upper case character are treated as case sensitive), or if it's a reserved word. This flag is only needed to force quoting of a reserved word which is not known by the SQLAlchemy dialect. :param quote_schema: same as 'quote' but applies to the schema identifier. :param schema: The schema name for this table, which is required if the table resides in a schema other than the default selected schema for the engine's database connection. Defaults to ``None``. If the owning :class:`_schema.MetaData` of this :class:`_schema.Table` specifies its own :paramref:`_schema.MetaData.schema` parameter, then that schema name will be applied to this :class:`_schema.Table` if the schema parameter here is set to ``None``. To set a blank schema name on a :class:`_schema.Table` that would otherwise use the schema set on the owning :class:`_schema.MetaData`, specify the special symbol :attr:`.BLANK_SCHEMA`. .. versionadded:: 1.0.14 Added the :attr:`.BLANK_SCHEMA` symbol to allow a :class:`_schema.Table` to have a blank schema name even when the parent :class:`_schema.MetaData` specifies :paramref:`_schema.MetaData.schema`. The quoting rules for the schema name are the same as those for the ``name`` parameter, in that quoting is applied for reserved words or case-sensitive names; to enable unconditional quoting for the schema name, specify the flag ``quote_schema=True`` to the constructor, or use the :class:`.quoted_name` construct to specify the name. :param comment: Optional string that will render an SQL comment on table creation. .. versionadded:: 1.2 Added the :paramref:`_schema.Table.comment` parameter to :class:`_schema.Table`. :param \**kw: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``_``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. r&Nr cCs|jr|f|jS|fSdSr#)Z _annotationsZ_annotations_cache_key)r6Zanon_mapZ bindparamsrrr!_gen_cache_keys zTable._gen_cache_key)1.4z8Deprecated alias of :paramref:`_schema.Table.must_exist`)2.0zThe autoload parameter is deprecated and will be removed in version 2.0. Please use the autoload_with parameter, passing an engine or connection.) mustexistautoloadc Os|s|st|Sz$|d|d|dd}}}Wntk rRtdYnX|dd}|dkrp|j}n |tkr|d}|dd}|dd}|r|rd }t|| d | d d} t ||} | |j kr|s|st |rt d | |j | } |r| j||| S| r&t d | t|} | j| ||||| z(| j||f||| j| || WStk rt|||W5QRXYnXdS)NrrrzJTable() takes at least two positional-only arguments 'name' and 'metadata'r keep_existingFextend_existingz9keep_existing and extend_existing are mutually exclusive. must_existrOzTable '%s' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.zTable '%s' not defined)object__new__ IndexError TypeErrorgetr BLANK_SCHEMArr5popr"tablesboolInvalidRequestError_init_existingrBZbefore_parent_attach _add_table_initafter_parent_attach ExceptionrZ safe_reraise _remove_table) clsr7r8rmetadatar rQrRmsgrSr'r&rrr!rUsV  $           z Table.__new__cOsdS)zConstructor for :class:`_schema.Table`. This method is a no-op. See the top-level documentation for :class:`_schema.Table` for constructor arguments. Nr)r6r7r8rrr!__init__[szTable.__init__cstt|t||dd||_|dd|_|jdkrF|j|_n,|jtkrXd|_n|dd}t|j||_t|_ t|_ t dd |t|_ t|_|jdk rd|j|jf|_n|j|_|dd}|d|dk }|d d|d d }|d d } |d d} |dd} |dd} |dd|_|dd|_d|kr^|d|_d|kr|d} | D]\}}t|||qv|ddpg|_|jf||r|j||| | | d|j|d| p|p|idS)Nquoter quote_schemaT)_implicit_generated%s.%s autoload_withrPautoload_replacerQFrR _extend_on resolve_fksinclude_columnsimplicit_returningcommentr< listenersprefixes)rnroallow_replacements)superrKrgrrZrer rYsetindexes constraintsPrimaryKeyConstraintr2 foreign_keys_extra_dependenciesrfullnamerqrrr<rlisten _prefixes _extra_kwargs _autoloadr;)r6rrer7kwargsrirlrPrQrRrnrorprsevtfn __class__rr!r`fsl                    z Table._initrTc CsJ|dkrt|dd}t|}|}|j|||||dW5QRXdS)NzuNo engine is bound to this Table's MetaData. Pass an engine to the Table via autoload_with=)rfrn)r rinspect_inspection_contextZ reflect_table) r6rerlrpexclude_columnsrorninspZ conn_insprrr!rs   zTable._autoloadcCst|jdddS)zTReturn the set of constraints as a list, sorted by creation order. cSs|jSr#)Z_creation_order)r(rrr!z+Table._sorted_constraints..r')sortedryr>rrr!_sorted_constraintsszTable._sorted_constraintscCstdd|jDS)a:class:`_schema.ForeignKeyConstraint` objects referred to by this :class:`_schema.Table`. This list is produced from the collection of :class:`_schema.ForeignKey` objects currently associated. .. seealso:: :attr:`_schema.Table.constraints` :attr:`_schema.Table.foreign_keys` :attr:`_schema.Table.indexes` css|] }|jVqdSr#) constraint).0fkcrrr! sz0Table.foreign_key_constraints..)rwr{r>rrr!foreign_key_constraintsszTable.foreign_key_constraintsc OsV|dd}|d|dk }|dd}|dd}|dd}|dd|d d|rx||jkrxtd |j|f|d d}|d d} |dk r|jD]} | j|kr|j| qd D]} | |krtdqd|kr|dd|_d|kr|d|_ |r<|s dd|jD} nd} |j |j ||| | |d|j f||j |dS)NrlrPrmTr rnrRFrQz7Can't change schema of existing table from '%s' to '%s'rpro)rhriz2Can't redefine 'quote' or 'quote_schema' argumentsrrr<cSsg|] }|jqSrrrr(rrr! sz(Table._init_existing..rr)rZr rr5r(r_columnsremoverrr<rrerr;) r6r7rrlrPrmr rnrpror(r'rrrr!r^sR             zTable._init_existingcKs||dSr#_validate_dialect_kwargsr6rrrr!r szTable._extra_kwargscCsdSr#rr>rrr!_init_collections#szTable._init_collectionscCsdSr#rr>rrr!_reset_exported&szTable._reset_exportedcCs|jjSr#) primary_key_autoincrement_columnr>rrr!r)szTable._autoincrement_columncCst|j|jS)aReturn the 'key' for this :class:`_schema.Table`. This value is used as the dictionary key within the :attr:`_schema.MetaData.tables` collection. It is typically the same as that of :attr:`_schema.Table.name` for a table with no :attr:`_schema.Table.schema` set; otherwise it is typically of the form ``schemaname.tablename``. )r"rr r>rrr!r'-s z Table.keycsDddtjgtjgddjDfdddDS)Nz Table(%s), cSsg|] }t|qSrreprrxrrr!r?sz"Table.__repr__..cs"g|]}d|tt|fqSz%s=%srgetattrrkr>rr!r@sr )joinrrrecolumnsr>rr>r!r?;s  zTable.__repr__cCst|j|jSr#)r" descriptionr r>rrr!__str__Csz Table.__str__cCs|jr|jjpdS)z2Return the connectable associated with this Table.Nrebindr>rrr!rFsz Table.bindcCs|j|dS)aAdd a 'dependency' for this Table. This is another Table object which must be created first before this one can, or dropped after this one. Usually, dependencies between tables are determined via ForeignKey objects. However, for other situations that create dependencies outside of foreign keys (rules, inheriting), this method can manually establish such a link. N)r|addr6r&rrr!add_is_dependent_onLs zTable.add_is_dependent_onFcCs|j||ddS)aAppend a :class:`_schema.Column` to this :class:`_schema.Table`. The "key" of the newly added :class:`_schema.Column`, i.e. the value of its ``.key`` attribute, will then be available in the ``.c`` collection of this :class:`_schema.Table`, and the column definition will be included in any CREATE TABLE, SELECT, UPDATE, etc. statements generated from this :class:`_schema.Table` construct. Note that this does **not** change the definition of the table as it exists within any underlying database, assuming that table has already been created in the database. Relational databases support the addition of columns to existing tables using the SQL ALTER command, which would need to be emitted for an already-existing table that doesn't contain the newly added column. :param replace_existing: When ``True``, allows replacing existing columns. When ``False``, the default, an warning will be raised if a column with the same ``.key`` already exists. A future version of sqlalchemy will instead rise a warning. .. versionadded:: 1.4.0 )ruNr2)r6columnZreplace_existingrrr! append_columnZszTable.append_columncCs||dS)aAppend a :class:`_schema.Constraint` to this :class:`_schema.Table`. This has the effect of the constraint being included in any future CREATE TABLE statement, assuming specific DDL creation events have not been associated with the given :class:`_schema.Constraint` object. Note that this does **not** produce the constraint within the relational database automatically, for a table that already exists in the database. To add a constraint to an existing relational database table, the SQL ALTER command must be used. SQLAlchemy also provides the :class:`.AddConstraint` construct which can produce this SQL when invoked as an executable clause. Nr)r6rrrr!append_constraintxszTable.append_constraintcKs||j|j|||_dSr#)r_rr re)r6rer8rrr! _set_parentszTable._set_parentrMzThe :meth:`_schema.Table.exists` method is deprecated and will be removed in a future release. Please refer to :meth:`_reflection.Inspector.has_table`.cCs,|dkrt|}t|}|j|j|jdS)z!Return True if this table exists.Nr)r rrZ has_tablerr )r6rrrrr!existss  z Table.existscCs&|dkrt|}|jtj||ddS)a-Issue a ``CREATE`` statement for this :class:`_schema.Table`, using the given :class:`.Connectable` for connectivity. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. .. seealso:: :meth:`_schema.MetaData.create_all`. N checkfirstr _run_ddl_visitorrZSchemaGeneratorr6rrrrr!createsz Table.createcCs&|dkrt|}|jtj||ddS)a)Issue a ``DROP`` statement for this :class:`_schema.Table`, using the given :class:`.Connectable` for connectivity. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. .. seealso:: :meth:`_schema.MetaData.drop_all`. Nrr rrZ SchemaDropperrrrr!drops z Table.dropzP:meth:`_schema.Table.tometadata` is renamed to :meth:`_schema.Table.to_metadata`cCs|j||||dS)zReturn a copy of this :class:`_schema.Table` associated with a different :class:`_schema.MetaData`. See :meth:`_schema.Table.to_metadata` for a full description. )r referred_schema_fnr) to_metadata)r6rer rrrrr! tometadatas zTable.tometadatac sn|dkrj}|tkrj}n|dkr,|j}t||}||jkrZtdj|j|Sg}jD]}| |j |dqdt ||f||j dj jD]t}t|tr|j}|r||||} n|jkr|nd} |j | dq|js|jrq|j |dqjD]D} | jr.qt| jffdd| jD| jd| j qS) al Return a copy of this :class:`_schema.Table` associated with a different :class:`_schema.MetaData`. E.g.:: m1 = MetaData() user = Table('user', m1, Column('id', Integer, primary_key=True)) m2 = MetaData() user_copy = user.to_metadata(m2) .. versionchanged:: 1.4 The :meth:`_schema.Table.to_metadata` function was renamed from :meth:`_schema.Table.tometadata`. :param metadata: Target :class:`_schema.MetaData` object, into which the new :class:`_schema.Table` object will be created. :param schema: optional string name indicating the target schema. Defaults to the special symbol :attr:`.RETAIN_SCHEMA` which indicates that no change to the schema name should be made in the new :class:`_schema.Table`. If set to a string name, the new :class:`_schema.Table` will have this new name as the ``.schema``. If set to ``None``, the schema will be set to that of the schema set on the target :class:`_schema.MetaData`, which is typically ``None`` as well, unless set explicitly:: m2 = MetaData(schema='newschema') # user_copy_one will have "newschema" as the schema name user_copy_one = user.to_metadata(m2, schema=None) m3 = MetaData() # schema defaults to None # user_copy_two will have None as the schema name user_copy_two = user.to_metadata(m3, schema=None) :param referred_schema_fn: optional callable which can be supplied in order to provide for the schema name that should be assigned to the referenced table of a :class:`_schema.ForeignKeyConstraint`. The callable accepts this parent :class:`_schema.Table`, the target schema that we are changing to, the :class:`_schema.ForeignKeyConstraint` object, and the existing "target schema" of that constraint. The function should return the string schema name that should be applied. E.g.:: def referred_schema_fn(table, to_schema, constraint, referred_schema): if referred_schema == 'base_tables': return referred_schema else: return to_schema new_table = table.to_metadata(m2, schema="alt_schema", referred_schema_fn=referred_schema_fn) .. versionadded:: 0.9.2 :param name: optional string name indicating the target table name. If not specified or None, the table name is retained. This allows a :class:`_schema.Table` to be copied to the same :class:`_schema.MetaData` target with a new name. .. versionadded:: 1.0.0 NzBTable '%s' already exists within the given MetaData - not copying.r)r rrr r,csg|]}t|qSr)r.rexprrrr!rdsz%Table.to_metadata..)unique_table)r RETAIN_SCHEMAr r"r[rwarnrrappend_copyrKrrrryr$ForeignKeyConstraint_referred_schemar _type_bound _column_flagrxIndex expressionsrrD) r6rer rrr'r7r(Zreferred_schemaZfk_constraint_schemaindexrrr!rsO           zTable.to_metadata)rTN)F)N)NF)NF)*rErFrGrHrIryrxrZ_traverse_internalsrZ dp_stringrLrdeprecated_paramsrUrgr`rpropertyrrr^rrrrr'r?rrrrrr deprecatedrrrrrr __classcell__rrrr!rKsxG  6 N   9       rKcseZdZdZdZdZfddZdZdZdZ ddZ d d Z d d Z d dZ ddZd ddZddZddZeddddZddZd!ddZZS)"r%z(Represents a column in a database table.rTcsT|dd}|dd}t|}|rPt|dtjrP|dk rFtd|d}|r|d}t|dr|dk rxtd|d}|dk rt||dd}nd|krtd t t | |||d ||_ |d d |_ }|d t|_}|tk r||_n| |_|dd|_|dd|_|dd|_|dd|_|dd|_|dd |_|dd|_|dd|_|dd|_t|_t|_|dd|_d|_d|_d|kr|d|_ nt|j!t"r|j!#||jdk rZt|jt$t%fr|&|jnFt'|j!dd rJt|jtj(rJt)d|j |jf|&t$|j|jdk rt|jt*r|&|j+d n|&t,|j|jdk rt|jt$t%fr|&|jn|&t$|jdd|jdk rt|jt*r|&|j+dn|&t,|jdd|j-|t.|d|krD|d|_/|j0f|dS)aJ Construct a new ``Column`` object. :param name: The name of this column as represented in the database. This argument may be the first positional argument, or specified via keyword. Names which contain no upper case characters will be treated as case insensitive names, and will not be quoted unless they are a reserved word. Names with any number of upper case characters will be quoted and sent exactly. Note that this behavior applies even for databases which standardize upper case names as case insensitive such as Oracle. The name field may be omitted at construction time and applied later, at any time before the Column is associated with a :class:`_schema.Table`. This is to support convenient usage within the :mod:`~sqlalchemy.ext.declarative` extension. :param type\_: The column's type, indicated using an instance which subclasses :class:`~sqlalchemy.types.TypeEngine`. If no arguments are required for the type, the class of the type can be sent as well, e.g.:: # use a type with arguments Column('data', String(50)) # use no arguments Column('level', Integer) The ``type`` argument may be the second positional argument or specified by keyword. If the ``type`` is ``None`` or is omitted, it will first default to the special type :class:`.NullType`. If and when this :class:`_schema.Column` is made to refer to another column using :class:`_schema.ForeignKey` and/or :class:`_schema.ForeignKeyConstraint`, the type of the remote-referenced column will be copied to this column as well, at the moment that the foreign key is resolved against that remote :class:`_schema.Column` object. .. versionchanged:: 0.9.0 Support for propagation of type to a :class:`_schema.Column` from its :class:`_schema.ForeignKey` object has been improved and should be more reliable and timely. :param \*args: Additional positional arguments include various :class:`.SchemaItem` derived constructs which will be applied as options to the column. These include instances of :class:`.Constraint`, :class:`_schema.ForeignKey`, :class:`.ColumnDefault`, :class:`.Sequence`, :class:`.Computed` :class:`.Identity`. In some cases an equivalent keyword argument is available such as ``server_default``, ``default`` and ``unique``. :param autoincrement: Set up "auto increment" semantics for an integer primary key column. The default value is the string ``"auto"`` which indicates that a single-column primary key that is of an INTEGER type with no stated client-side or python-side defaults should receive auto increment semantics automatically; all other varieties of primary key columns will not. This includes that :term:`DDL` such as PostgreSQL SERIAL or MySQL AUTO_INCREMENT will be emitted for this column during a table create, as well as that the column is assumed to generate new integer primary key values when an INSERT statement invokes which will be retrieved by the dialect. When used in conjunction with :class:`.Identity` on a dialect that supports it, this parameter has no effect. The flag may be set to ``True`` to indicate that a column which is part of a composite (e.g. multi-column) primary key should have autoincrement semantics, though note that only one column within a primary key may have this setting. It can also be set to ``True`` to indicate autoincrement semantics on a column that has a client-side or server-side default configured, however note that not all dialects can accommodate all styles of default as an "autoincrement". It can also be set to ``False`` on a single-column primary key that has a datatype of INTEGER in order to disable auto increment semantics for that column. .. versionchanged:: 1.1 The autoincrement flag now defaults to ``"auto"`` which indicates autoincrement semantics by default for single-column integer primary keys only; for composite (multi-column) primary keys, autoincrement is never implicitly enabled; as always, ``autoincrement=True`` will allow for at most one of those columns to be an "autoincrement" column. ``autoincrement=True`` may also be set on a :class:`_schema.Column` that has an explicit client-side or server-side default, subject to limitations of the backend database and dialect. The setting *only* has an effect for columns which are: * Integer derived (i.e. INT, SMALLINT, BIGINT). * Part of the primary key * Not referring to another column via :class:`_schema.ForeignKey`, unless the value is specified as ``'ignore_fk'``:: # turn on autoincrement for this column despite # the ForeignKey() Column('id', ForeignKey('other.id'), primary_key=True, autoincrement='ignore_fk') It is typically not desirable to have "autoincrement" enabled on a column that refers to another via foreign key, as such a column is required to refer to a value that originates from elsewhere. The setting has these two effects on columns that meet the above criteria: * DDL issued for the column will include database-specific keywords intended to signify this column as an "autoincrement" column, such as AUTO INCREMENT on MySQL, SERIAL on PostgreSQL, and IDENTITY on MS-SQL. It does *not* issue AUTOINCREMENT for SQLite since this is a special SQLite flag that is not required for autoincrementing behavior. .. seealso:: :ref:`sqlite_autoincrement` * The column will be considered to be available using an "autoincrement" method specific to the backend database, such as calling upon ``cursor.lastrowid``, using RETURNING in an INSERT statement to get at a sequence-generated value, or using special functions such as "SELECT scope_identity()". These methods are highly specific to the DBAPIs and databases in use and vary greatly, so care should be taken when associating ``autoincrement=True`` with a custom default generation function. :param default: A scalar, Python callable, or :class:`_expression.ColumnElement` expression representing the *default value* for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert. This is a shortcut to using :class:`.ColumnDefault` as a positional argument; see that class for full detail on the structure of the argument. Contrast this argument to :paramref:`_schema.Column.server_default` which creates a default generator on the database side. .. seealso:: :ref:`metadata_defaults_toplevel` :param doc: optional String that can be used by the ORM or similar to document attributes on the Python side. This attribute does **not** render SQL comments; use the :paramref:`_schema.Column.comment` parameter for this purpose. :param key: An optional string identifier which will identify this ``Column`` object on the :class:`_schema.Table`. When a key is provided, this is the only identifier referencing the ``Column`` within the application, including ORM attribute mapping; the ``name`` field is used only when rendering SQL. :param index: When ``True``, indicates that a :class:`_schema.Index` construct will be automatically generated for this :class:`_schema.Column`, which will result in a "CREATE INDEX" statement being emitted for the :class:`_schema.Table` when the DDL create operation is invoked. Using this flag is equivalent to making use of the :class:`_schema.Index` construct explicitly at the level of the :class:`_schema.Table` construct itself:: Table( "some_table", metadata, Column("x", Integer), Index("ix_some_table_x", "x") ) To add the :paramref:`_schema.Index.unique` flag to the :class:`_schema.Index`, set both the :paramref:`_schema.Column.unique` and :paramref:`_schema.Column.index` flags to True simultaneously, which will have the effect of rendering the "CREATE UNIQUE INDEX" DDL instruction instead of "CREATE INDEX". The name of the index is generated using the :ref:`default naming convention ` which for the :class:`_schema.Index` construct is of the form ``ix__``. As this flag is intended only as a convenience for the common case of adding a single-column, default configured index to a table definition, explicit use of the :class:`_schema.Index` construct should be preferred for most use cases, including composite indexes that encompass more than one column, indexes with SQL expressions or ordering, backend-specific index configuration options, and indexes that use a specific name. .. note:: the :attr:`_schema.Column.index` attribute on :class:`_schema.Column` **does not indicate** if this column is indexed or not, only if this flag was explicitly set here. To view indexes on a column, view the :attr:`_schema.Table.indexes` collection or use :meth:`_reflection.Inspector.get_indexes`. .. seealso:: :ref:`schema_indexes` :ref:`constraint_naming_conventions` :paramref:`_schema.Column.unique` :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. :param nullable: When set to ``False``, will cause the "NOT NULL" phrase to be added when generating DDL for the column. When ``True``, will normally generate nothing (in SQL this defaults to "NULL"), except in some very specific backend-specific edge cases where "NULL" may render explicitly. Defaults to ``True`` unless :paramref:`_schema.Column.primary_key` is also ``True`` or the column specifies a :class:`_sql.Identity`, in which case it defaults to ``False``. This parameter is only used when issuing CREATE TABLE statements. .. note:: When the column specifies a :class:`_sql.Identity` this parameter is in general ignored by the DDL compiler. The PostgreSQL database allows nullable identity column by setting this parameter to ``True`` explicitly. :param onupdate: A scalar, Python callable, or :class:`~sqlalchemy.sql.expression.ClauseElement` representing a default value to be applied to the column within UPDATE statements, which will be invoked upon update if this column is not present in the SET clause of the update. This is a shortcut to using :class:`.ColumnDefault` as a positional argument with ``for_update=True``. .. seealso:: :ref:`metadata_defaults` - complete discussion of onupdate :param primary_key: If ``True``, marks this column as a primary key column. Multiple columns can have this flag set to specify composite primary keys. As an alternative, the primary key of a :class:`_schema.Table` can be specified via an explicit :class:`.PrimaryKeyConstraint` object. :param server_default: A :class:`.FetchedValue` instance, str, Unicode or :func:`~sqlalchemy.sql.expression.text` construct representing the DDL DEFAULT value for the column. String types will be emitted as-is, surrounded by single quotes:: Column('x', Text, server_default="val") x TEXT DEFAULT 'val' A :func:`~sqlalchemy.sql.expression.text` expression will be rendered as-is, without quotes:: Column('y', DateTime, server_default=text('NOW()')) y DATETIME DEFAULT NOW() Strings and text() will be converted into a :class:`.DefaultClause` object upon initialization. Use :class:`.FetchedValue` to indicate that an already-existing column will generate a default value on the database side which will be available to SQLAlchemy for post-fetch after inserts. This construct does not specify any DDL and the implementation is left to the database, such as via a trigger. .. seealso:: :ref:`server_defaults` - complete discussion of server side defaults :param server_onupdate: A :class:`.FetchedValue` instance representing a database-side default generation function, such as a trigger. This indicates to SQLAlchemy that a newly generated value will be available after updates. This construct does not actually implement any kind of generation function within the database, which instead must be specified separately. .. warning:: This directive **does not** currently produce MySQL's "ON UPDATE CURRENT_TIMESTAMP()" clause. See :ref:`mysql_timestamp_onupdate` for background on how to produce this clause. .. seealso:: :ref:`triggered_columns` :param quote: Force quoting of this column's name on or off, corresponding to ``True`` or ``False``. When left at its default of ``None``, the column identifier will be quoted according to whether the name is case sensitive (identifiers with at least one upper case character are treated as case sensitive), or if it's a reserved word. This flag is only needed to force quoting of a reserved word which is not known by the SQLAlchemy dialect. :param unique: When ``True``, and the :paramref:`_schema.Column.index` parameter is left at its default value of ``False``, indicates that a :class:`_schema.UniqueConstraint` construct will be automatically generated for this :class:`_schema.Column`, which will result in a "UNIQUE CONSTRAINT" clause referring to this column being included in the ``CREATE TABLE`` statement emitted, when the DDL create operation for the :class:`_schema.Table` object is invoked. When this flag is ``True`` while the :paramref:`_schema.Column.index` parameter is simultaneously set to ``True``, the effect instead is that a :class:`_schema.Index` construct which includes the :paramref:`_schema.Index.unique` parameter set to ``True`` is generated. See the documentation for :paramref:`_schema.Column.index` for additional detail. Using this flag is equivalent to making use of the :class:`_schema.UniqueConstraint` construct explicitly at the level of the :class:`_schema.Table` construct itself:: Table( "some_table", metadata, Column("x", Integer), UniqueConstraint("x") ) The :paramref:`_schema.UniqueConstraint.name` parameter of the unique constraint object is left at its default value of ``None``; in the absence of a :ref:`naming convention ` for the enclosing :class:`_schema.MetaData`, the UNIQUE CONSTRAINT construct will be emitted as unnamed, which typically invokes a database-specific naming convention to take place. As this flag is intended only as a convenience for the common case of adding a single-column, default configured unique constraint to a table definition, explicit use of the :class:`_schema.UniqueConstraint` construct should be preferred for most use cases, including composite constraints that encompass more than one column, backend-specific index configuration options, and constraints that use a specific name. .. note:: the :attr:`_schema.Column.unique` attribute on :class:`_schema.Column` **does not indicate** if this column has a unique constraint or not, only if this flag was explicitly set here. To view indexes and unique constraints that may involve this column, view the :attr:`_schema.Table.indexes` and/or :attr:`_schema.Table.constraints` collections or use :meth:`_reflection.Inspector.get_indexes` and/or :meth:`_reflection.Inspector.get_unique_constraints` .. seealso:: :ref:`schema_unique_constraint` :ref:`constraint_naming_conventions` :paramref:`_schema.Column.index` :param system: When ``True``, indicates this is a "system" column, that is a column which is automatically made available by the database, and should not be included in the columns list for a ``CREATE TABLE`` statement. For more elaborate scenarios where columns should be conditionally rendered differently on different backends, consider custom compilation rules for :class:`.CreateColumn`. :param comment: Optional string that will render an SQL comment on table creation. .. versionadded:: 1.2 Added the :paramref:`_schema.Column.comment` parameter to :class:`_schema.Column`. rNtype_rz0May not pass name positionally and as a keyword.Z _sqla_typez1May not pass type_ positionally and as a keyword.rhz9Explicit 'name' is required when sending 'quote' argumentr'rFnullabler1server_defaultserver_onupdaterrsystemdoconupdate autoincrementautorr_proxiesZ_warn_on_bytestringz?Unicode column '%s' has non-unicode default value %r specified.T for_updater<)1rZlistr$r string_typesrr5hasattrrrvr%rgr'rr_user_defined_nullablerr1rrrrrrrrrwryr{rrcomputedidentityrtyper r2 ColumnDefaultSequencerr binary_typer FetchedValue_as_for_update DefaultClauser;set_creation_orderr<r)r6r7rrrZcoltyperZudnrrr!rgus                   zColumn.__init__NcKs||dSr#rrrrr!rszColumn._extra_kwargscCsD|jdkrdS|jdk r:|jjr2|jjd|jS|jSn|jSdS)Nz (no name)r)rr&Znamed_with_columnrr>rrr!rs  zColumn.__str__cCs&|jD]}|jj|jrdSqdS)zOReturn True if this Column references the given column via foreign key.TFN)r{rZ proxy_set intersectionr6rfkrrr! referencess zColumn.referencescCs||dSr#r)r6rrrr!append_foreign_keyszColumn.append_foreign_keycsg}jjkr|djr*|djs:|djrJ|djrZ|djrj|djrz|ddd t jgt j gd d j Dd d j Djdk rd jjpdgfdd |DS)Nr'rrrr1rrrz Column(%s)rcSsg|]}|dk rt|qSr#rrrrr!rsz#Column.__repr__..cSsg|] }t|qSrrrrrr!rsz table=<%s>z table=Nonecs"g|]}d|tt|fqSrrrr>rr!rs)r'rrrrrr1rrrrrrr{ryr&r)r6kwargrr>r!r?s@             zColumn.__repr__cs|jstd||jdkr*|j|_t|dd}|dk r\|k r\td|j|jf|jjkr̈j|j}||k r|st d|jjfd|j D]*}j ||j jkrj |j qj||_|jrj|n$|jjkrtd|jjf|jrXt|jt jr8tdtd|jt|jdd n6|jrt|jt jrztd t|jdd |fd d |jrt|jtst|j trtddS)NzfColumn must be constructed with a non-blank name or assign a non-blank .name before adding to a Table.r&z1Column object '%s' already assigned to Table '%s'zA column with name '%s' is already present in table '%s'. Please use method :meth:`_schema.Table.append_column` with the parameter ``replace_existing=True`` to replace an existing column.rMzTTrying to redefine primary-key column '%s' as a non-primary-key column on table '%s'zThe 'index' keyword argument on Column is boolean only. To create indexes with a specific name, create an explicit Index object external to the Table.T)rrzThe 'unique' keyword argument on Column is boolean only. To create unique constraints or indexes with a specific name, append an explicit UniqueConstraint to the Table's list of elements, or create an explicit Index object external to the Table.)rcs |Sr#)_set_remote_tablerr&rr!rrz$Column._set_parent..z4An column cannot specify both Identity and Sequence.)!rrr5Z_reset_memoizationsr'rrrrXrZwarn_deprecatedr{rrryr-r&r_replacer}rr$rrrr\rUniqueConstraint_setup_on_memoized_fksrr1rr)r6r&ruexistingr)rrrr!rs             zColumn._set_parentcCsj|jj|jfdf|jj|jfdfg}|D]<\}}||jjjkr(|jjj|D]}|j|krL||qLq(dS)NFT)r&r'rre _fk_memos link_to_name)r6rZfk_keysfk_keyrrrrr!r's  zColumn._setup_on_memoized_fkscCs*|jdk r|||jnt|d|dS)Nra)r&rr~)r6rrrr!_on_table_attach2s zColumn._on_table_attachrMz]The :meth:`_schema.Column.copy` method is deprecated and will be removed in a future release.cKs |jf|Sr#rr6r8rrr!rA8sz Column.copyc  sfdd|jDfdd|jD}i}|jD]2}|j|j}|D]\}}|||d|<qJq2|j}|j} t|tt frd}} | |jj f|j } t| t r| jf} |jtk r|j|d<|j||j| |j|j|j|j|j|j|j||j| |j|jd|} || S)zvCreate a copy of this ``Column``, uninitialized. This is used in :meth:`_schema.Table.to_metadata`. csg|]}|js|jfqSr)rrrr8rr!rHsz Column._copy..csg|]}|js|jfqSr)rrrrrr!rJs_Nr)rrr'rrrrrr1rrrrrr)ryr{dialect_options _non_defaultsitemsrrr$ComputedIdentityrrrr rArr _constructorrr'rrrrrr1rrrrrD) r6r8r7Z column_kwargs dialect_namer dialect_option_keydialect_option_valuerrrr(rrr!r@s\        z Column._copyFc Ks dd|jD}|dkr,|jdkr,tdz^|j|rNttj|rF|n|jn|pV|j|j f||rh|n |rp|n|j |j |j |gd}Wn:t k r}ztjt d|j|dW5d}~XYnX||_|j|_|jdk r|jj|j |_|j r|j ||r|j||j |fS)a$Create a *proxy* for this column. This is a copy of this ``Column`` referenced by a different parent (such as an alias or select statement). The column should be used only in select scenarios, as its full DDL/default information is not transferred. cSsg|]}t|j|jdqS)) _constraint) ForeignKeyrr)rfrrr!rsz&Column._make_proxy..Nz^Cannot initialize a sub-selectable with this Column object until its 'name' has been assigned.)r'rrrzCould not create a copy of this %r object. Ensure the class includes a _constructor() attribute or method which accepts the standard Column constructor arguments, or references the Column class itself.from_)r{rrr]rrexpectrZTruncatedLabelRolerr'rrrWrr4rr&Z_propagate_attrsZ _is_clone_ofrrXrupdate) r6 selectablerr'Zname_is_truncatabler8rr(r:rrr! _make_proxyzsT        zColumn._make_proxy)T)NNF)rErFrGrHrIZ inherit_cachergr{rrrrrrr?rrrrrrArrrrrrr!r%ns8 |     X  ;r%c @seZdZdZdZd+ddZddZed d d,d d Z d-d dZ d.ddZ e ddZ ddZe e ZddZddZejddZddZddZdd Zejd!d"Zd#d$Zd%d&Zd'd(Zd)d*ZdS)/ra;Defines a dependency between two columns. ``ForeignKey`` is specified as an argument to a :class:`_schema.Column` object, e.g.:: t = Table("remote_table", metadata, Column("remote_id", ForeignKey("main_table.id")) ) Note that ``ForeignKey`` is only a marker object that defines a dependency between two columns. The actual constraint is in all cases represented by the :class:`_schema.ForeignKeyConstraint` object. This object will be generated automatically when a ``ForeignKey`` is associated with a :class:`_schema.Column` which in turn is associated with a :class:`_schema.Table`. Conversely, when :class:`_schema.ForeignKeyConstraint` is applied to a :class:`_schema.Table`, ``ForeignKey`` markers are automatically generated to be present on each associated :class:`_schema.Column`, which are also associated with the constraint object. Note that you cannot define a "composite" foreign key constraint, that is a constraint between a grouping of multiple parent/child columns, using ``ForeignKey`` objects. To define this grouping, the :class:`_schema.ForeignKeyConstraint` object must be used, and applied to the :class:`_schema.Table`. The associated ``ForeignKey`` objects are created automatically. The ``ForeignKey`` objects associated with an individual :class:`_schema.Column` object are available in the `foreign_keys` collection of that column. Further examples of foreign key configuration are in :ref:`metadata_foreignkeys`. Z foreign_keyNFc Ksttj||_t|jtjr&d|_n.|j|_t|jj tj t fsTt d|jj ||_d|_||_||_||_||_||_||_| |_| |_| r| |_| |_dS)a Construct a column-level FOREIGN KEY. The :class:`_schema.ForeignKey` object when constructed generates a :class:`_schema.ForeignKeyConstraint` which is associated with the parent :class:`_schema.Table` object's collection of constraints. :param column: A single target column for the key relationship. A :class:`_schema.Column` object or a column name as a string: ``tablename.columnkey`` or ``schema.tablename.columnkey``. ``columnkey`` is the ``key`` which has been assigned to the column (defaults to the column name itself), unless ``link_to_name`` is ``True`` in which case the rendered name of the column is used. :param name: Optional string. An in-database name for the key if `constraint` is not provided. :param onupdate: Optional string. If set, emit ON UPDATE when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param ondelete: Optional string. If set, emit ON DELETE when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY when issuing DDL for this constraint. :param link_to_name: if True, the string name given in ``column`` is the rendered name of the referenced column, not its locally assigned ``key``. :param use_alter: passed to the underlying :class:`_schema.ForeignKeyConstraint` to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE statement. See :paramref:`_schema.ForeignKeyConstraint.use_alter` for further description. .. seealso:: :paramref:`_schema.ForeignKeyConstraint.use_alter` :ref:`use_alter` :param match: Optional string. If set, emit MATCH when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param \**dialect_kw: Additional keyword arguments are dialect specific, and passed in the form ``_``. The arguments are ultimately handled by a corresponding :class:`_schema.ForeignKeyConstraint`. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. .. versionadded:: 0.9.2 Nz8ForeignKey received Column not bound to a Table, got: %r)rrrZDDLReferredColumnRole_colspecr$rr _table_columnr&ZNoneTyperrr5rparent use_alterrrondelete deferrable initiallyrmatchr<_unvalidated_dialect_kw) r6rrrrrr r!r"rr#r< dialect_kwrrr!rgs4U zForeignKey.__init__cCs d|S)NzForeignKey(%r)) _get_colspecr>rrr!r?VszForeignKey.__repr__rMzaThe :meth:`_schema.ForeignKey.copy` method is deprecated and will be removed in a future release.cKs|jfd|i|S)Nr r)r6r r8rrr!rAYszForeignKey.copyc KsFt|j|df|j|j|j|j|j|j|j|j d|j }| |S)aProduce a copy of this :class:`_schema.ForeignKey` object. The new :class:`_schema.ForeignKey` will not be bound to any :class:`_schema.Column`. This method is usually used by the internal copy procedures of :class:`_schema.Column`, :class:`_schema.Table`, and :class:`_schema.MetaData`. :param schema: The returned :class:`_schema.ForeignKey` will reference the original table and column name, qualified by the given string schema name. r)rrrr r!r"rr#) rr&rrrr r!r"rr#r$rD)r6r r8rrrr!ras   zForeignKey._copycCs|r*|j\}}}|dk r|}d|||fS|rZ|j\}}}|rLd|||fSd||fSn&|jdk rzd|jjj|jjfS|jSdS)zReturn a string based 'column specification' for this :class:`_schema.ForeignKey`. This is usually the equivalent of the string-based "tablename.colname" argument first passed to the object's constructor. Nz%s.%s.%srk)_column_tokensrr&r}r'r)r6r table_nameZ_schematnamecolnamerrr!r&s    zForeignKey._get_colspeccCs |jdS)Nr)r'r>rrr!rszForeignKey._referred_schemacCs@|jdk r&|jjdkrdS|jjjSn|j\}}}t||SdSr#)rr&r'r'r")r6r r)r*rrr! _table_keys     zForeignKey._table_keycCs||jdk S)zrReturn True if the given :class:`_schema.Table` is referenced by this :class:`_schema.ForeignKey`.NZcorresponding_columnrrrrr!rszForeignKey.referencescCs ||jS)aReturn the :class:`_schema.Column` in the given :class:`_schema.Table` referenced by this :class:`_schema.ForeignKey`. Returns None if this :class:`_schema.ForeignKey` does not reference the given :class:`_schema.Table`. r,rrrr! get_referents zForeignKey.get_referentcCsv|d}|dkr&td|jt|dkr@|}d}n|}|}t|dkrhd|}nd}|||fS)z7parse a string-based _colspec into its component parts.rNz,Invalid foreign key column specification: %srr)r&splitrr5rlenrZr)r6mr)r*r rrr!r's   zForeignKey._column_tokenscCs|jdkrtdn|jjdkr,td|jj}|jjD] }t|tr<|j|ksXtqfq.set_type) r$rr&rKr1rr;rr)r6rr=rr<r!r8# s     zForeignKey._set_target_columncCst|jtjr||\}}}||jkr@td|j||f|q|j |jkr\t d|qt d|j|j ||f||n$t |jdr|j}|S|j}|SdS)aReturn the target :class:`_schema.Column` referenced by this :class:`_schema.ForeignKey`. If no target column has been established, an exception is raised. .. versionchanged:: 0.9.0 Foreign key target column resolution now occurs as soon as both the ForeignKey object and the remote Column to which it refers are both associated with the same MetaData object. z|Foreign key associated with column '%s' could not find table '%s' with which to generate a foreign key to target column '%s'z9Table %s is no longer associated with its parent MetaDatar6__clause_element__N)r$rrrr4rerZNoReferencedTableErrorrr'r]r7rrr>)r6r2r3r*r9rrr!r5 s6     zForeignKey.columncKsD|jdk r|j|k rtd||_|jj||j|jdS)Nz&This ForeignKey already has a parent !)rrr]r{rr _set_tabler6rr8rrr!re szForeignKey._set_parentcCs,|\}}}|||||j|dSr#)r4r:r_validate_dest_table)r6r&r2r3r*rrr!rn szForeignKey._set_remote_tablecCs8|\}}}||f}||j|kr4|j||dSr#)r4rr)r6rer2 table_keyr*rrrr!_remove_from_metadatas sz ForeignKey._remove_from_metadatac Cs$t|tst|jdkrftggf|j|j|j|j|j |j |j d|j |_|j |||j||j|t|jtjr|\}}}||f}||jjkr|jj|}z||||Wntjk rYnX|jj||n4t|jdr|j}||n|j}||dS)N)rrrr r!r"r#r>)r$rKr1rrrrrr r!r"r#r$_append_elementr2r{rrrrr4rer[r:rr7rrrr>r8)r6rr&r2rBr*rr9rrr!r?{ sD         zForeignKey._set_table) NFNNNNNFNN)N)N)NN)rErFrGrHrIrgr?rrrArr&rrr+Ztarget_fullnamerr-rJr'r4r:r8rrrrCr?rrrr!rsL' w       ## / rc@s^eZdZdZdZdZdZdZdddZddZ e j d d d dd d Z ddZ eddZdS)DefaultGeneratorz'Base class for column *default* values.Zdefault_generatorFNcCs ||_dSr#rr6rrrr!rg szDefaultGenerator.__init__cKs"||_|jr||j_n||j_dSr#)rrrr1r@rrr!r s zDefaultGenerator._set_parentz!:meth:`.DefaultGenerator.execute`zAll statement execution in SQLAlchemy 2.0 is performed by the :meth:`_engine.Connection.execute` method of :class:`_engine.Connection`, or in the ORM by the :meth:`.Session.execute` method of :class:`.Session`.) alternativecCs |dkrt|}||dtjS)Nr)r _execute_defaultr EMPTY_DICT)r6rrrr!execute s zDefaultGenerator.executecCs|||||Sr#)rH)r6 connectionZ multiparamsparamsZexecution_optionsrrr!_execute_on_connection s z'DefaultGenerator._execute_on_connectioncCs"t|dddk r|jjjSdSdS)z4Return the connectable associated with this default.rN)rrr&rr>rrr!r s zDefaultGenerator.bind)F)N)rErFrGrHrI is_sequenceis_server_defaultrrgrrZ deprecated_20rJrMrrrrrr!rE s  rEcsreZdZdZfddZejddZejddZejdd Z eje d d d Z d dZ ddZ ZS)raA plain default value on a column. This could correspond to a constant, a callable function, or a SQL clause. :class:`.ColumnDefault` is generated automatically whenever the ``default``, ``onupdate`` arguments of :class:`_schema.Column` are used. A :class:`.ColumnDefault` can be passed positionally as well. For example, the following:: Column('foo', Integer, default=50) Is equivalent to:: Column('foo', Integer, ColumnDefault(50)) c sBtt|jf|t|tr&tdt|r8||}||_ dS)a{Construct a new :class:`.ColumnDefault`. :param arg: argument representing the default value. May be one of the following: * a plain non-callable Python value, such as a string, integer, boolean, or other simple type. The default value will be used as is each time. * a SQL expression, that is one which derives from :class:`_expression.ColumnElement`. The SQL expression will be rendered into the INSERT or UPDATE statement, or in the case of a primary key column when RETURNING is not used may be pre-executed before an INSERT within a SELECT. * A Python callable. The function will be invoked for each new row subject to an INSERT or UPDATE. The callable must accept exactly zero or one positional arguments. The one-argument form will receive an instance of the :class:`.ExecutionContext`, which provides contextual information as to the current :class:`_engine.Connection` in use as well as the current statement and parameters. z4ColumnDefault may not be a server-side default type.N) rvrrgr$rrr5callable_maybe_wrap_callablearg)r6rRrrrr!rg s  zColumnDefault.__init__cCs t|jSr#)rPrRr>rrr! is_callable szColumnDefault.is_callablecCs t|jtSr#)r$rRrr>rrr!is_clause_element szColumnDefault.is_clause_elementcCs|j o|j o|j Sr#)rSrTrNr>rrr! is_scalar s zColumnDefault.is_scalarzsqlalchemy.sql.sqltypescCs(tjj}|jr t|jj|j SdSdSNF)r preloadedZ sql_sqltypesrTr$rRrZNullType)r6Zsqltypesrrr! _arg_is_typed szColumnDefault._arg_is_typedcsztjdd}Wn(tk r:tfddYSX|ddk rTt|dpVd}t|d|}|dkrtfddS|d krStd dS) zWrap callables that don't accept a context. This is to allow easy compatibility with default callables that aren't specific to accepting of a context. T)Zno_selfcsSr#rctxrrr!r1 rz4ColumnDefault._maybe_wrap_callable..NrcsSr#rrYr[rr!r7 rrzDColumnDefault Python function takes zero or one positional arguments)rZget_callable_argspecrWZ wrap_callabler/rr5)r6rZargspecZ defaultedZ positionalsrr[r!rQ' sz"ColumnDefault._maybe_wrap_callablecCs d|jfS)NzColumnDefault(%r))rRr>rrr!r?A szColumnDefault.__repr__)rErFrGrHrgrrJrSrTrUpreload_modulerXrQr?rrrrr!r s #    rc @seZdZdZdddZdS)IdentityOptionszDefines options for a named database sequence or an identity column. .. versionadded:: 1.3.18 .. seealso:: :class:`.Sequence` Nc Cs:||_||_||_||_||_||_||_||_| |_dS)a\Construct a :class:`.IdentityOptions` object. See the :class:`.Sequence` documentation for a complete description of the parameters. :param start: the starting index of the sequence. :param increment: the increment value of the sequence. :param minvalue: the minimum value of the sequence. :param maxvalue: the maximum value of the sequence. :param nominvalue: no minimum value of the sequence. :param nomaxvalue: no maximum value of the sequence. :param cycle: allows the sequence to wrap around when the maxvalue or minvalue has been reached. :param cache: optional integer value; number of future values in the sequence which are calculated in advance. :param order: optional boolean value; if ``True``, renders the ORDER keyword. N start incrementminvaluemaxvalue nominvalue nomaxvaluecyclecacheorder) r6r`rarbrcrdrerfrgrhrrr!rgP szIdentityOptions.__init__) NNNNNNNNN)rErFrGrHrgrrrr!r^E s r^cseZdZdZdZdZdddZejdd Z ejd d Z e d d dZ fddZ ddZddZeddZdddZdddZddZZS) ra Represents a named database sequence. The :class:`.Sequence` object represents the name and configurational parameters of a database sequence. It also represents a construct that can be "executed" by a SQLAlchemy :class:`_engine.Engine` or :class:`_engine.Connection`, rendering the appropriate "next value" function for the target database and returning a result. The :class:`.Sequence` is typically associated with a primary key column:: some_table = Table( 'some_table', metadata, Column('id', Integer, Sequence('some_table_seq'), primary_key=True) ) When CREATE TABLE is emitted for the above :class:`_schema.Table`, if the target platform supports sequences, a CREATE SEQUENCE statement will be emitted as well. For platforms that don't support sequences, the :class:`.Sequence` construct is ignored. .. seealso:: :ref:`defaults_sequences` :class:`.CreateSequence` :class:`.DropSequence` sequenceTNFc Cstj||dtj||||||||| | d t|||_| |_| tkrRd|_} n0|dk rv| dkrv|jrv|j|_} n t| ||_||_t || |_ |r| || dk rt | |_ nd|_ dS)a7Construct a :class:`.Sequence` object. :param name: the name of the sequence. :param start: the starting index of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "START WITH" clause. If ``None``, the clause is omitted, which on most platforms indicates a starting value of 1. :param increment: the increment value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "INCREMENT BY" clause. If ``None``, the clause is omitted, which on most platforms indicates an increment of 1. :param minvalue: the minimum value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "MINVALUE" clause. If ``None``, the clause is omitted, which on most platforms indicates a minvalue of 1 and -2^63-1 for ascending and descending sequences, respectively. .. versionadded:: 1.0.7 :param maxvalue: the maximum value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "MAXVALUE" clause. If ``None``, the clause is omitted, which on most platforms indicates a maxvalue of 2^63-1 and -1 for ascending and descending sequences, respectively. .. versionadded:: 1.0.7 :param nominvalue: no minimum value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "NO MINVALUE" clause. If ``None``, the clause is omitted, which on most platforms indicates a minvalue of 1 and -2^63-1 for ascending and descending sequences, respectively. .. versionadded:: 1.0.7 :param nomaxvalue: no maximum value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "NO MAXVALUE" clause. If ``None``, the clause is omitted, which on most platforms indicates a maxvalue of 2^63-1 and -1 for ascending and descending sequences, respectively. .. versionadded:: 1.0.7 :param cycle: allows the sequence to wrap around when the maxvalue or minvalue has been reached by an ascending or descending sequence respectively. This value is used when the CREATE SEQUENCE command is emitted to the database as the "CYCLE" clause. If the limit is reached, the next number generated will be the minvalue or maxvalue, respectively. If cycle=False (the default) any calls to nextval after the sequence has reached its maximum value will return an error. .. versionadded:: 1.0.7 :param schema: optional schema name for the sequence, if located in a schema other than the default. The rules for selecting the schema name when a :class:`_schema.MetaData` is also present are the same as that of :paramref:`_schema.Table.schema`. :param cache: optional integer value; number of future values in the sequence which are calculated in advance. Renders the CACHE keyword understood by Oracle and PostgreSQL. .. versionadded:: 1.1.12 :param order: optional boolean value; if ``True``, renders the ORDER keyword, understood by Oracle, indicating the sequence is definitively ordered. May be necessary to provide deterministic ordering using Oracle RAC. .. versionadded:: 1.1.12 :param data_type: The type to be returned by the sequence, for dialects that allow us to choose between INTEGER, BIGINT, etc. (e.g., mssql). .. versionadded:: 1.4.0 :param optional: boolean value, when ``True``, indicates that this :class:`.Sequence` object only needs to be explicitly generated on backends that don't provide another way to generate primary key identifiers. Currently, it essentially means, "don't create this sequence on the PostgreSQL backend, where the SERIAL keyword creates a sequence for us automatically". :param quote: boolean value, when ``True`` or ``False``, explicitly forces quoting of the :paramref:`_schema.Sequence.name` on or off. When left at its default of ``None``, normal quoting rules based on casing and reserved words take place. :param quote_schema: Set the quoting preferences for the ``schema`` name. :param metadata: optional :class:`_schema.MetaData` object which this :class:`.Sequence` will be associated with. A :class:`.Sequence` that is associated with a :class:`_schema.MetaData` gains the following capabilities: * The :class:`.Sequence` will inherit the :paramref:`_schema.MetaData.schema` parameter specified to the target :class:`_schema.MetaData`, which affects the production of CREATE / DROP DDL, if any. * The :meth:`.Sequence.create` and :meth:`.Sequence.drop` methods automatically use the engine bound to the :class:`_schema.MetaData` object, if any. * The :meth:`_schema.MetaData.create_all` and :meth:`_schema.MetaData.drop_all` methods will emit CREATE / DROP for this :class:`.Sequence`, even if the :class:`.Sequence` is not associated with any :class:`_schema.Table` / :class:`_schema.Column` that's a member of this :class:`_schema.MetaData`. The above behaviors can only occur if the :class:`.Sequence` is explicitly associated with the :class:`_schema.MetaData` via this parameter. .. seealso:: :ref:`sequence_metadata` - full discussion of the :paramref:`.Sequence.metadata` parameter. :param for_update: Indicates this :class:`.Sequence`, when associated with a :class:`_schema.Column`, should be invoked for UPDATE statements on that column's table, rather than for INSERT statements, when no value is otherwise present for that column in the statement. rr_N)rErgr^rroptionalrYr rer"_key _set_metadatar data_type)r6rr`rarbrcrdrerfr rgrhrmrjrhrerirrrr!rg s8      zSequence.__init__cCsdSrVrr>rrr!rS[ szSequence.is_callablecCsdSrVrr>rrr!rT_ szSequence.is_clause_elementzsqlalchemy.sql.functionscCs0|jrtjjjj||jdStjjj|SdS)zReturn a :class:`.next_value` function element which will render the appropriate increment function for this :class:`.Sequence` within any SQL expression. rN)rrrWZ sql_functionsfunc next_valuer>rrr!rpc s  zSequence.next_valuec s tt||||jdSr#)rvrrrr?r@rrr!rq szSequence._set_parentcCs||jdSr#)rlre)r6rr&rrr!r?u szSequence._set_tablecCs||_||jj|j<dSr#)re _sequencesrk)r6rerrr!rlx szSequence._set_metadatacCs|jr|jjSdSdSr#rr>rrr!r| sz Sequence.bindcCs&|dkrt|}|jtj||ddS)zCreates this sequence in the database. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. Nrrrrrr!r szSequence.createcCs&|dkrt|}|jtj||ddS)zDrops this sequence from the database. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. Nrrrrrr!r sz Sequence.dropcCstd|jjdS)NzThis %s cannot be used directly as a column expression. Use func.next_value(sequence) to produce a 'next value' function that's usable as a column element.)rr]rrEr>rrr!_not_a_column_expr s zSequence._not_a_column_expr)NNNNNNNNNNNFNNNF)NT)NT)rErFrGrHrIrNrgrrJrSrTr]rprr?rlrrrrrrrrrrr!rz sF  =     rc@sJeZdZdZdZdZdZdZdddZddZ dd Z d d Z d d Z dS)raA marker for a transparent database-side default. Use :class:`.FetchedValue` when the database is configured to provide some automatic default for a column. E.g.:: Column('foo', Integer, FetchedValue()) Would indicate that some trigger or default generator will create a new value for the ``foo`` column during an INSERT. .. seealso:: :ref:`triggered_columns` TFcCs ||_dSr#rrFrrr!rg szFetchedValue.__init__cCs||jkr|S||SdSr#)r_clonerFrrr!r s zFetchedValue._as_for_updatecCs4|j|j}|j|j|jdd||_|S)Nr)rrUr@rrZr)r6rnrrr!rs s zFetchedValue._clonecKs"||_|jr||j_n||j_dSr#)rrrrr@rrr!r s zFetchedValue._set_parentcCs t|Sr#r=r>rrr!r? szFetchedValue.__repr__N)F) rErFrGrHrO reflected has_argumentrTrgrrsrr?rrrr!r s rcs.eZdZdZdZdfdd ZddZZS) ra>A DDL-specified DEFAULT column value. :class:`.DefaultClause` is a :class:`.FetchedValue` that also generates a "DEFAULT" clause when "CREATE TABLE" is emitted. :class:`.DefaultClause` is generated automatically whenever the ``server_default``, ``server_onupdate`` arguments of :class:`_schema.Column` are used. A :class:`.DefaultClause` can be passed positionally as well. For example, the following:: Column('foo', Integer, server_default="50") Is equivalent to:: Column('foo', Integer, DefaultClause("50")) TFcs:t|tjdttfdtt||||_||_ dS)NrrR) rZassert_arg_typerrrrvrrgrRru)r6rRrZ _reflectedrrr!rg szDefaultClause.__init__cCsd|j|jfS)Nz DefaultClause(%r, for_update=%r))rRrr>rrr!r? szDefaultClause.__repr__)FF)rErFrGrHrvrgr?rrrrr!r src@sNeZdZdZdZdddZeddZd d Ze d d d dZ ddZ dS) ConstraintarA table-level SQL constraint. :class:`_schema.Constraint` serves as the base class for the series of constraint objects that can be associated with :class:`_schema.Table` objects, including :class:`_schema.PrimaryKeyConstraint`, :class:`_schema.ForeignKeyConstraint` :class:`_schema.UniqueConstraint`, and :class:`_schema.CheckConstraint`. rNFcKs@||_||_||_|r||_||_||_t|||dS)aVCreate a SQL constraint. :param name: Optional, the in-database name of this ``Constraint``. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY when issuing DDL for this constraint. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param \**dialect_kw: Additional keyword arguments are dialect specific, and passed in the form ``_``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. :param _create_rule: used internally by some datatypes that also create constraints. :param _type_bound: used internally to indicate that this constraint is associated with a specific datatype. N) rr!r"r< _create_rulerrrr)r6rr!r"rxr<rr%rrr!rg s* zConstraint.__init__cCs<zt|jtr|jWSWntk r,YnXtddS)NzdThis constraint is not bound to a table. Did you mean to call table.append_constraint(constraint) ?)r$rrKr3rr]r>rrr!r&? s  zConstraint.tablecKs||_|j|dSr#)rryrr6rr8rrr!rK szConstraint._set_parentrMzaThe :meth:`_schema.Constraint.copy` method is deprecated and will be removed in a future release.cKs |jf|Sr#rrrrr!rAO szConstraint.copycKs tdSr#)NotImplementedErrorrrrr!rW szConstraint._copy)NNNNNF) rErFrGrHrIrgrr&rrrrArrrrr!rw s$  4  rwc@s6eZdZdZdZddZd ddZddZd d ZdS) ColumnCollectionMixinNFc Os|dd}|dd|_t|_|dd}|dk rpg|_ttj|D]"\}}}}|j || |qJndd|D|_|r|jr| dS)N _autoattachTrF_gather_expressionscSsg|]}ttj|qSr)rrrDDLConstraintColumnRole)rrrrr!r{ sz2ColumnCollectionMixin.__init__..) rZrr r_pending_colargsrZ expect_col_expression_collectionrr~r _check_attach) r6rr8r|Zprocessed_expressionsrrZstrnameZ add_elementrrr!rgh s,    zColumnCollectionMixin.__init__c sddjD}dd|D}t||r|r.cSsg|]}t|jtr|qSr)r$r&rKrrrr!r s z#Should not reach here on event callcss|]}|dk r|VqdSr#rrrrr!r sz6ColumnCollectionMixin._check_attach..cs(t|tr$|s$jdddS)NT)r)r$rKdiscardr)rr&) cols_wo_tabler6rr! _col_attached s  z:ColumnCollectionMixin._check_attach.._col_attachedcSsh|] }|jqSrrrrrr! sz6ColumnCollectionMixin._check_attach..rrcsg|]}|jk r|qSrrrrrr!r s z(Column(s) %s are not part of table '%s'.rcss|]}d|VqdSz'%s'Nrrrrr!r s)rrw differencer1Z_cols_wo_tablerr/r2rZ_allow_multiple_tablesr&rr5rr) r6rZcol_objsZ cols_w_tableZhas_string_colsrr)rr[Zothersr)rr6r&r!r s>     z#ColumnCollectionMixin._check_attachcsfdd|jDS)Ncs&g|]}t|tjrj|n|qSr)r$rrr(rr)rrr!r sz:ColumnCollectionMixin._col_expressions..)rrrrr!_col_expressions s z&ColumnCollectionMixin._col_expressionscKs(||D]}|dk r |j|q dSr#)rrr)r6r&r8r)rrr!r sz!ColumnCollectionMixin._set_parent)F) rErFrGrrrgrrrrrrr!r{[ s   1r{c@sdeZdZdZddZdZddZddZe d d dd d Z dd dZ ddZ ddZ ddZdS)ColumnCollectionConstraintz-A constraint that proxies a ColumnCollection.cOsB|dd}|dd}tj|f|tj|f|||ddS)aZ :param \*columns: A sequence of column names or Column objects. :param name: Optional, the in-database name of this constraint. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY when issuing DDL for this constraint. :param \**kw: other keyword arguments including dialect-specific arguments are propagated to the :class:`.Constraint` superclass. r|TrF)r|rN)rZrwrgr{)r6rr8r|rrrr!rg s  z#ColumnCollectionConstraint.__init__NcKst||t||dSr#)rwrr{)r6r&r8rrr!r s z&ColumnCollectionConstraint._set_parentcCs ||jkSr#)r)r6rrrr! __contains__ sz'ColumnCollectionConstraint.__contains__rMzqThe :meth:`_schema.ColumnCollectionConstraint.copy` method is deprecated and will be removed in a future release.cKs|jfd|i|SNr,rr6r,r8rrr!rA szColumnCollectionConstraint.copyc  sxi}jD]2}j|j}|D]\}}|||d|<q"q jfddjDjjjd|}|S)Nr csg|]}t|jqSr)r.rrr6r,rr!r sz4ColumnCollectionConstraint._copy..)rr!r") r r r rrrr!r"rD) r6r,r8Zconstraint_kwargsrr rrr(rrr!r s,     z ColumnCollectionConstraint._copycCs |j|S)zReturn True if this constraint contains the given column. Note that this object also contains an attribute ``.columns`` which is a :class:`_expression.ColumnCollection` of :class:`_schema.Column` objects. )rcontains_columnr6r)rrr!r s z*ColumnCollectionConstraint.contains_columncCs t|jSr#)iterrr>rrr!__iter__ sz#ColumnCollectionConstraint.__iter__cCs t|jSr#)r/rr>rrr!__len__ sz"ColumnCollectionConstraint.__len__)N)N)rErFrGrHrgrrrrrrArrrrrrrr!r s   rc sbeZdZdZdZdZeddddfd d Zed d Z e d ddddZ dddZ ZS)CheckConstraintzlA table- or column-level CHECK constraint. Can be included in the definition of a Table or Column. TZ table_or_column_check_constraintsqltextz:class:`.CheckConstraint`z$:paramref:`.CheckConstraint.sqltext`NFc sfttj||_g} t|jid| jitt |j | |||||| |d| |dk rb| |dS)aConstruct a CHECK constraint. :param sqltext: A string containing the constraint definition, which will be used verbatim, or a SQL expression construct. If given as a string, the object is converted to a :func:`_expression.text` object. If the textual string includes a colon character, escape this using a backslash:: CheckConstraint(r"foo ~ E'a(?\:b|c)d") :param name: Optional, the in-database name of the constraint. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY when issuing DDL for this constraint. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 r)rr!r"rxr<rr|N) rrrDDLExpressionRolerrZtraverserrvrrgr2) r6rrr!r"r&r<rxr|rr8rrrr!rg( s"/   zCheckConstraint.__init__cCst|jt Sr#)r$rrKr>rrr!is_column_leveli szCheckConstraint.is_column_levelrMzfThe :meth:`_schema.CheckConstraint.copy` method is deprecated and will be removed in a future release.cKs|jfd|i|Srrrrrr!rAm szCheckConstraint.copyc KsL|dk rt|j|j|}n|j}t||j|j|j|j|d|jd}| |S)NF)rr"r!rxr&r|r) r.rr&rrr"r!rxrrD)r6r,r8rr(rrr!ru s zCheckConstraint._copy)NNNNNNTF)N)N)rErFrGrHrrIrrgrrrrrArrrrrr!r s2<  rc @seZdZdZdZdddZddZdZdZe d d Z e d d Z e d dZ ddZ e ddZe ddZddZedddddZdddZdS) raA table-level FOREIGN KEY constraint. Defines a single column or composite FOREIGN KEY ... REFERENCES constraint. For a no-frills, single column foreign key, adding a :class:`_schema.ForeignKey` to the definition of a :class:`_schema.Column` is a shorthand equivalent for an unnamed, single column :class:`_schema.ForeignKeyConstraint`. Examples of foreign key configuration are in :ref:`metadata_foreignkeys`. Zforeign_key_constraintNFc  stjf|||| d| |_|_| _|_| _tt|t|krxtt|t|krnt dn t dfdd|D_ t jf|| dk rt dr| jkst| dS)a- Construct a composite-capable FOREIGN KEY. :param columns: A sequence of local column names. The named columns must be defined and present in the parent Table. The names should match the ``key`` given to each column (defaults to the name) unless ``link_to_name`` is True. :param refcolumns: A sequence of foreign column names or Column objects. The columns must all be located within the same Table. :param name: Optional, the in-database name of the key. :param onupdate: Optional string. If set, emit ON UPDATE when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param ondelete: Optional string. If set, emit ON DELETE when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY when issuing DDL for this constraint. :param link_to_name: if True, the string name given in ``column`` is the rendered name of the referenced column, not its locally assigned ``key``. :param use_alter: If True, do not emit the DDL for this constraint as part of the CREATE TABLE definition. Instead, generate it via an ALTER TABLE statement issued after the full collection of tables have been created, and drop it via an ALTER TABLE statement before the full collection of tables are dropped. The use of :paramref:`_schema.ForeignKeyConstraint.use_alter` is particularly geared towards the case where two or more tables are established within a mutually-dependent foreign key constraint relationship; however, the :meth:`_schema.MetaData.create_all` and :meth:`_schema.MetaData.drop_all` methods will perform this resolution automatically, so the flag is normally not needed. .. versionchanged:: 1.0.0 Automatic resolution of foreign key cycles has been added, removing the need to use the :paramref:`_schema.ForeignKeyConstraint.use_alter` in typical use cases. .. seealso:: :ref:`use_alter` :param match: Optional string. If set, emit MATCH when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param \**dialect_kw: Additional keyword arguments are dialect specific, and passed in the form ``_``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. .. versionadded:: 0.9.2 )rr!r"r<zOForeignKeyConstraint with duplicate source column references are not supported.z_ForeignKeyConstraint number of constrained columns must match the number of referenced columns.csBg|]:}t|fjjjjjjjjd j qS)) rrrr rrr#r!r") rrrr rrr#r!r"dialect_kwargs)rZrefcolr>rr!rs  z1ForeignKeyConstraint.__init__..Nr)rwrgrr rrr#r/rwrr5elementsr{rrr1r2)r6rZ refcolumnsrrr r!r"rrr#r&r<r%rr>r!rg s>W  zForeignKeyConstraint.__init__cCs|j||j|dSr#)rrrrrrrr!rD+s z$ForeignKeyConstraint._append_elementcCstt|j|jSr#)r OrderedDictzip column_keysrr>rrr! _elements@szForeignKeyConstraint._elementscCs|jD] }|jSdSr#)rr)r6elemrrr!rEs  z%ForeignKeyConstraint._referred_schemacCs|jdjjS)alThe :class:`_schema.Table` object to which this :class:`_schema.ForeignKeyConstraint` references. This is a dynamically calculated attribute which may not be available if the constraint and/or parent table is not yet associated with a metadata collection that contains the referred table. .. versionadded:: 1.0.0 r)rrr&r>rrr!referred_tableLs z#ForeignKeyConstraint.referred_tablecCsZtdd|jD}d|krVt|dkrVt|dd\}}td|j|j||fdS)NcSsg|] }|qSr)r+)rrrrr!r[sz=ForeignKeyConstraint._validate_dest_table..rrrzJForeignKeyConstraint on %s(%s) refers to multiple remote tables: %s and %s)rwrr/rrr5r}_col_description)r6r&Z table_keysZelem0Zelem1rrr!rAZsz)ForeignKeyConstraint._validate_dest_tablecCs(t|dr|jSdd|jDSdS)aReturn a list of string keys representing the local columns in this :class:`_schema.ForeignKeyConstraint`. This list is either the original string arguments sent to the constructor of the :class:`_schema.ForeignKeyConstraint`, or if the constraint has been initialized with :class:`_schema.Column` objects, is the string ``.key`` of each element. .. versionadded:: 1.0.0 rcSs$g|]}t|tr|jnt|qSr)r$rr'strrrrr!rtsz4ForeignKeyConstraint.column_keys..N)rrkeysrr>rrr!rds  z ForeignKeyConstraint.column_keyscCs d|jS)Nr)rrr>rrr!rysz%ForeignKeyConstraint._col_descriptionc Kst||zt||WnFtk rb}z(tjtd|j|j df|dW5d}~XYnXt |j |j D]&\}}t |dr|j|k rr||qr||dS)NzQCan't create ForeignKeyConstraint on table '%s': no column named '%s' is present.rrr)rwrrKeyErrorrr4rr5rr7rrrrrr2rA)r6r&r8Zker)rrrr!r}s    z ForeignKeyConstraint._set_parentrMzkThe :meth:`_schema.ForeignKeyConstraint.copy` method is deprecated and will be removed in a future release.cKs|jf||d|S)Nrr)r6r r,r8rrr!rAszForeignKeyConstraint.copyc svtdd|jDfdd|jD|j|j|j|j|j|j|j|j d }t |j|jD]\}}| |qX| |S)NcSsg|] }|jjqSr)rr'rrrr!rsz.ForeignKeyConstraint._copy..cs:g|]2}|jdk r.||jjjkr.jnddqS)N)r r()r&r+rr&r'rrrrr!rs)rrr rr!r"rr#) rrrrr rr!r"rr#rrD)r6r r,r8rZself_fkZother_fkrrr!rs"   zForeignKeyConstraint._copy) NNNNNFFNNN)NN)NN)rErFrGrHrIrgrDrrrrrrrArrrrrrArrrrr!r sF          rcsZeZdZdZdZfddZfddZddZd d Ze d d Z e j d dZ ZS)rza A table-level PRIMARY KEY constraint. The :class:`.PrimaryKeyConstraint` object is present automatically on any :class:`_schema.Table` object; it is assigned a set of :class:`_schema.Column` objects corresponding to those marked with the :paramref:`_schema.Column.primary_key` flag:: >>> my_table = Table('mytable', metadata, ... Column('id', Integer, primary_key=True), ... Column('version_id', Integer, primary_key=True), ... Column('data', String(50)) ... ) >>> my_table.primary_key PrimaryKeyConstraint( Column('id', Integer(), table=, primary_key=True, nullable=False), Column('version_id', Integer(), table=, primary_key=True, nullable=False) ) The primary key of a :class:`_schema.Table` can also be specified by using a :class:`.PrimaryKeyConstraint` object explicitly; in this mode of usage, the "name" of the constraint can also be specified, as well as other options which may be recognized by dialects:: my_table = Table('mytable', metadata, Column('id', Integer), Column('version_id', Integer), Column('data', String(50)), PrimaryKeyConstraint('id', 'version_id', name='mytable_pk') ) The two styles of column-specification should generally not be mixed. An warning is emitted if the columns present in the :class:`.PrimaryKeyConstraint` don't match the columns that were marked as ``primary_key=True``, if both are present; in this case, the columns are taken strictly from the :class:`.PrimaryKeyConstraint` declaration, and those columns otherwise marked as ``primary_key=True`` are ignored. This behavior is intended to be backwards compatible with previous behavior. .. versionchanged:: 0.9.2 Using a mixture of columns within a :class:`.PrimaryKeyConstraint` in addition to columns marked as ``primary_key=True`` now emits a warning if the lists don't match. The ultimate behavior of ignoring those columns marked with the flag only is currently maintained for backwards compatibility; this warning may raise an exception in a future release. For the use case where specific options are to be specified on the :class:`.PrimaryKeyConstraint`, but the usual style of using ``primary_key=True`` flags is still desirable, an empty :class:`.PrimaryKeyConstraint` may be specified, which will take on the primary key column collection from the :class:`_schema.Table` based on the flags:: my_table = Table('mytable', metadata, Column('id', Integer, primary_key=True), Column('version_id', Integer, primary_key=True), Column('data', String(50)), PrimaryKeyConstraint(name='mytable_pk', mssql_clustered=True) ) .. versionadded:: 0.9.2 an empty :class:`.PrimaryKeyConstraint` may now be specified for the purposes of establishing keyword arguments with the constraint, independently of the specification of "primary key" columns within the :class:`_schema.Table` itself; columns marked as ``primary_key=True`` will be gathered into the empty constraint's column collection. Zprimary_key_constraintcs$|dd|_tt|j||dS)NrjF)rZrjrvrzrg)r6rr8rrr!rgszPrimaryKeyConstraint.__init__c stt|||j|k r:|j|j||_|j|dd|jD}|jr|rt |t |jkrt d|j d dd|Dd dd|jDd dd|jDfg|dd<|jD]}d |_|jtkrd |_q|r|j|dS) NcSsg|]}|jr|qSr)rrrrr!r sz4PrimaryKeyConstraint._set_parent..zTable '%s' specifies columns %s as primary_key=True, not matching locally specified columns %s; setting the current primary key columns to %s. This warning may become an exception in a future releasercss|]}d|jVqdSrrrrrr!rsz3PrimaryKeyConstraint._set_parent..css|]}d|jVqdSrrrrrr!rscss|]}d|jVqdSrrrrrr!rsTF)rvrzrrryrrr(rrwrrrrrrrextend)r6r&r8Z table_pksr(rrr!rs.     z PrimaryKeyConstraint._set_parentcCs8|D] }d|_q|j|tj|||jdS)aKrepopulate this :class:`.PrimaryKeyConstraint` given a set of columns. Existing columns in the table that are marked as primary_key=True are maintained. Also fires a new event. This is basically like putting a whole new :class:`.PrimaryKeyConstraint` object on the parent :class:`_schema.Table` object without actually replacing the object. The ordering of the given list of columns is also maintained; these columns will be appended to the list of columns after any which are already present. TN)rrrrzr_resetr2r&)r6rr)rrr!_reload$s   zPrimaryKeyConstraint._reloadcCs*tj||j||j||dSr#)rzrrrr-rBZ'_sa_event_column_added_to_pk_constraintrrrr!rAs  zPrimaryKeyConstraint._replacecs6|jdk r(gfdd|jDSt|jSdS)Ncsg|]}|k r|qSrrrautoincrr!rLsz>PrimaryKeyConstraint.columns_autoinc_first..)rrrr>rrr!columns_autoinc_firstGsz*PrimaryKeyConstraint.columns_autoinc_firstcCsdd}t|jdkrVt|jd}|jdkr<||d|S|jdkr||dr|SnLd}|jD]<}|jdkr`||d|dk rtd|j|jfq`|}q`|SdS) NcSs|jjdkst|jjtjjs>|r8td|j|fqdSnNt|jtdt fsZ|sZdS|j dk rxt|j t sx|sxdS|j r|j dkrdSdS)NzGColumn type %s on column '%s' is not compatible with autoincrement=TrueF)T ignore_fkT)rZ_type_affinity issubclassrZ INTEGERTYPErr5r$r1rrrr{r)r)Z autoinc_truerrr!_validate_autoincRs4 zEPrimaryKeyConstraint._autoincrement_column.._validate_autoincrrT)rrFzGOnly one Column may be marked autoincrement=True, found both %s and %s.)r/rrrrr5r)r6rr)rrrr!rPs2      z*PrimaryKeyConstraint._autoincrement_column)rErFrGrHrIrgrrrrrrrJrrrrrr!rzsI   rzc@seZdZdZdZdS)raA table-level UNIQUE constraint. Defines a single column or composite UNIQUE constraint. For a no-frills, single column constraint, adding ``unique=True`` to the ``Column`` definition is a shorthand equivalent for an unnamed, single column UniqueConstraint. Zunique_constraintN)rErFrGrHrIrrrr!rsrc@sLeZdZdZdZddZddZeddZdd d Z dd dZ ddZ d S)ra A table-level INDEX. Defines a composite (one or more column) INDEX. E.g.:: sometable = Table("sometable", metadata, Column("name", String(50)), Column("address", String(100)) ) Index("some_index", sometable.c.name) For a no-frills, single column index, adding :class:`_schema.Column` also supports ``index=True``:: sometable = Table("sometable", metadata, Column("name", String(50), index=True) ) For a composite index, multiple columns can be specified:: Index("some_index", sometable.c.name, sometable.c.address) Functional indexes are supported as well, typically by using the :data:`.func` construct in conjunction with table-bound :class:`_schema.Column` objects:: Index("some_index", func.lower(sometable.c.name)) An :class:`.Index` can also be manually associated with a :class:`_schema.Table`, either through inline declaration or using :meth:`_schema.Table.append_constraint`. When this approach is used, the names of the indexed columns can be specified as strings:: Table("sometable", metadata, Column("name", String(50)), Column("address", String(100)), Index("some_index", "name", "address") ) To support functional or expression-based indexes in this form, the :func:`_expression.text` construct may be used:: from sqlalchemy import text Table("sometable", metadata, Column("name", String(50)), Column("address", String(100)), Index("some_index", text("lower(name)")) ) .. versionadded:: 0.9.5 the :func:`_expression.text` construct may be used to specify :class:`.Index` expressions, provided the :class:`.Index` is explicitly associated with the :class:`_schema.Table`. .. seealso:: :ref:`schema_indexes` - General information on :class:`.Index`. :ref:`postgresql_indexes` - PostgreSQL-specific options available for the :class:`.Index` construct. :ref:`mysql_indexes` - MySQL-specific options available for the :class:`.Index` construct. :ref:`mssql_indexes` - MSSQL-specific options available for the :class:`.Index` construct. rcOsd|_}t||dd|_|dd|_|dd}d|krL|d|_d|kr^|d}||g|_tj |f|||jd|dk r| |dS) aConstruct an index object. :param name: The name of the index :param \*expressions: Column expressions to include in the index. The expressions are normally instances of :class:`_schema.Column`, but may also be arbitrary SQL expressions which ultimately refer to a :class:`_schema.Column`. :param unique=False: Keyword only argument; if True, create a unique index. :param quote=None: Keyword only argument; whether to apply quoting to the name of the index. Works in the same manner as that of :paramref:`_schema.Column.quote`. :param info=None: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param \**kw: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``_``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. NrhrFrr<r)rr}) r&rrZrrr<rrr{rgr)r6rrr8r&rrrr!rgs(     zIndex.__init__cKst|||jdk r<||jk r.)r{rr&rr5rrrxrrrr/r1r)r6r&r8rZcol_expressionsrrr!r&s   zIndex._set_parentcCs|jjS)z2Return the connectable associated with this Index.)r&rr>rrr!r:sz Index.bindNFcCs&|dkrt|}|jtj||d|S)zIssue a ``CREATE`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`_schema.MetaData.create_all`. Nrrrrrr!r@s z Index.createcCs&|dkrt|}|jtj||ddS)zIssue a ``DROP`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`_schema.MetaData.drop_all`. Nrrrrrr!rOs z Index.dropcCs6ddt|jgdd|jD|jr,dgp.gS)Nz Index(%s)rcSsg|] }t|qSrr)rerrr!rasz"Index.__repr__..z unique=True)rrrrrr>rrr!r?]s zIndex.__repr__)NF)NF) rErFrGrHrIrgrrrrrr?rrrr!rsK<   rixzix_%(column_0_label)sc@seZdZdZdZejddd)ddZdZdd Z d d Z d d Z ddZ ddZ ddZddZddZedddZeeeZddZddZedd Zd*d#d$Zd+d%d&Zd,d'd(ZdS)-MetaDataaDA collection of :class:`_schema.Table` objects and their associated schema constructs. Holds a collection of :class:`_schema.Table` objects as well as an optional binding to an :class:`_engine.Engine` or :class:`_engine.Connection`. If bound, the :class:`_schema.Table` objects in the collection and their columns may participate in implicit SQL execution. The :class:`_schema.Table` objects themselves are stored in the :attr:`_schema.MetaData.tables` dictionary. :class:`_schema.MetaData` is a thread-safe object for read operations. Construction of new tables within a single :class:`_schema.MetaData` object, either explicitly or via reflection, may not be completely thread-safe. .. seealso:: :ref:`metadata_describing` - Introduction to database metadata re)rNzcThe :paramref:`_schema.MetaData.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.rnNcCsRt|_t|||_|r|nt|_|r.||_t|_ i|_ t t |_||_dS)a>Create a new MetaData object. :param bind: An Engine or Connection to bind to. May also be a string or URL instance, these are passed to :func:`_sa.create_engine` and this :class:`_schema.MetaData` will be bound to the resulting engine. :param schema: The default schema to use for the :class:`_schema.Table`, :class:`.Sequence`, and potentially other objects associated with this :class:`_schema.MetaData`. Defaults to ``None``. .. seealso:: :ref:`schema_metadata_schema_name` - details on how the :paramref:`_schema.MetaData.schema` parameter is used. :paramref:`_schema.Table.schema` :paramref:`.Sequence.schema` :param quote_schema: Sets the ``quote_schema`` flag for those :class:`_schema.Table`, :class:`.Sequence`, and other objects which make usage of the local ``schema`` name. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param naming_convention: a dictionary referring to values which will establish default naming conventions for :class:`.Constraint` and :class:`.Index` objects, for those objects which are not given a name explicitly. The keys of this dictionary may be: * a constraint or Index class, e.g. the :class:`.UniqueConstraint`, :class:`_schema.ForeignKeyConstraint` class, the :class:`.Index` class * a string mnemonic for one of the known constraint classes; ``"fk"``, ``"pk"``, ``"ix"``, ``"ck"``, ``"uq"`` for foreign key, primary key, index, check, and unique constraint, respectively. * the string name of a user-defined "token" that can be used to define new naming tokens. The values associated with each "constraint class" or "constraint mnemonic" key are string naming templates, such as ``"uq_%(table_name)s_%(column_0_name)s"``, which describe how the name should be composed. The values associated with user-defined "token" keys should be callables of the form ``fn(constraint, table)``, which accepts the constraint/index object and :class:`_schema.Table` as arguments, returning a string result. The built-in names are as follows, some of which may only be available for certain types of constraint: * ``%(table_name)s`` - the name of the :class:`_schema.Table` object associated with the constraint. * ``%(referred_table_name)s`` - the name of the :class:`_schema.Table` object associated with the referencing target of a :class:`_schema.ForeignKeyConstraint`. * ``%(column_0_name)s`` - the name of the :class:`_schema.Column` at index position "0" within the constraint. * ``%(column_0N_name)s`` - the name of all :class:`_schema.Column` objects in order within the constraint, joined without a separator. * ``%(column_0_N_name)s`` - the name of all :class:`_schema.Column` objects in order within the constraint, joined with an underscore as a separator. * ``%(column_0_label)s``, ``%(column_0N_label)s``, ``%(column_0_N_label)s`` - the label of either the zeroth :class:`_schema.Column` or all :class:`.Columns`, separated with or without an underscore * ``%(column_0_key)s``, ``%(column_0N_key)s``, ``%(column_0_N_key)s`` - the key of either the zeroth :class:`_schema.Column` or all :class:`.Columns`, separated with or without an underscore * ``%(referred_column_0_name)s``, ``%(referred_column_0N_name)s`` ``%(referred_column_0_N_name)s``, ``%(referred_column_0_key)s``, ``%(referred_column_0N_key)s``, ... column tokens which render the names/keys/labels of columns that are referenced by a :class:`_schema.ForeignKeyConstraint`. * ``%(constraint_name)s`` - a special key that refers to the existing name given to the constraint. When this key is present, the :class:`.Constraint` object's existing name will be replaced with one that is composed from template string that uses this token. When this token is present, it is required that the :class:`.Constraint` is given an explicit name ahead of time. * user-defined: any additional token may be implemented by passing it along with a ``fn(constraint, table)`` callable to the naming_convention dictionary. .. versionadded:: 1.3.0 - added new ``%(column_0N_name)s``, ``%(column_0_N_name)s``, and related tokens that produce concatenations of names, keys, or labels for all columns referred to by a given constraint. .. seealso:: :ref:`constraint_naming_conventions` - for detailed usage examples. N)rZ FacadeDictr[rr DEFAULT_NAMING_CONVENTIONnaming_conventionr<rw_schemasrq collections defaultdictrrr)r6rr rirr<rrr!rgs   zMetaData.__init__cCs|jrd|jSdSdS)NzMetaData(bind=%r)z MetaData()rnr>rrr!r?/s zMetaData.__repr__cCst|tjs|j}||jkSr#)r$rrr'r[)r6Z table_or_keyrrr!r5s zMetaData.__contains__cCs,t||}|j|||r(|j|dSr#)r"r[Z _insert_itemrr)r6rr r&r'rrr!r_:s zMetaData._add_tablecCs\t||}t|j|d}|dk r8|jD]}||q(|jrXtdd|jD|_dS)NcSsg|]}|jdk r|jqSr#r)rtrrr!rHs z*MetaData._remove_table..) r"dictrZr[r{rCrrwvalues)r6rr r'removedrrrr!rc@s   zMetaData._remove_tablecCs|j|j|j|j|j|jdS)N)r[r schemas sequencesfk_memosr)r[r rrqrrr>rrr! __getstate__OszMetaData.__getstate__cCsF|d|_|d|_|d|_d|_|d|_|d|_|d|_dS)Nr[r rrrr)r[r r_bindrqrr)r6staterrr! __setstate__Ys     zMetaData.__setstate__cCs |jdk S)z:True if this MetaData is bound to an Engine or Connection.Nrr>rrr!is_boundbszMetaData.is_boundcCs|jS)a-An :class:`_engine.Engine` or :class:`_engine.Connection` to which this :class:`_schema.MetaData` is bound. Typically, a :class:`_engine.Engine` is assigned to this attribute so that "implicit execution" may be used, or alternatively as a means of providing engine binding information to an ORM :class:`.Session` object:: engine = create_engine("someurl://") metadata.bind = engine .. seealso:: :ref:`dbengine_implicit` - background on "bound metadata" rr>rrr!rgsz MetaData.bindsqlalchemy.engine.urlcCs4tjj}t|tj|jfr*t||_n||_dS)z;Bind this MetaData to an Engine, Connection, string or URL.N) rrW engine_urlr$rURL sqlalchemy create_enginer)r6rurlrrr!_bind_to{szMetaData._bind_tocCs$t|j|j|jdS)z+Clear all Table objects from this MetaData.N)rclearr[rrr>rrr!rs  zMetaData.clearcCs||j|jdS)z1Remove the given Table object from this MetaData.N)rcrr rrrr!rszMetaData.removecCstt|jdddS)aReturns a list of :class:`_schema.Table` objects sorted in order of foreign key dependency. The sorting will place :class:`_schema.Table` objects that have dependencies first, before the dependencies themselves, representing the order in which they can be created. To get the order in which the tables would be dropped, use the ``reversed()`` Python built-in. .. warning:: The :attr:`.MetaData.sorted_tables` attribute cannot by itself accommodate automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. When these cycles are detected, the foreign keys of these tables are omitted from consideration in the sort. A warning is emitted when this condition occurs, which will be an exception raise in a future release. Tables which are not part of the cycle will still be returned in dependency order. To resolve these cycles, the :paramref:`_schema.ForeignKeyConstraint.use_alter` parameter may be applied to those constraints which create a cycle. Alternatively, the :func:`_schema.sort_tables_and_constraints` function will automatically return foreign key constraints in a separate collection when cycles are detected so that they may be applied to a schema separately. .. versionchanged:: 1.3.17 - a warning is emitted when :attr:`.MetaData.sorted_tables` cannot perform a proper sort due to cyclical dependencies. This will be an exception in a future release. Additionally, the sort will continue to return other tables not involved in the cycle in dependency order which was not the case previously. .. seealso:: :func:`_schema.sort_tables` :func:`_schema.sort_tables_and_constraints` :attr:`_schema.MetaData.tables` :meth:`_reflection.Inspector.get_table_names` :meth:`_reflection.Inspector.get_sorted_table_and_fkc_names` cSs|jSr#r)rrrr!rrz(MetaData.sorted_tables..r)rZ sort_tablesrr[rr>rrr! sorted_tabless3zMetaData.sorted_tablesFTc s|dkrt}t|} | ||td} | |dkrLjdk r\| d<t| |r| dk rtfddD} n} tj dkrԇfddt | D} nt rfddt | D} n\fddD} | rDr$d p&d }td |j|d | ffd dD} | D]R}zt|f| Wn8tjk r}ztd||fW5d}~XYnXq\W5QRXdS)a-Load all available table definitions from the database. Automatically creates ``Table`` entries in this ``MetaData`` for any table available in the database but not yet present in the ``MetaData``. May be called multiple times to pick up tables recently added to the database, however no special action is taken if a table in this ``MetaData`` no longer exists in the database. :param bind: A :class:`.Connectable` used to access the database; if None, uses the existing bind on this ``MetaData``, if any. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. :param schema: Optional, query and reflect tables from an alternate schema. If None, the schema associated with this :class:`_schema.MetaData` is used, if any. :param views: If True, also reflect views. :param only: Optional. Load only a sub-set of available named tables. May be specified as a sequence of names or a callable. If a sequence of names is provided, only those tables will be reflected. An error is raised if a table is requested but not available. Named tables already present in this ``MetaData`` are ignored. If a callable is provided, it will be used as a boolean predicate to filter the list of potential table names. The callable is called with a table name and this ``MetaData`` instance as positional arguments and should return a true value for any table to reflect. :param extend_existing: Passed along to each :class:`_schema.Table` as :paramref:`_schema.Table.extend_existing`. .. versionadded:: 0.9.1 :param autoload_replace: Passed along to each :class:`_schema.Table` as :paramref:`_schema.Table.autoload_replace`. .. versionadded:: 0.9.1 :param resolve_fks: if True, reflect :class:`_schema.Table` objects linked to :class:`_schema.ForeignKey` objects located in each :class:`_schema.Table`. For :meth:`_schema.MetaData.reflect`, this has the effect of reflecting related tables that might otherwise not be in the list of tables being reflected, for example if the referenced table is in a different schema or is omitted via the :paramref:`.MetaData.reflect.only` parameter. When False, :class:`_schema.ForeignKey` objects are not followed to the :class:`_schema.Table` in which they link, however if the related table is also part of the list of tables that would be reflected in any case, the :class:`_schema.ForeignKey` object will still resolve to its related :class:`_schema.Table` after the :meth:`_schema.MetaData.reflect` operation is complete. Defaults to True. .. versionadded:: 1.3.0 .. seealso:: :paramref:`_schema.Table.resolve_fks` :param \**dialect_kwargs: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``_``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. .. versionadded:: 0.9.2 - Added :paramref:`.MetaData.reflect.**dialect_kwargs` to support dialect-level reflection options for all :class:`_schema.Table` objects reflected. N)rlrRrmrornr csg|]}d|fqS)rkrrrrrr!rCsz$MetaData.reflect..cs g|]\}}s|kr|qSrrrrZschnamecurrentrRrr!rKscs*g|]"\}}s|kr|r|qSrrr)rrRonlyr6rr!rQs  csg|]}|kr|qSrrr) availablerr!rXsz schema '%s'zACould not reflect: requested table(s) not available in %r%s: (%s)rcsg|]}s|kr|qSrrrrrr!r_szSkipping table %s: %s)r rrrrwrr rZ OrderedSetZget_table_namesZget_view_namesr[rrPrr]ZenginerrKZUnreflectableTableErrorr)r6rr ZviewsrrRrmrorrZ reflect_optsZavailable_w_schemaloadmissingsrZuerrr)rrrRrr r6r!reflects^`    zMetaData.reflectcCs(|dkrt|}|jtj|||ddS)aCreate all tables stored in this metadata. Conditional by default, will not attempt to recreate tables already present in the target database. :param bind: A :class:`.Connectable` used to access the database; if None, uses the existing bind on this ``MetaData``, if any. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. :param tables: Optional list of ``Table`` objects, which is a subset of the total tables in the ``MetaData`` (others are ignored). :param checkfirst: Defaults to True, don't issue CREATEs for tables already present in the target database. Nrr[rr6rr[rrrr! create_allkszMetaData.create_allcCs(|dkrt|}|jtj|||ddS)aDrop all tables stored in this metadata. Conditional by default, will not attempt to drop tables not present in the target database. :param bind: A :class:`.Connectable` used to access the database; if None, uses the existing bind on this ``MetaData``, if any. .. note:: the "bind" argument will be required in SQLAlchemy 2.0. :param tables: Optional list of ``Table`` objects, which is a subset of the total tables in the ``MetaData`` (others are ignored). :param checkfirst: Defaults to True, only issue DROPs for tables confirmed to be present in the target database. Nrrrrrr!drop_allszMetaData.drop_all)NNNNN)NNFNFTT)NNT)NNT)rErFrGrHrIrrrgr[r?rr_rcrrrrr]rrrrrrrrrrrr!rjsN       8 # rrMzT:class:`.ThreadLocalMetaData` is deprecated and will be removed in a future release.rg) constructorcsXeZdZdZdZfddZddZeddd Z e ee Zd d Z d d Z Z S)ThreadLocalMetaDataaA MetaData variant that presents a different ``bind`` in every thread. Makes the ``bind`` property of the MetaData a thread-local value, allowing this collection of tables to be bound to different ``Engine`` implementations or connections in each thread. The ThreadLocalMetaData starts off bound to None in each thread. Binds must be made explicitly by assigning to the ``bind`` property or using ``connect()``. You can also re-bind dynamically multiple times per thread, just like a regular ``MetaData``. recs$tj|_i|_tt|dS)z Construct a ThreadLocalMetaData.N)r threadinglocalcontext_ThreadLocalMetaData__enginesrvrrgr>rrr!rgs zThreadLocalMetaData.__init__cCst|jddS)zThe bound Engine or Connection for this thread. This property may be assigned an Engine or Connection, or assigned a string or URL to automatically create a basic Engine for this bind with ``create_engine()``._engineN)rrr>rrr!rszThreadLocalMetaData.bindrcCstjj}t|tj|jfrbz|j||j_Wq~t k r^t |}||j|<||j_Yq~Xn||jkrv||j|<||j_dS)z-Bind to a Connectable in the caller's thread.N) rrWrr$rrrrrrrr)r6rrrrrr!rs    zThreadLocalMetaData._bind_tocCst|jdo|jjdk S)z(True if there is a bind for this thread.rN)rrrr>rrr!rs  zThreadLocalMetaData.is_boundcCs&|jD]}t|dr |q dS)z2Dispose all bound engines, in all thread contexts.disposeN)rrrr)r6rrrr!rs zThreadLocalMetaData.dispose)rErFrGrHrIrgrrr]rrrrrrrrr!rs     rc@sZeZdZdZdZeddddddZd d Zd d Ze d ddddZ dddZ dS)r aDefines a generated column, i.e. "GENERATED ALWAYS AS" syntax. The :class:`.Computed` construct is an inline construct added to the argument list of a :class:`_schema.Column` object:: from sqlalchemy import Computed Table('square', meta, Column('side', Float, nullable=False), Column('area', Float, Computed('side * side')) ) See the linked documentation below for complete details. .. versionadded:: 1.3.11 .. seealso:: :ref:`computed_ddl` Zcomputed_columnrz:class:`.Computed`z:paramref:`.Computed.sqltext`NcCs ttj||_||_d|_dS)a Construct a GENERATED ALWAYS AS DDL construct to accompany a :class:`_schema.Column`. :param sqltext: A string containing the column generation expression, which will be used verbatim, or a SQL expression construct, such as a :func:`_expression.text` object. If given as a string, the object is converted to a :func:`_expression.text` object. :param persisted: Optional, controls how this column should be persisted by the database. Possible values are: * ``None``, the default, it will use the default persistence defined by the database. * ``True``, will render ``GENERATED ALWAYS AS ... STORED``, or the equivalent for the target database if supported. * ``False``, will render ``GENERATED ALWAYS AS ... VIRTUAL``, or the equivalent for the target database if supported. Specifying ``True`` or ``False`` may raise an error when the DDL is emitted to the target database if the database does not support that persistence option. Leaving this parameter at its default of ``None`` is guaranteed to succeed for all databases that support ``GENERATED ALWAYS AS``. N)rrrrr persistedr)r6rrrrr!rgs zComputed.__init__cKsRt|jtdtfr(t|jtdtfs2td||_||_||j_||j_dS)NzPA generated column cannot specify a server_default or a server_onupdate argument) r$rrr rrr5rrryrrr!r,s zComputed._set_parentcCs|Sr#rrFrrr!r9szComputed._as_for_updaterMz_The :meth:`_schema.Computed.copy` method is deprecated and will be removed in a future release.cKs|j|f|Sr#rrrrr!rA<sz Computed.copycKs8t|j|jdk r|jjnd|}t||jd}||S)N)r)r.rrr&r rrD)r6r,r8rgrrr!rDszComputed._copy)N)N)N) rErFrGrHrIrrgrrrrrArrrrr!r s  !  r c @sJeZdZdZdZdddZddZd d Ze d d d dZ ddZ dS)raDefines an identity column, i.e. "GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY" syntax. The :class:`.Identity` construct is an inline construct added to the argument list of a :class:`_schema.Column` object:: from sqlalchemy import Identity Table('foo', meta, Column('id', Integer, Identity()) Column('description', Text), ) See the linked documentation below for complete details. .. versionadded:: 1.4 .. seealso:: :ref:`identity_ddl` Zidentity_columnFNc Cs4tj|||||||| | | d ||_||_d|_dS)ahConstruct a GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY DDL construct to accompany a :class:`_schema.Column`. See the :class:`.Sequence` documentation for a complete description of most parameters. .. note:: MSSQL supports this construct as the preferred alternative to generate an IDENTITY on a column, but it uses non standard syntax that only support :paramref:`_schema.Identity.start` and :paramref:`_schema.Identity.increment`. All other parameters are ignored. :param always: A boolean, that indicates the type of identity column. If ``False`` is specified, the default, then the user-specified value takes precedence. If ``True`` is specified, a user-specified value is not accepted ( on some backends, like PostgreSQL, OVERRIDING SYSTEM VALUE, or similar, may be specified in an INSERT to override the sequence value). Some backends also have a default value for this parameter, ``None`` can be used to omit rendering this part in the DDL. It will be treated as ``False`` if a backend does not have a default value. :param on_null: Set to ``True`` to specify ON NULL in conjunction with a ``always=False`` identity column. This option is only supported on some backends, like Oracle. :param start: the starting index of the sequence. :param increment: the increment value of the sequence. :param minvalue: the minimum value of the sequence. :param maxvalue: the maximum value of the sequence. :param nominvalue: no minimum value of the sequence. :param nomaxvalue: no maximum value of the sequence. :param cycle: allows the sequence to wrap around when the maxvalue or minvalue has been reached. :param cache: optional integer value; number of future values in the sequence which are calculated in advance. :param order: optional boolean value; if true, renders the ORDER keyword. r_N)r^rgalwayson_nullr) r6rrr`rarbrcrdrerfrgrhrrr!rgis; zIdentity.__init__cKsht|jtdtfr$t|jtds.td|jdkrBtd||_||_ |j t kr^d|_ ||_dS)Nz^A column with an Identity object cannot specify a server_default or a server_onupdate argumentFzCA column with an Identity object cannot specify autoincrement=False) r$rrrrrr5rrrrrrryrrr!rs$   zIdentity._set_parentcCs|Sr#rrFrrr!rszIdentity._as_for_updaterMz_The :meth:`_schema.Identity.copy` method is deprecated and will be removed in a future release.cKs |jf|Sr#rrrrr!rAsz Identity.copyc Ks>t|j|j|j|j|j|j|j|j|j |j |j d }| |S)N) rrr`rarbrcrdrerfrgrh) rrrr`rarbrcrdrerfrgrhrD)r6r8irrr!rszIdentity._copy) FNNNNNNNNNN) rErFrGrHrIrgrrrrrArrrrr!rOs, K r)BrH __future__rrrrrrrrrbaser r r r r rrrrrrrrrrrrrrrsymbolrrYrr"r.Z_self_inspectsZ Visitabler/rKr%rrErrTr^rrrrwr{rrrrzrrZ immutabledictrrZdeprecated_clsrr rrrrr!s                            0TMr0q5,4$^e^l-\ L@C`