o znh@sdZddlmZddlZddlZddlZddlmZddlmZddlm Z ddl m Z dd l m Z dd l m Z dd l mZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZedZeddZ ddZ!dd Z"ej#Gd!d"d"ee j$Z%Gd#d$d$e e%eZ&Gd%d&d&e e%eZ'Gd'd(d(e e%Z(Gd)d*d*e)Z*Gd+d,d,e*e%Z+Gd-d.d.e+Z,Gd/d0d0e+Z-ej#Gd1d2d2e*eZ.Gd3d4d4e.Z/e0d5d6Gd7d8d8e/Z1Gd9d:d:e e%Z2d;d<Z3d=d>Z4Gd?d@d@e)Z5GdAdBdBe5e2Z6GdCdDdDe6Z7GdEdFdFe6Z8GdGdHdHe6Z9GdIdJdJe6Z:GdKdLdLe e5e%Z;eGdQdRdRe>Z?GdSdTdTe)Z@e@dZAe@jBZBGdUdVdVe.e%ZCdS)Wa/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)ddl)type_api)visitors)_bind_or_error)ColumnCollection) DialectKWArgs)SchemaEventTarget) _as_truncated)_document_text_coercion)_literal_as_text) ClauseElement) ColumnClause) ColumnElement) quoted_name) TextClause) TableClauseevent)exc) inspection)util retain_schema blank_schemazSymbol indicating that a :class:`.Table` or :class:`.Sequence` should have 'None' for its schema, even if the parent :class:`.MetaData` has specified a schema. .. versionadded:: 1.0.14 cCs|dur|S|d|S)N.)nameschemarr@/usr/local/lib/python3.10/dist-packages/sqlalchemy/sql/schema.py_get_table_keyIs r!csfdd}t|i|S)Ncs0t|tr|jur|jjvrj|jSdSN) isinstanceColumntablekeyc)col source_table target_tablerr replaceSs    z!_copy_expression..replace)rreplacement_traverse) expressionr*r+r,rr)r _copy_expressionRs r/c@sbeZdZdZdZddZddZddZee d d d d Z e j d dZ ddZddZdS) SchemaItemz3Base class for items that define a database schema. schema_itemc GsP|D]#}|dur%z|j}Wnty ttd|Yqw||qdS)z7Initialize the list of child items for this SchemaItem.NzJ'SchemaItem' object, such as a 'Column' or a 'Constraint' expected, got %r)_set_parent_with_dispatchAttributeErrorrraise_from_causer ArgumentError)selfargsitemspwdrrr _init_itemsfs   zSchemaItem._init_itemscKsgS)z"used to allow SchemaVisitor accessrr6kwargsrrr get_childrenwzSchemaItem.get_childrencCstj|dgdS)Ninfo) omit_kwargr generic_reprr6rrr __repr__{zSchemaItem.__repr__0.9zThe :attr:`.SchemaItem.quote` attribute is deprecated and will be removed in a future release. Use the :attr:`.quoted_name.quote` attribute on the ``name`` field of the target schema item to retrievequoted status.cC|jjS)zReturn the value of the ``quote`` flag passed to this schema object, for those schema items which have a ``name`` field. )rquoterCrrr rH~szSchemaItem.quotecCsiS)aLInfo 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:`.Table` and :class:`.Column`. rrCrrr r?s zSchemaItem.infocCs(d|jvr |j|_|j|j|S)Nr?)__dict__r?copydispatch_update)r6r1rrr _schema_item_copys  zSchemaItem._schema_item_copycCs |||Sr")get)r6effective_schemamap_rrr _translate_schema zSchemaItem._translate_schemaN)__name__ __module__ __qualname____doc____visit_name__r:r=rDpropertyr deprecatedrHmemoized_propertyr?rMrQrrrr r0`s    r0csBeZdZdZdZejddddZee ddd d Z d d Z fd dZ   dAddZ eddZeddZddZddZddZddZed d!Zed"d#Zd$d%Zd&d'Zed(d)Zd*d+Zd,d-Zd.d/Ze d0d1d2d3Zd4d5Z 6dBd7d8ZdCd9d:ZdDd;d<Z dDd=d>Z!e"ddfd?d@Z#Z$S)ETablea2Represent a table in a database. e.g.:: mytable = Table("mytable", metadata, Column('mytable_id', Integer, primary_key=True), Column('value', String(50)) ) The :class:`.Table` object constructs a unique instance of itself based on its name and optional schema name within the given :class:`.MetaData` object. Calling the :class:`.Table` constructor with the same name and same :class:`.MetaData` argument a second time will return the *same* :class:`.Table` object - in this way the :class:`.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:`.Table` within the owning :class:`.MetaData` collection. Additional calls to :class:`.Table` with the same name, metadata, and schema name will return the same :class:`.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:`.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:`.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:`.ForeignKeyConstraint`. :param autoload: Defaults to False, unless :paramref:`.Table.autoload_with` is set in which case it defaults to True; :class:`.Column` objects for this table should be reflected from the database, possibly augmenting or replacing existing :class:`.Column` objects that were explicitly specified. .. versionchanged:: 1.0.0 setting the :paramref:`.Table.autoload_with` parameter implies that :paramref:`.Table.autoload` will default to True. .. seealso:: :ref:`metadata_reflection_toplevel` :param autoload_replace: Defaults to ``True``; when using :paramref:`.Table.autoload` in conjunction with :paramref:`.Table.extend_existing`, indicates that :class:`.Column` objects present in the already-existing :class:`.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:`.Column` objects specified programmatically within the call to :class:`.Table` that also is autoloading; those :class:`.Column` objects will always replace existing columns of the same name when :paramref:`.Table.extend_existing` is ``True``. .. seealso:: :paramref:`.Table.autoload` :paramref:`.Table.extend_existing` :param autoload_with: An :class:`.Engine` or :class:`.Connection` object with which this :class:`.Table` object will be reflected; when set to a non-None value, it implies that :paramref:`.Table.autoload` is ``True``. If left unset, but :paramref:`.Table.autoload` is explicitly set to ``True``, an autoload operation will attempt to proceed by locating an :class:`.Engine` or :class:`.Connection` bound to the underlying :class:`.MetaData` object. .. seealso:: :paramref:`.Table.autoload` :param extend_existing: When ``True``, indicates that if this :class:`.Table` is already present in the given :class:`.MetaData`, apply further arguments within the constructor to the existing :class:`.Table`. If :paramref:`.Table.extend_existing` or :paramref:`.Table.keep_existing` are not set, and the given name of the new :class:`.Table` refers to a :class:`.Table` that is already present in the target :class:`.MetaData` collection, and this :class:`.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:`.Table` is specified that matches an existing :class:`.Table`, yet specifies additional constructs. :paramref:`.Table.extend_existing` will also work in conjunction with :paramref:`.Table.autoload` to run a new reflection operation against the database, even if a :class:`.Table` of the same name is already present in the target :class:`.MetaData`; newly reflected :class:`.Column` objects and other options will be added into the state of the :class:`.Table`, potentially overwriting existing columns and options of the same name. As is always the case with :paramref:`.Table.autoload`, :class:`.Column` objects can be specified in the same :class:`.Table` constructor, which will take precedence. Below, the existing table ``mytable`` will be augmented with :class:`.Column` objects both reflected from the database, as well as the given :class:`.Column` named "y":: Table("mytable", metadata, Column('y', Integer), extend_existing=True, autoload=True, autoload_with=engine ) .. seealso:: :paramref:`.Table.autoload` :paramref:`.Table.autoload_replace` :paramref:`.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 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:`.Table` objects related to this one via :class:`.ForeignKey` objects, when :paramref:`.Table.autoload` or :paramref:`.Table.autoload_with` is specified. Defaults to True. Set to False to disable reflection of related tables as :class:`.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:`.MetaData` collection, or becomes present later, a :class:`.ForeignKey` object associated with this :class:`.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:`.MetaData`, ignore further arguments within the constructor to the existing :class:`.Table`, and return the :class:`.Table` object as originally created. This is to allow a function that wishes to define a new :class:`.Table` on first call, but on subsequent calls will return the same :class:`.Table`, without any of the declarations (particularly constraints) being applied a second time. If :paramref:`.Table.extend_existing` or :paramref:`.Table.keep_existing` are not set, and the given name of the new :class:`.Table` refers to a :class:`.Table` that is already present in the target :class:`.MetaData` collection, and this :class:`.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:`.Table` is specified that matches an existing :class:`.Table`, yet specifies additional constructs. .. seealso:: :paramref:`.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:`.Table` before the "autoload" process begins. Particularly useful for the :meth:`.DDLEvents.column_reflect` event:: def listen_for_reflect(table, column_info): "handle the column reflection event" # ... t = Table( 'sometable', autoload=True, listeners=[ ('column_reflect', listen_for_reflect) ]) :param mustexist: When ``True``, indicates that this Table must already be present in the given :class:`.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:`.MetaData` of this :class:`.Table` specifies its own :paramref:`.MetaData.schema` parameter, then that schema name will be applied to this :class:`.Table` if the schema parameter here is set to ``None``. To set a blank schema name on a :class:`.Table` that would otherwise use the schema set on the owning :class:`.MetaData`, specify the special symbol :attr:`.BLANK_SCHEMA`. .. versionadded:: 1.0.14 Added the :attr:`.BLANK_SCHEMA` symbol to allow a :class:`.Table` to have a blank schema name even when the parent :class:`.MetaData` specifies :paramref:`.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 useexisting: the same as :paramref:`.Table.extend_existing`. :param comment: Optional string that will render an SQL comment on table creation. .. versionadded:: 1.2 Added the :paramref:`.Table.comment` parameter to :class:`.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%)0.7zThe :paramref:`.Table.useexisting` parameter is deprecated and will be removed in a future release. Please use :paramref:`.Table.extend_existing`.) useexistingc Os|st|Sz|d|d|dd}}}Wn ty$tdw|dd}|dur3|j}n|tur9d}|dd}|dd}d |vrX|rRd }t ||d d}|rc|rcd }t ||d d} t ||} | |j vr|s|st |rt d | |j | } |r| j|i|| S| rt d| t|} | j| ||||| z| j||g|Ri|| j| || WSt|||WdYdS1swYYdS)Nrrrz$Table() takes at least two argumentsr keep_existingFextend_existingr]z/useexisting is synonymous with extend_existing.z9keep_existing and extend_existing are mutually exclusive. mustexistzTable '%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 TypeErrorrNr BLANK_SCHEMApoprr5r!tablesboolInvalidRequestError_init_existingrKbefore_parent_attach _add_table_initafter_parent_attachr safe_reraise _remove_table) clsr7kwrmetadatarr^r_msgr`r&r%rrr rbs` $             &z Table.__new__rFzThe :meth:`.SchemaItem.quote` method is deprecated and will be removed in a future release. Use the :attr:`.quoted_name.quote` attribute on the ``schema`` field of the target schema item to retrieve quoted status.cCrG)z^Return the value of the ``quote_schema`` flag passed to this :class:`.Table`. )rrHrCrrr quote_schemas zTable.quote_schemacOdS)zConstructor for :class:`~.schema.Table`. This method is a no-op. See the top-level documentation for :class:`~.schema.Table` for constructor arguments. Nr)r6r7rrrrr __init__ szTable.__init__cstt|t||dd||_|dd|_|jdur#|j|_n|jtur,d|_n |dd}t|j||_t|_ t|_ t |_ t dd|t|_t|_|jdurdd|j|jf|_n|j|_|dd}|d|du}|d d|d d}|d d} |d d} |d d|_|dd|_d|vr|d|_d|vr|d} | D] \} } t|| | q|dg|_|jdi||r|j||| || d|j|dS)NrHrruT)_implicit_generated%s.%s autoload_withautoloadautoload_replace _extend_on resolve_fksinclude_columnsimplicit_returningcommentr? listenersprefixes)r}r~r)superr[rwrrfrsrresetindexes constraintsr_columnsPrimaryKeyConstraintr2 foreign_keys_extra_dependenciesrfullnamerrr?rlisten _prefixes _extra_kwargs _autoloadr:)r6rrsr7r<rurzr{r}r~rrevtfn __class__rr rms`               z Table._initrTNcCsL|r|j|jj|||||ddSt|dd}|j|jj|||||ddS)Nr}zNo engine is bound to this Table's MetaData. Pass an engine to the Table via autoload_with=, or associate the MetaData with an engine via metadata.bind=)rt) run_callabledialect reflecttabler)r6rsrzrexclude_columnsr~r}bindrrr rZs*    zTable._autoloadcCst|jdddS)zTReturn the set of constraints as a list, sorted by creation order. cS|jSr")_creation_order)r'rrr z+Table._sorted_constraints..r&)sortedrrCrrr _sorted_constraintsszTable._sorted_constraintscCstdd|jDS)z:class:`.ForeignKeyConstraint` objects referred to by this :class:`.Table`. This list is produced from the collection of :class:`.ForeignKey` objects currently associated. .. versionadded:: 1.0.0 css|]}|jVqdSr") constraint).0fkcrrr sz0Table.foreign_key_constraints..)rrrCrrr foreign_key_constraintss zTable.foreign_key_constraintsc Os<|dd}|d|du}|dd}|dd}|dd}|r0||jkr0td|j|f|dd}|d d} |durQ|jD] } | j|vrP|j| qCd D] } | |vr^td qSd |vrj|d d|_d |vrt|d |_ |r|sdd|jD} nd} |j |j ||| | |d|j di||j |dS)Nrzr{r|Trr}z7Can't change schema of existing table from '%s' to '%s'rr~)rHruz2Can't redefine 'quote' or 'quote_schema' argumentsrr?cSsg|]}|jqSrrrr'rrr z(Table._init_existing..rr)rfrrr5r'rrremoverr?rrsrr:) r6r7r<rzr{r|rr}rr~r'r&rrrr rjsR           zTable._init_existingcK||dSr"_validate_dialect_kwargsr;rrr rzTable._extra_kwargscCdSr"rrCrrr _init_collectionszTable._init_collectionscCrr"rrCrrr _reset_exportedrzTable._reset_exportedcCrGr") primary_key_autoincrement_columnrCrrr rszTable._autoincrement_columncCt|j|jS)a_Return the 'key' for this :class:`.Table`. This value is used as the dictionary key within the :attr:`.MetaData.tables` collection. It is typically the same as that of :attr:`.Table.name` for a table with no :attr:`.Table.schema` set; otherwise it is typically of the form ``schemaname.tablename``. )r!rrrCrrr r&s z Table.keycsDddtjgtjgddjDfdddDS)Nz Table(%s), cSg|]}t|qSrreprrxrrr rz"Table.__repr__..c"g|] }d|tt|fqS%s=%srgetattrrkrCrr r"r)joinrrrscolumnsrCrrCr rDs  zTable.__repr__cCrr")r! descriptionrrCrrr __str__rz Table.__str__cCs|jr|jjpdS)z2Return the connectable associated with this Table.NrsrrCrrr rsz 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)raddr6r%rrr add_is_dependent_ons zTable.add_is_dependent_oncC||dS)azAppend 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. Nr2r6columnrrr append_columnszTable.append_columncCr)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_constraintszTable.append_constraintr\zthe :meth:`.Table.append_ddl_listener` method is deprecated and will be removed in a future release. Please refer to :class:`.DDLEvents`.cs,fdd}t|ddd|dS)z8Append a DDL event listener to this ``Table``. cs||dSr"r)target connectionrr event_namelistenerrr adapt_listener9rEz1Table.append_ddl_listener..adapt_listener-_Nrrr,r6rrrrrr append_ddl_listener.s zTable.append_ddl_listenercCs||j|j|||_dSr")rlrrrsr6rsrrr _set_parent>s zTable._set_parentFcKs,|s tj|fd|i|S|rt|jSgS)Ncolumn_collections)rr=listr)r6rschema_visitorrrrrr r=Bs zTable.get_childrencCs(|durt|}|j|jj|j|jdS)z!Return True if this table exists.Nr)rrr has_tablerrr6rrrr existsOs z Table.existscC&|durt|}|jtj||ddS)zIssue a ``CREATE`` statement for this :class:`.Table`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`.MetaData.create_all`. N checkfirstr _run_visitorrSchemaGeneratorr6rrrrr createYs z Table.createcCr)zIssue a ``DROP`` statement for this :class:`.Table`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`.MetaData.drop_all`. Nrrrr SchemaDropperrrrr drophs z Table.dropc sj|durj}|turj}n|dur|j}t||}||jvr-tdj|j|Sg}jD] }| |j |dq2t ||g|R|j dj jD]9}t|trz|j}|rf||||} n |jkrm|nd} |j | dqR|js|jrqR|j |dqRjD] } | jrqt| jgfdd| jDR| jd| j qS) a` Return a copy of this :class:`.Table` associated with a different :class:`.MetaData`. E.g.:: m1 = MetaData() user = Table('user', m1, Column('id', Integer, primary_key=True)) m2 = MetaData() user_copy = user.tometadata(m2) :param metadata: Target :class:`.MetaData` object, into which the new :class:`.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:`.Table`. If set to a string name, the new :class:`.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:`.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.tometadata(m2, schema=None) m3 = MetaData() # schema defaults to None # user_copy_two will have None as the schema name user_copy_two = user.tometadata(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:`.ForeignKeyConstraint`. The callable accepts this parent :class:`.Table`, the target schema that we are changing to, the :class:`.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.tometadata(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:`.Table` to be copied to the same :class:`.MetaData` target with a new name. .. versionadded:: 1.0.0 NzBTable '%s' already exists within the given MetaData - not copying.r)rrrr+csg|]}t|qSr)r/)rexprrrr rs z$Table.tometadata..)unique_table)r RETAIN_SCHEMArr!rgrwarnrrappendrJr[rr<rr#ForeignKeyConstraint_referred_schemar _type_bound _column_flagrIndex expressionsrrM) r6rsrreferred_schema_fnrr&r7r'referred_schemafk_constraint_schemaindexrrr tometadatavs~G           zTable.tometadata)rTN)TFr"NF)%rSrTrUrVrWrdeprecated_paramsrbrXrYrurwrmrrrrjrrrrr&rDrrrrrrrr=rrrrr __classcell__rrrr r[sn 8  I %   6       r[cseZdZdZdZfddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZ dddZdddZZS)r$z(Represents a column in a database table.rcs.|dd}|dd}t|}|r(t|dtjr(|dur#td|d}|rA|d}t|drA|dur|jdurdS|jdur|jjr|jjd|jS|jS|jS)Nz (no name)r)rr%named_with_columnrrCrrr r|s  zColumn.__str__cCs&|jD] }|jj|jrdSqdS)zOReturn True if this Column references the given column via foreign key.TF)rr proxy_set intersectionr6rfkrrr referencess zColumn.referencescCs||dSr"r)r6r(rrr append_foreign_keyrzColumn.append_foreign_keycsg}jjkr |djr|djs|djr%|djr-|djr5|dddt jgt j gd d j Dd d j Dj dur^d j jp_d gfdd |DS)Nr&rr rr r z Column(%s)rcSsg|] }|durt|qSr"rrrrr rz#Column.__repr__..cSrrrrrrr rrz table=<%s>z table=NonecrrrrrCrr rr)r&rrrr rr r rrrrrr%r)r6kwargrrCr rDs<            zColumn.__repr__csv|jstd|jdur|j|_t|dd}|dur*|ur*td|j|jf|jjvrTj|j}||urT|jD]}j ||j j vrSj |j q>j ||j rdj |n|jj vrutd|jjf|_|jrt|jtjrtdtd|jt|jddn|jrt|jtjrtdt|jdd |fd d dS) 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'zTTrying 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_tabler(r%rr rs z$Column._set_parent..)rrr5r&rrrrNrrrrr,r_replacerr%rr#rrrrrhrUniqueConstraint_setup_on_memoized_fks)r6r%existingr(r(rr/r rsd           zColumn._set_parentcCsj|jj|jfdf|jj|jfdfg}|D]\}}||jjjvr2|jjj|D] }|j|ur1||q&qdS)NFT)r%r&rrs _fk_memos link_to_name)r6rfk_keysfk_keyr5r(rrr r2s  zColumn._setup_on_memoized_fkscCs,|jdur |||jdSt|d|dS)Nrn)r%rr)r6rrrr _on_table_attachs zColumn._on_table_attachc sfdd|jDfdd|jD}|j}|j}t|tr/d}}||jjdi|j}t|t r?|jdi}|j ||j ||j |j |j|j|j|j|j|j||j||j|jd}||S)ziCreate a copy of this ``Column``, uninitialized. This is used in ``Table.tometadata``. c"g|] }|js|jdiqSr)rrJrrrrr rs zColumn.copy..cr9r:)rrJrr;rr rrN)rr r&rr rrrrr r rrrrr)rrr rr#ComputedrrJrr _constructorrr&rr rrrrr rrrrM)r6rrr7r rr r'rr;r rJs@    z Column.copyNFcKsdd|jD}|dur|jdurtdz+|j|r"t|p |jn|p&|j|jg|R|r0|n|r4|n|j|j|j |gd}Wnt yTt t d|j Ynw||_|j||jdurl|jj|j|_|jru|j||j|||S)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 r<sz&Column._make_proxy..Nz^Cannot initialize a sub-selectable with this Column object until its 'name' has been assigned.)r&rr rzCould 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.)rrrrir=r rr&rr rdrr4rr%rr _is_clone_ofrrNrKrn)r6 selectablerr&name_is_truncatablerrr(r'rrr _make_proxy1sL      zColumn._make_proxycKs@|rdd|j|jfDt|jt|jStj|fi|S)NcSsg|]}|dur|qSr"rrrrr riz'Column.get_children..)r rrrrrr=)r6rr<rrr r=fszColumn.get_children)NNFF)rSrTrUrVrWrwrrr)r*rDrr2r8rJrDr=rrrrr r$s$ s  D , 5r$c@seZdZdZdZ          d'ddZddZd(d d Zd)d d Ze d dZ ddZ e eZ ddZ ddZejddZddZddZddZejddZdd Zd!d"Zd#d$Zd%d&ZdS)*r?aDefines a dependency between two columns. ``ForeignKey`` is specified as an argument to a :class:`.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:`.ForeignKeyConstraint` object. This object will be generated automatically when a ``ForeignKey`` is associated with a :class:`.Column` which in turn is associated with a :class:`.Table`. Conversely, when :class:`.ForeignKeyConstraint` is applied to a :class:`.Table`, ``ForeignKey`` markers are automatically generated to be present on each associated :class:`.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:`.ForeignKeyConstraint` object must be used, and applied to the :class:`.Table`. The associated ``ForeignKey`` objects are created automatically. The ``ForeignKey`` objects associated with an individual :class:`.Column` object are available in the `foreign_keys` collection of that column. Further examples of foreign key configuration are in :ref:`metadata_foreignkeys`. foreign_keyNFc Ks||_t|jtjrd|_n2t|jdr|j|_n|j|_t|jts-t d|jt|jj tj t fs@t d|jj ||_ d|_||_||_||_||_||_||_| |_| |_| rc| |_| |_dS)a9 Construct a column-level FOREIGN KEY. The :class:`.ForeignKey` object when constructed generates a :class:`.ForeignKeyConstraint` which is associated with the parent :class:`.Table` object's collection of constraints. :param column: A single target column for the key relationship. A :class:`.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:`.ForeignKeyConstraint` to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE statement. See :paramref:`.ForeignKeyConstraint.use_alter` for further description. .. seealso:: :paramref:`.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:`.ForeignKeyConstraint`. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. .. versionadded:: 0.9.2 N__clause_element__z9String, Column, or Column-bound argument expected, got %rz8ForeignKey received Column not bound to a Table, got: %r)_colspecr#rr _table_columnrrHrrr5r%NoneTyperrparent use_alterrrondelete deferrable initiallyr5matchr?_unvalidated_dialect_kw) r6rr>rMrrrNrOrPr5rQr? dialect_kwrrr rwsBR    zForeignKey.__init__cCs d|S)NzForeignKey(%r)) _get_colspecrCrrr rDrRzForeignKey.__repr__c CsFt|j|df|j|j|j|j|j|j|j|j d|j }| |S)aProduce a copy of this :class:`.ForeignKey` object. The new :class:`.ForeignKey` will not be bound to any :class:`.Column`. This method is usually used by the internal copy procedures of :class:`.Column`, :class:`.Table`, and :class:`.MetaData`. :param schema: The returned :class:`.ForeignKey` will reference the original table and column name, qualified by the given string schema name. r)rMrrrNrOrPr5rQ) r?rTrMrrrNrOrPr5rQrRrM)r6rr(rrr rJs   zForeignKey.copycCs~|r|j\}}}|dur|}d|||fS|r,|j\}}}|r&d|||fSd||fS|jdur.set_type)rLrrkr#r%r[r2r)r6rrmrrlr rhs     zForeignKey._set_target_columncCst|jtjr;|\}}}||jvrtd|j||f||j |jvr,t d|t d|j|j ||f||t |jdrH|j}|S|j}|S)aReturn the target :class:`.Column` referenced by this :class:`.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 MetaDatarfrH)r#rIrrrdrsrNoReferencedTableErrorrLr&rirgrrrH)r6rbrcrYrirrr rs6     zForeignKey.columncCsD|jdur|j|urtd||_|jj||j|jdS)Nz&This ForeignKey already has a parent !)rLrrirrr8 _set_tablerrrr rszForeignKey._set_parentcCs,|\}}}|||||j|dSr")rdrjr_validate_dest_table)r6r%rbrcrYrrr r-szForeignKey._set_remote_tablecCs<|\}}}||f}||j|vr|j||dSdSr")rdr4r)r6rsrb table_keyrYr7rrr _remove_from_metadata$s z ForeignKey._remove_from_metadatac Cs |jdur1t|tr1tggf|j|j|j|j|j|j |j d|j |_|j |||j ||j|t|jtjrt|\}}}||f}||jjvri|jj|}z ||||Wn tjyhYnw|jj||dSt|jdr|j}||dS|j}||dS)N)rMrrrNrOrPrQrH)rr#r[rrMrrrNrOrPrQrR_append_elementr2rrrIrrrdrsrgrjrrgr4rrrHrh)r6rr%rbrqrYr7rirrr ro,sD       zForeignKey._set_table) NFNNNNNFNNr"NN)rSrTrUrVrWrwrDrJrTrXrrZtarget_fullnamer)r]rrZrUrdrjrhrrr-rrrorrrr r?qsD$ {     ## /  r?c@s,eZdZddZddZZeddZdS)_NotAColumnExprcCtd|jj)Nz7This %s cannot be used directly as a column expression.rrirrSrCrrr _not_a_column_exprVs z"_NotAColumnExpr._not_a_column_exprcC|Sr"ryrCrrr r\z_NotAColumnExpr.cCrzr"r{rCrrr r]r|N)rSrTrUryrH self_grouprX _from_objectsrrrr rvUs rvc@sPeZdZdZdZdZdZdZdddZddZ dd d Z d d Z e d dZ dS)DefaultGeneratorz'Base class for column *default* values.default_generatorFNcC ||_dSr"rr6rrrr rwi zDefaultGenerator.__init__cC$||_|jr ||j_dS||j_dSr")rrrr rrrr rl  zDefaultGenerator._set_parentcKs"|durt|}|j|fi|Sr")r_execute_default)r6rr<rrr executesszDefaultGenerator.executecCs||||Sr")r)r6r multiparamsparamsrrr _execute_on_connectionxrz'DefaultGenerator._execute_on_connectioncCst|dddur |jjjSdS)z4Return the connectable associated with this default.rN)rrr%rrCrrr r{s zDefaultGenerator.bindrFr")rSrTrUrVrW is_sequenceis_server_defaultrrwrrrrXrrrrr r`s  rcseZdZdZfddZejddZejddZejdd Z eje d d d Z d dZ ddZ ee ZddZZS)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:`.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 sHtt|jdi|t|trtdt|r| |}||_ dS)aj"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:`.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:`.Connection` in use as well as the current statement and parameters. z4ColumnDefault may not be a server-side default type.Nr) rrrwr#rrr5rcallable_maybe_wrap_callablearg)r6rr<rrr rws    zColumnDefault.__init__cCs t|jSr")rrrrCrrr is_callable zColumnDefault.is_callablecCs t|jtSr")r#rrrCrrr is_clause_elementrzColumnDefault.is_clause_elementcCs|j o |j o |j Sr")rrrrCrrr is_scalars zColumnDefault.is_scalarzsqlalchemy.sql.sqltypescCs|jr t|jj|j SdSr)rr#rrNullType)r6sqltypesrrr _arg_is_typedszColumnDefault._arg_is_typedcsz tjdd}WntytfddYSw|ddur)t|dp*d}t|d|}|dkrAtfddS|d krGStd ) 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)no_selfcSr"rctxrrr rrz4ColumnDefault._maybe_wrap_callable..Nrcrr"rrrrr rrrzDColumnDefault Python function takes zero or one positional arguments)rget_callable_argspecrd wrap_callabler_rr5)r6rargspec defaulted positionalsrrr rs z"ColumnDefault._maybe_wrap_callablecCs|jrdSdS)Ncolumn_onupdatecolumn_defaultrrCrrr _visit_nameszColumnDefault._visit_namecCs d|jfS)NzColumnDefault(%r))rrCrrr rDrRzColumnDefault.__repr__)rSrTrUrVrwrrZrrr dependenciesrrrrXrWrDrrrrr rs  #    rcseZdZdZdZdZ               dfdd Zejdd Z ejd d Z e d d dZ fddZ ddZddZeddZdddZdddZddZZS)raRepresents 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` or :class:`.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:`.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:: :class:`.CreateSequence` :class:`.DropSequence` sequenceTNFcstt|j|dt|| |_||_||_||_||_||_ ||_ ||_ | |_ | |_ | |_| tur7d|_} n|durI| durI|jrI|j|_} nt| ||_||_t|| |_|ra||dSdS)aConstruct 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:`.MetaData` is also present are the same as that of :paramref:`.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 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 schema 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:`.MetaData` object which this :class:`.Sequence` will be associated with. A :class:`.Sequence` that is associated with a :class:`.MetaData` gains the following capabilities: * The :class:`.Sequence` will inherit the :paramref:`.MetaData.schema` parameter specified to the target :class:`.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:`.MetaData` object, if any. * The :meth:`.MetaData.create_all` and :meth:`.MetaData.drop_all` methods will emit CREATE / DROP for this :class:`.Sequence`, even if the :class:`.Sequence` is not associated with any :class:`.Table` / :class:`.Column` that's a member of this :class:`.MetaData`. The above behaviors can only occur if the :class:`.Sequence` is explicitly associated with the :class:`.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:`.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. rN)rrrwrrstart incrementminvaluemaxvalue nominvalue nomaxvaluecyclecacheorderoptionalrerrsr!_key _set_metadata)r6rrrrrrrrrrrrrHrsrurrrr rw s.    zSequence.__init__cCrvrrrCrrr r r>zSequence.is_callablecCrvrrrCrrr r r>zSequence.is_clause_elementzsqlalchemy.sql.functions.funccCs|j||jdS)zReturn a :class:`.next_value` function element which will render the appropriate increment function for this :class:`.Sequence` within any SQL expression. r) next_valuer)r6funcrrr r szSequence.next_valuecs tt||||jdSr")rrrr8rorrrr r szSequence._set_parentcCs||jdSr")rrs)r6rr%rrr ro rEzSequence._set_tablecCs||_||jj|j<dSr")rs _sequencesrrrrr r szSequence._set_metadatacCs|jr|jjSdSr"rrCrrr r sz Sequence.bindcCr)z&Creates this sequence in the database.Nrrrrrr r zSequence.createcCr)z&Drops this sequence from the database.Nrrrrrr r rz Sequence.dropcCrw)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.rxrCrrr ry s zSequence._not_a_column_expr)NNNNNNNNNNFNNNF)NT)rSrTrUrVrWrrwrrZrrrrrrorrXrrrryrrrrr rsF'       rc@sFeZdZdZdZdZdZdddZddZdd 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` TFcCrr"rrrrr rw rzFetchedValue.__init__cCs||jkr|S||Sr")r_clonerrrr r  s  zFetchedValue._as_for_updatecCs4|j|j}|j|j|jdd||_|S)Nr)rrbrIupdaterfr)r6rnrrr r s zFetchedValue._clonecCrr")rrrr rrrr r& rzFetchedValue._set_parentcCs t|Sr"rArCrrr rD- rzFetchedValue.__repr__NrF) rSrTrUrVr reflected has_argumentrwr rrrDrrrr r s  rcs.eZdZdZdZdfdd ZddZZS) r!a7A 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:`.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)Nrr) rassert_arg_typerrrrr!rwrr)r6rr _reflectedrrr rwI s  zDefaultClause.__init__cCsd|j|jfS)Nz DefaultClause(%r, for_update=%r))rrrCrrr rDQ rEzDefaultClause.__repr__)FF)rSrTrUrVrrwrDrrrrr r!1 s r!z0.6zy:class:`.PassiveDefault` is deprecated and will be removed in a future release. Please refer to :class:`.DefaultClause`.c@seZdZdZddZdS)PassiveDefaultz*A DDL-specified DEFAULT column value. cOstj|g|Ri|dSr")r!rw)r6rrrrrr rw^ szPassiveDefault.__init__N)rSrTrUrVrwrrrr rU s rc@sFeZdZdZdZ      d ddZeddZd d Zd d Z dS) ConstraintzA table-level SQL constraint.rNFcKs@||_||_||_|r||_||_||_t|||dS)aCreate 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 _create_rule: a callable which is passed the DDLCompiler object during compilation. Returns True or False to signal inline generation of this Constraint. The AddConstraint and DropConstraint DDL constructs provide DDLElement's more comprehensive "conditional DDL" approach that is passed a database connection when DDL is being issued. _create_rule is instead called during any CREATE TABLE compilation, where there may not be any transaction/connection in progress. However, it allows conditional compilation of the constraint even for backends which do not support addition of constraints through ALTER TABLE, which currently includes SQLite. _create_rule is used by some types to create constraints. Currently, its call signature is subject to change at any time. :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. N) rrOrPr? _create_rulerrr"r)r6rrOrPrr?rrSrrr rwg s4 zConstraint.__init__cCs6z t|jtr |jWSWn tyYnwtd)NzdThis constraint is not bound to a table. Did you mean to call table.append_constraint(constraint) ?)r#rLr[r3rrirCrrr r% s  zConstraint.tablecCs||_|j|dSr")rLrrr6rLrrr r szConstraint._set_parentcKstr")NotImplementedError)r6rrrrr rJ szConstraint.copy)NNNNNF) rSrTrUrVrWrwrXr%rrJrrrr rb s >  rcCs*t|dr |}t|tstd|S)NrHzschema.Column object expected)rrHr#r$rr5)elementrrr _to_schema_column s   rcCsF|dur|St|dr|}t|tjtfs!d}t|||S)NrHz1Element %r is not a string name or column element)rrHr#rrrrr5)rrtrrr _to_schema_column_or_string s rc@sDeZdZdZ dZddZeddZd ddZd d Z d d Z dS)ColumnCollectionMixinNFcOsP|dd}|dd|_t|_dd|D|_|r$|jr&|dSdSdS)N _autoattachTrFcSrr)rrrrr r sz2ColumnCollectionMixin.__init__..)rfrrr_pending_colargs _check_attach)r6rrrrrrr rw s   zColumnCollectionMixin.__init__ccs|D]:}d}d}t|dr|}t|ttfs|}ng}t|id|ji|r.|d}|dur4|n|}||||fVqdS)NrHrr)rrHr#rrrtraverser)rqrrstrnamercols add_elementrrr "_extract_col_expression_collection s z8ColumnCollectionMixin._extract_col_expression_collectionc sddjD}dd|D}t||r>|rJdtj|}|s>fdd}_D]}||q4dS|}dd|D}t|d krV|dSt|d krjs|d j fd d|d dD} | rt d d dd| Dj fdSdSdS)NcSsg|] }t|tr|qSr)r#r$rrrr r z7ColumnCollectionMixin._check_attach..cSsg|] }t|jtr|qSr)r#r%r[rrrr r r+z#Should not reach here on event callcs0t|tr|sjdddSdSdS)NT)r)r#r[discardr)rr%) cols_wo_tabler6rr _col_attached s  z:ColumnCollectionMixin._check_attach.._col_attachedcSsh|]}|jqSrr/rrrr  rz6ColumnCollectionMixin._check_attach..rrcsg|] }|jur|qSrr/rr/rr r rz(Column(s) %s are not part of table '%s'.rcss|]}d|VqdSz'%s'Nrrrrr r z6ColumnCollectionMixin._check_attach..)rr difference_cols_wo_tabler8r_r2rf_allow_multiple_tablesr%rr5rr) r6rcol_objs cols_w_tablehas_string_colsrr(rrgothersr)rr6r%r r s:     z#ColumnCollectionMixin._check_attachcsfdd|jDS)Ncs&g|]}t|tjrj|n|qSr)r#rrr'rr(r/rr r& sz:ColumnCollectionMixin._col_expressions..)rrrr/r _col_expressions% s z&ColumnCollectionMixin._col_expressionscCs(||D] }|dur|j|qdSr")rrr)r6r%r(rrr r+ s  z!ColumnCollectionMixin._set_parentrF) rSrTrUrrrw classmethodrrrrrrrr r s  0 rc@sNeZdZdZddZdZ ddZddZd d Zd d Z d dZ ddZ dS)ColumnCollectionConstraintz-A constraint that proxies a ColumnCollection.cOsH|dd}|dd}tj|fi|tj|g|R||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. rTrF)rrN)rfrrwr)r6rrrrrrrr rw4 s   z#ColumnCollectionConstraint.__init__NcCst||t||dSr")rrrrrrr rU  z&ColumnCollectionConstraint._set_parentcCs ||jvSr")r)r6rrrr __contains__Y rz'ColumnCollectionConstraint.__contains__cKs*|j|j|j|j|jd}||S)N)rrOrP)rrkeysrrOrPrM)r6rrr'rrr rJ\ s zColumnCollectionConstraint.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:`.ColumnCollection` of :class:`.Column` objects. )rcontains_columnr6r(rrr re s z*ColumnCollectionConstraint.contains_columncs|jjfddjDS)Nc3s|]}|VqdSr"r)rr& ordered_dictrr rt rz6ColumnCollectionConstraint.__iter__..)r_data_listrCrrr __iter__o sz#ColumnCollectionConstraint.__iter__cCs t|jjSr")r_rrrCrrr __len__v rRz"ColumnCollectionConstraint.__len__) rSrTrUrVrwrrrrJrrrrrrr r1 s  rcs\eZdZdZdZeddd        dfdd Zd d ZeeZdd d Z Z S)CheckConstraintzlA table- or column-level CHECK constraint. Can be included in the definition of a Table or Column. Tsqltextz:class:`.CheckConstraint`z$:paramref:`.CheckConstraint.sqltext`NFc sht|dd|_g} t|jid| jitt|j| |||||| |d| |dur2||dSdS)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:`.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 Tallow_coercion_to_textr)rrOrPrr?rrN) r rrrrrrrwr2) r6rrrOrPr%r?rrrrrrrrr rw s$.   zCheckConstraint.__init__cCst|jtrdSdS)Ncheck_constraintcolumn_check_constraint)r#rLr[rCrrr rW s zCheckConstraint.__visit_name__c KsL|dur t|j|j|}n|j}t||j|j|j|j|d|jd}| |S)NF)rrPrOrr%rr) r/rr%rrrPrOrrrM)r6r+rrrr'rrr rJ s zCheckConstraint.copy)NNNNNNTFr") rSrTrUrVrr rwrWrXrJrrrrr rz s(<rc@seZdZdZdZ          dddZddZdZ dZ e d d Z e d d Z e d dZ ddZ e ddZe ddZddZdddZdS)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:`.ForeignKey` to the definition of a :class:`.Column` is a shorthand equivalent for an unnamed, single column :class:`.ForeignKeyConstraint`. Examples of foreign key configuration are in :ref:`metadata_foreignkeys`. foreign_key_constraintNFc  stjf|||| d| |_|_| _|_| _tt|t|kr;tt|t|kr6t dt dfdd|D_ t jg|R| duret dr^| jus^J| dSdS)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:`.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:`.MetaData.create_all` and :meth:`.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:`.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 )rrOrPr?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)) r>rrrNrMr5rQrOrP) r?rrrNrMr5rQrOrPdialect_kwargs)rrefcolrCrr re s$ z1ForeignKeyConstraint.__init__..NrL)rrwrrNr5rMrQr_rrr5elementsrrrLr2)r6r refcolumnsrrrNrOrPrMr5rQr%r?rSrrCr rw s@V  zForeignKeyConstraint.__init__cCs|j||j|dSr")rrrrr'rrr rs| rz$ForeignKeyConstraint._append_elementcCstt|j|jSr")r OrderedDictzip column_keysrrCrrr _elements zForeignKeyConstraint._elementscCs|jD]}|jSdSr")rr)r6elemrrr r s  z%ForeignKeyConstraint._referred_schemacCs|jdjjS)a^The :class:`.Table` object to which this :class:`.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%rCrrr referred_table s z#ForeignKeyConstraint.referred_tablecCs^tdd|jD}d|vr+t|dkr-t|dd\}}td|j|j||fdSdS)NcSsg|]}|qSr)rZ)rrrrr r rz=ForeignKeyConstraint._validate_dest_table..rrrzJForeignKeyConstraint on %s(%s) refers to multiple remote tables: %s and %s)rrr_rrr5r_col_description)r6r% table_keyselem0elem1rrr rp sz)ForeignKeyConstraint._validate_dest_tablecCs$t|dr |jSdd|jDS)aReturn a list of string keys representing the local columns in this :class:`.ForeignKeyConstraint`. This list is either the original string arguments sent to the constructor of the :class:`.ForeignKeyConstraint`, or if the constraint has been initialized with :class:`.Column` objects, is the string .key of each element. .. versionadded:: 1.0.0 rLcSs$g|]}t|tr |jnt|qSr)r#rr&strrrrr r sz4ForeignKeyConstraint.column_keys..)rrrrrCrrr r s z ForeignKeyConstraint.column_keyscCs d|jS)Nr)rrrCrrr r rz%ForeignKeyConstraint._col_descriptionc Cst||zt||Wnty'}z td|j|jdfd}~wwt|j |j D]\}}t |dr=|j |urB| |q/||dS)NzQCan't create ForeignKeyConstraint on table '%s': no column named '%s' is present.rrL)rrrKeyErrorrr5rr7rrrrrLr2rp)r6r%ker(r(rrr r s  z ForeignKeyConstraint._set_parentc svtdd|jDfdd|jD|j|j|j|j|j|j|j|j d }t |j|jD] \}}| |q,| |S)NcSsg|]}|jjqSr)rLr&rrrr r rz-ForeignKeyConstraint.copy..cs:g|]}|jdur||jjjkrjnddqS)N)rrV)rTrZrLr%r&rrrrr r s)rrrNrMrOrPr5rQ) rrrrrNrMrOrPr5rQrrM)r6rr+rrrself_fkother_fkrrr rJ s"    zForeignKeyConstraint.copy) NNNNNFFNNNrt)rSrTrUrVrWrwrsrrrXrrrrprrrrJrrrr r sB        rcsZeZdZdZdZfddZfddZddZd d Ze d d Z e j d dZ ZS)ra A table-level PRIMARY KEY constraint. The :class:`.PrimaryKeyConstraint` object is present automatically on any :class:`.Table` object; it is assigned a set of :class:`.Column` objects corresponding to those marked with the :paramref:`.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:`.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:`.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:`.Table` itself; columns marked as ``primary_key=True`` will be gathered into the empty constraint's column collection. primary_key_constraintcs(|dd|_tt|j|i|dS)NrxF)rfrxrrrw)r6rrrrrr rwF szPrimaryKeyConstraint.__init__c stt|||j|ur|j|j||_|j|dd|jD}|jra|rat |t |j krat d|j ddd|Dddd|jDddd|jDfg|dd<|jD]}d |_d |_qd|j|dS) NcSsg|]}|jr|qSr)rrrrr rR 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 releasercs|]}d|jVqdSrrrrrr r_ z3PrimaryKeyConstraint._set_parent..csr rrrrrr r` r csr rrrrrr ra r TF)rrrrrrrr'rrvaluesrrrrr extend)r6r% table_pksr'rrr rJ s2   z PrimaryKeyConstraint._set_parentcCs8|D]}d|_q|j|tj|||jdS)aDrepopulate 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:`.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)rrr rr_resetr2r%)r6rr(rrr _reloadk s   zPrimaryKeyConstraint._reloadcCstj||j|dSr")rrrrr,rrrr r0 rzPrimaryKeyConstraint._replacecs2|jdurgfdd|jDSt|jS)Ncsg|]}|ur|qSrrrautoincrr r rEz>PrimaryKeyConstraint.columns_autoinc_first..)rrrrCrrr columns_autoinc_first s z*PrimaryKeyConstraint.columns_autoinc_firstcCsdd}t|jdkr.t|jd}|jdur||d|S|jdvr*||dr,|SdSdSd}|jD]}|jdurP||d|durNtd|j|jf|}q3|S) NcSs|jjdust|jjtjjs|rtd|j|fdSt|jtdt fs+|s+dS|j dur4|s4dS|j r>|j dvr>dSdS)NzGColumn type %s on column '%s' is not compatible with autoincrement=TrueF)T ignore_fkT) r_type_affinity issubclassr INTEGERTYPErr5r#r rr rr)r( autoinc_truerrr _validate_autoinc s( zEPrimaryKeyConstraint._autoincrement_column.._validate_autoincrrT)rrFzGOnly one Column may be marked autoincrement=True, found both %s and %s.)r_rrrrr5r)r6rr(rrrr r s0       z*PrimaryKeyConstraint._autoincrement_column)rSrTrUrVrWrwrrr0rXrrrZrrrrrr r sI  ! rc@seZdZdZdZdS)r1aA 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. unique_constraintN)rSrTrUrVrWrrrr r1 sr1c@sLeZdZdZdZddZddZeddZdd d Z dd d Z ddZ d S)rad 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:`.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:`.Column` objects:: Index("some_index", func.lower(sometable.c.name)) An :class:`.Index` can also be manually associated with a :class:`.Table`, either through inline declaration or using :meth:`.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:`.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:`.text` construct may be used to specify :class:`.Index` expressions, provided the :class:`.Index` is explicitly associated with the :class:`.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. rc Osd|_}g}g}||D]\}}} } || ||q||_t||dd|_|dd|_|dd} d|vrC|d|_d|vrL|d}| |t j |g|Rd| i|durh| |dSdS)a~Construct 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:`.Column`, but may also be arbitrary SQL expressions which ultimately refer to a :class:`.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:`.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) r%rrrrrfrrr?rrrwr) r6rrrrr%rprocessed_expressionsrrrrrrrr rw%s<       zIndex.__init__cCst|||jdur||jurtd|j|jj|jf||_|j||j }| |}t |t |ks9Jddt ||D|_ dS)NzKIndex '%s' is against table '%s', and cannot be associated with table '%s'.cSs"g|] \}}t|tr |n|qSr)r#r)rrcolexprrrr rxsz%Index._set_parent..) rrr%rr5rrrrrrr_r)r6r%rcol_expressionsrrr ris    zIndex._set_parentcCrG)z2Return the connectable associated with this Index.)r%rrCrrr r}sz Index.bindNcCs"|durt|}|tj||S)zIssue a ``CREATE`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`.MetaData.create_all`. Nrrrrr rs z Index.createcCs"|durt|}|tj|dS)zIssue a ``DROP`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`.MetaData.drop_all`. Nrrrrr rs z Index.dropcCs6ddt|jgdd|jD|jrdgpgS)Nz Index(%s)rcSrrr)rerrr rrz"Index.__repr__..z unique=True)rrrrrrCrrr rDs zIndex.__repr__r") rSrTrUrVrWrwrrXrrrrDrrrr r sHD    rixzix_%(column_0_label)sc@seZdZdZdZejdd      d-ddZdZ d d Z d d Z d dZ ddZ ddZ ddZddZddZedddZeeeZddZddZed d!Z      " "d.d#d$Zed%d&d'd(Zd/d)d*Zd/d+d,ZdS)0MetaDataaA collection of :class:`.Table` objects and their associated schema constructs. Holds a collection of :class:`.Table` objects as well as an optional binding to an :class:`.Engine` or :class:`.Connection`. If bound, the :class:`.Table` objects in the collection and their columns may participate in implicit SQL execution. The :class:`.Table` objects themselves are stored in the :attr:`.MetaData.tables` dictionary. :class:`.MetaData` is a thread-safe object for read operations. Construction of new tables within a single :class:`.MetaData` object, either explicitly or via reflection, may not be completely thread-safe. .. seealso:: :ref:`metadata_describing` - Introduction to database metadata rs)z0.8zThe :paramref:`.MetaData.reflect` flag is deprecated and will be removed in a future release. Please use the :meth:`.MetaData.reflect` method.)reflectNFcCspt|_t|||_|r|nt|_|r||_t|_ i|_ t t |_||_|r6|s0td|dSdS)aCreate 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 create_engine() and this MetaData will be bound to the resulting engine. :param reflect: Optional, automatically load all tables from the bound database. Defaults to False. ``bind`` is required when this option is set. :param schema: The default schema to use for the :class:`.Table`, :class:`.Sequence`, and potentially other objects associated with this :class:`.MetaData`. Defaults to ``None``. When this value is set, any :class:`.Table` or :class:`.Sequence` which specifies ``None`` for the schema parameter will instead have this schema name defined. To build a :class:`.Table` or :class:`.Sequence` that still has ``None`` for the schema even when this parameter is present, use the :attr:`.BLANK_SCHEMA` symbol. .. note:: As referred above, the :paramref:`.MetaData.schema` parameter only refers to the **default value** that will be applied to the :paramref:`.Table.schema` parameter of an incoming :class:`.Table` object. It does not refer to how the :class:`.Table` is catalogued within the :class:`.MetaData`, which remains consistent vs. a :class:`.MetaData` collection that does not define this parameter. The :class:`.Table` within the :class:`.MetaData` will still be keyed based on its schema-qualified name, e.g. ``my_metadata.tables["some_schema.my_table"]``. The current behavior of the :class:`.ForeignKey` object is to circumvent this restriction, where it can locate a table given the table name alone, where the schema will be assumed to be present from this value as specified on the owning :class:`.MetaData` collection. However, this implies that a table qualified with BLANK_SCHEMA cannot currently be referred to by string name from :class:`.ForeignKey`. Other parts of SQLAlchemy such as Declarative may not have similar behaviors built in, however may do so in a future release, along with a consistent method of referring to a table in BLANK_SCHEMA. .. seealso:: :paramref:`.Table.schema` :paramref:`.Sequence.schema` :param quote_schema: Sets the ``quote_schema`` flag for those :class:`.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:`.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:`.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:`.Table` object associated with the constraint. * ``%(referred_table_name)s`` - the name of the :class:`.Table` object associated with the referencing target of a :class:`.ForeignKeyConstraint`. * ``%(column_0_name)s`` - the name of the :class:`.Column` at index position "0" within the constraint. * ``%(column_0N_name)s`` - the name of all :class:`.Column` objects in order within the constraint, joined without a separator. * ``%(column_0_N_name)s`` - the name of all :class:`.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:`.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:`.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:`.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. z8A bind must be supplied in conjunction with reflect=TrueN)r immutabledictrgrrDEFAULT_NAMING_CONVENTIONnaming_conventionr?r_schemasr collections defaultdictrr4rrr5r )r6rr rrur#r?rrr rws( '   zMetaData.__init__cCs d|jS)NzMetaData(bind=%r)rrCrrr rDrzMetaData.__repr__cCst|tjs |j}||jvSr")r#rrr&rg)r6 table_or_keyrrr rs  zMetaData.__contains__cCs2t||}t|j|||r|j|dSdSr")r!dict __setitem__rgr$r)r6rrr%r&rrr rls zMetaData._add_tablecCs`t||}t|j|d}|dur|jD]}||q|jr.tdd|jD|_dSdS)NcSsg|] }|jdur|jqSr"r)rtrrr rs  z*MetaData._remove_table..) r!r(rfrgrrrr$rr )r6rrr&removedr(rrr rps    zMetaData._remove_tablecCs|j|j|j|j|j|jdS)N)rgrschemas sequencesfk_memosr#)rgrr$rr4r#rCrrr __getstate__szMetaData.__getstate__cCsF|d|_|d|_|d|_d|_|d|_|d|_|d|_dS)Nrgrr#r-r,r.)rgrr#_bindrr$r4)r6staterrr __setstate__s     zMetaData.__setstate__cCs |jduS)z:True if this MetaData is bound to an Engine or Connection.Nr0rCrrr is_bounds zMetaData.is_boundcCr)a An :class:`.Engine` or :class:`.Connection` to which this :class:`.MetaData` is bound. Typically, a :class:`.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" r3rCrrr rsz MetaData.bindsqlalchemy.engine.urlcCs.t|tj|jfrt||_dS||_dS)z;Bind this MetaData to an Engine, Connection, string or URL.N)r#rrURL sqlalchemy create_enginer0)r6urlrrrr _bind_tos zMetaData._bind_tocCs$t|j|j|jdS)z+Clear all Table objects from this MetaData.N)r(clearrgr$r4rCrrr r;s  zMetaData.clearcCs||j|jdS)z1Remove the given Table object from this MetaData.N)rprrrrrr rrzMetaData.removecCstt|jdddS)aReturns a list of :class:`.Table` objects sorted in order of foreign key dependency. The sorting will place :class:`.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:`.sorted_tables` accessor cannot by itself accommodate automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. To resolve these cycles, either the :paramref:`.ForeignKeyConstraint.use_alter` parameter may be applied to those constraints, or use the :func:`.schema.sort_tables_and_constraints` function which will break out foreign key constraints involved in cycles separately. .. seealso:: :func:`.schema.sort_tables` :func:`.schema.sort_tables_and_constraints` :attr:`.MetaData.tables` :meth:`.Inspector.get_table_names` :meth:`.Inspector.get_sorted_table_and_fkc_names` cSrr"r)r*rrr rrz(MetaData.sorted_tables..r)r sort_tablesrrgr rCrrr sorted_tabless#zMetaData.sorted_tablesTc s|durt}|} d| ||td} | |dur#jdur+| d<t|jj| d|rB|j | durStfddD} n} tj durlfddt | D} n@t rfd dt | D} n+fd dD} | rrd pd }td |j|d| ffddD} | D])}z t|fi| Wqtjy}ztd||fWYd}~qd}~wwWddS1swYdS)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. :param schema: Optional, query and reflect tables from an alternate schema. If None, the schema associated with this :class:`.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:`.Table` as :paramref:`.Table.extend_existing`. .. versionadded:: 0.9.1 :param autoload_replace: Passed along to each :class:`.Table` as :paramref:`.Table.autoload_replace`. .. versionadded:: 0.9.1 :param resolve_fks: if True, reflect :class:`.Table` objects linked to :class:`.ForeignKey` objects located in each :class:`.Table`. For :meth:`.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:`.ForeignKey` objects are not followed to the :class:`.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:`.ForeignKey` object will still resolve to its related :class:`.Table` after the :meth:`.MetaData.reflect` operation is complete. Defaults to True. .. versionadded:: 1.3.0 .. seealso:: :paramref:`.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:`.Table` objects reflected. NT)r{rzr_r|r~r}r)rcsg|]}d|fqS)ryrrrrrr rrEz$MetaData.reflect..cs g|] \}}s |vr|qSrrrrschnamecurrentr_rr rscs*g|]\}}s |vr|r|qSrrr?)rBr_onlyr6rr rscsg|]}|vr|qSrrr>) availablerr rrEz schema '%s'rzACould not reflect: requested table(s) not available in %r%s: (%s)rcsg|] }s |vr|qSrrr>rArr rszSkipping table %s: %s)rconnectrrrr OrderedSetengine table_namesrget_view_namesrgrrrrirr[UnreflectableTableErrorr)r6rrviewsrCr_r|r~rconn reflect_optsavailable_w_schemaloadmissingsruerrr)rDrBr_rCrr6r r slW      "zMetaData.reflectr\zthe :meth:`.MetaData.append_ddl_listener` method is deprecated and will be removed in a future release. Please refer to :class:`.DDLEvents`.cs*fdd}t|d|dd|dS)z.adapt_listenerrrrNrrrrSr rs zMetaData.append_ddl_listenercC(|durt|}|jtj|||ddS)ayCreate 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. :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. Nrrgrr6rrgrrrr create_all   zMetaData.create_allcCrT)atDrop 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. :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. NrUrrVrrr drop_allrXzMetaData.drop_all)NFNNNN)NNFNFTT)NNT)rSrTrUrVrWrrrwrgrDrrlrpr/r2r4rrr:rXr;rr=r rYrrWrYrrrr rs^  5      (   rcsXeZdZdZdZfddZddZeddd 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``. rscs$tj|_i|_tt|dS)z Construct a ThreadLocalMetaData.N)r threadinglocalcontext_ThreadLocalMetaData__enginesrrZrwrCrrr rw s 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)rr]rCrrr rszThreadLocalMetaData.bindr5cCszt|tj|jfr-z |j||j_WdSty,t |}||j|<||j_YdSw||jvr7||j|<||j_dS)z-Bind to a Connectable in the caller's thread.N) r#rrr6r^r]r_rr7r8)r6r9rrrrr r:s      zThreadLocalMetaData._bind_tocCst|jdo |jjduS)z(True if there is a bind for this thread.r_N)rr]r_rCrrr r4.s  zThreadLocalMetaData.is_boundcCs&|jD] }t|dr|qdS)z2Dispose all bound engines, in all thread contexts.disposeN)r^r rr`)r6rrrr r`5s  zThreadLocalMetaData.dispose)rSrTrUrVrWrwrrrr:rXr4r`rrrrr rZs   rZc@s2eZdZdZdZedZddZe ddZ dS) _SchemaTranslateMapaProvide translation of schema names based on a mapping. Also provides helpers for producing cache keys and optimized access when no mapping is present. Used by the :paramref:`.Connection.execution_options.schema_translate_map` feature. .. versionadded:: 1.1 )rP__call__hash_key is_defaultrcsf_dur'fdd}|_dfddttdD_d_dSd_j_d _dS) Ncs|}||}|Sr")_default_schema_getterrQ)objrOrPr6rr schema_for_objectSs z7_SchemaTranslateMap.__init__..schema_for_object;c3s |] }d||fVqdS)rNrr)rPrr r[s z/_SchemaTranslateMap.__init__..rFrT)rPrbrrrrcrdre)r6rPrhrrgr rwOs   z_SchemaTranslateMap.__init__cCs"|durtSt|tr |St|Sr")_default_schema_mapr#ra)rqrPrrr _schema_getterds  z"_SchemaTranslateMap._schema_getterN) rSrTrUrV __slots__operator attrgetterrerwrrkrrrr ra=s rac@sDeZdZdZdZeddddddZd d Zd d Zdd dZ dS)r<a Defines 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:`.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` computed_columnrz:class:`.Computed`z:paramref:`.Computed.sqltext`NcCst|dd|_||_d|_dS)aConstruct a GENERATED ALWAYS AS DDL construct to accompany a :class:`.Column`. :param sqltext: A string containing the column generation expression, which will be used verbatim, or a SQL expression construct, such as a :func:`.text` object. If given as a string, the object is converted to a :func:`.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 databse 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``. TrN)r r persistedr)r6rrprrr rws zComputed.__init__cCsRt|jtdtfrt|jtdtfstd||_||_||j_||j_dS)NzPA generated column cannot specify a server_default or a server_onupdate argument) r#r rr<rrr5rrrrrr rs zComputed._set_parentcCs|Sr"rrrrr r rzComputed._as_for_updatecKs8|dur t|j|j|}n|j}t||jd}||S)N)rp)r/rr%r<rprM)r6r+rrrgrrr rJs  z Computed.copyr") rSrTrUrVrWr rwrr rJrrrr r<rs   r<)DrV __future__rr%rmr7rrrrbaserrr r rr r r rrrrrrBrrrrrsymbolrrer!r/_self_inspects Visitabler0r[r$r?rarvrrrrr!deprecated_clsrrrrrrrrrr1rr!r"rrZrarjrkr<rrrr s                        D`vg $w3$W eIcU QQC1