U kfԀ@s(UdZddlmZddlmZddlZddlmZddlZddl Z ddl m Z ddl m Z ddl m Z dd l m Z dd l mZdd l mZdd l mZdd l mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddl#m$Z$ddl#m%Z%dd l#m&Z&dd!l#m'Z'dd"l#m(Z(dd#l#m)Z)dd$l#m*Z*dd%l#m+Z+dd&l#m,Z,dd'lm-Z-dd(l.m/Z/dd)l.m0Z0dd*l.m1Z1dd+l.m2Z2dd,l.m3Z3dd-l4m5Z5dd.l!m6Z6dd/l"m7Z7d0d1lm8Z8d0d2lm9Z9d0d3lm:Z:d0d4lm;Z;d0d5l;mZ>d0d7l=m?Z?d0d8l=m@Z@d0d9l=mAZAd0d:l=mBZBd0d;l=mCZCe jrddlDmGZGdd?lDmHZHdd@lDmIZIddAl#mJZJddBlKmLZLddCl.mMZMddDlNmOZOddEl!mPZPddFl"mQZQd0dGlRmSZSd0dHlRmTZTd0dIlUmVZVd0dJlUmWZWd0dKlUmXZXd0dLlYmZZZd0dMl[m\Z\d0dNl]m^Z^edOdPdQZ_edRdSdQZ`edTdUdQZaedVZbeeece&fZdedWece3e1e fZeeeZfGdXdYdYeZgegjhZhdZeid[<egjjZjd\eid]<egjkZkd^eid_<d`dad`dbdcddZldedfdfdedgdhdiZme:jnGdjdSdSe,e"joZpGdkdldlZqGdmdndnepZrGdodUdUe*ere5e:jsdUZtGdpdqdqe*epe0e_ZudddrdsdadtdudvdwdxdydzZvGd{d|d|e*epZwer(d}d~dddZxd}ddddZyd}ddddZzne{dZxe{dZye{dZzGddde+epZ|Gddde|eZ}Gddde}Z~Gddde}ZedZGddde}ZGddde@ZGddde}ZGdddZGddderee|Ze:jnGddWdWe,ZGdddeZGddde*eqepZGdddZGdddeeZGdddeZGdddeZGdddeZGdddeZGddde*eeqepZe eetgecfZeecefZGdddeBddZeeee effZe;ddiZdeid<GddderZGdddeepZGdddeeepZdS)a/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. ) annotations)ABCN)Enum)Any)Callable)cast) Collection)Dict)Iterable)Iterator)List)Mapping)NoReturn)Optional)overload)Sequence)Set)Tuple) TYPE_CHECKING)TypeVar)Union) coercions)ddl)roles)type_api)visitors)_DefaultDescriptionTuple)_NoArg) _NoneName)_SentinelColumnCharacterization) _SentinelDefaultCharacterization)DedupeColumnCollection) DialectKWArgs) Executable)SchemaEventTarget)_document_text_coercion) ClauseElement) ColumnClause) ColumnElement) quoted_name) TextClause) TableClause) to_instance)ExternallyTraversible)event)exc) inspection)util) HasMemoized)Final)Literal)Protocol)Self) TypedDict) TypeGuard)_AutoIncrementType)_DDLColumnArgument) _InfoType)_TextCoercedExpressionArgument)_TypeEngineArgument)ReadOnlyColumnCollection) DDLCompiler) BindParameter)Function) TypeEngine)anon_map) Connection)Engine)_CoreMultiExecuteParams)CoreExecuteOptionsParameter)ExecutionContext)MockConnection)_ReflectionInfo) FromClause_Tr)bound_SI SchemaItem_TABTable)rGrFrK FetchedValuec@seZdZdZdZdZdS) SchemaConstrr/N)__name__ __module__ __qualname__ RETAIN_SCHEMA BLANK_SCHEMANULL_UNSPECIFIEDr]r]E/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/sql/schema.pyrUsrUz)Final[Literal[SchemaConst.RETAIN_SCHEMA]]rZz(Final[Literal[SchemaConst.BLANK_SCHEMA]]r[z,Final[Literal[SchemaConst.NULL_UNSPECIFIED]]r\str Optional[str]nameschemareturncCs|dkr |S|d|SdS)N.r])rbrcr]r]r^_get_table_keysrfColumnElement[Any]Optional[Table]) expression source_table target_tablerdcsL|dks|dkr|S||ddddfdd }tttt|i|S)Nr.rzOptional[ExternallyTraversible])elementkwrdcs4t|tr,|jkr,|jjkr,j|jSdSdSN) isinstanceColumntablekeyc)rlrmZfixed_source_tableZfixed_target_tabler]r^replaces  z!_copy_expression..replace)rr)rrZreplacement_traverse)rirjrkrur]rtr^_copy_expressions  rvc@s`eZdZdZdZdZddddddZd d d d Zej d d ddZ dddddZ dZ dS)rQz3Base class for items that define a database schema. schema_itemdefaultrNoneargsrmrdc Osb|D]X}|dk rz |j}Wn4tk rN}ztd||W5d}~XYqX||f|qdS)z7Initialize the list of child items for this SchemaItem.NzH'SchemaItem' object, such as a 'Column' or a 'Constraint' expected, got )_set_parent_with_dispatchAttributeErrorr1 ArgumentError)selfr{rmitemZspwderrr]r]r^ _init_itemss zSchemaItem._init_itemsr_rdcCstj|dgdS)Ninfo)Z omit_kwargr3Z generic_reprrr]r]r^__repr__szSchemaItem.__repr__r=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`. r]rr]r]r^rs zSchemaItem.inforP)rwrdcCs(d|jkr|j|_|j|j|S)Nr)__dict__rcopydispatch_update)rrwr]r]r^_schema_item_copys  zSchemaItem._schema_item_copyTN) rWrXrY__doc____visit_name__Zcreate_drop_stringify_dialectrrr3memoized_propertyrrZ_use_schema_mapr]r]r]r^rQs c@s4eZdZUdZdZded<d ddddd d d ZdS) HasConditionalDDLzdefine a class that includes the :meth:`.HasConditionalDDL.ddl_if` method, allowing for conditional rendering of DDL. Currently applies to constraints and indexes. .. versionadded:: 2.0 NzOptional[ddl.DDLIf]_ddl_ifr`zOptional[ddl.DDLIfCallable] Optional[Any]r8)dialect callable_staterdcCst||||_|S)aapply a conditional DDL rule to this schema item. These rules work in a similar manner to the :meth:`.ExecutableDDLElement.execute_if` callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as :class:`.CreateTable`. :meth:`.HasConditionalDDL.ddl_if` currently applies towards the :class:`.Index` construct as well as all :class:`.Constraint` constructs. :param dialect: string name of a dialect, or a tuple of string names to indicate multiple dialect types. :param callable\_: a callable that is constructed using the same form as that described in :paramref:`.ExecutableDDLElement.execute_if.callable_`. :param state: any arbitrary object that will be passed to the callable, if present. .. versionadded:: 2.0 .. seealso:: :ref:`schema_ddl_ddl_if` - background and usage examples )rZDDLIfr)rrrrr]r]r^ddl_ifs"zHasConditionalDDL.ddl_if)NNN)rWrXrYrr__annotations__rr]r]r]r^rs  rc@seZdZUdZded<dS) HasSchemaAttrz1schema item that includes a top-level schema namer`rcN)rWrXrYrrr]r]r]r^r5s rcseZdZUdZdZer>ejddddZejdddd Z d e d <d e d <de d<de d<erejddddZ ejddddZ ejddddZ ddddddZejsejdd d!d!d!d"d#d$Zed!d!d!d"d%d&Zd'd'd'd'd(d)d)d(d'd(d'd'd'd'd'd(d*d+d,d-d.d/d/d0d1d1d1d1d2d1d3d4d5d6d7d1d!d8d9fd:d;Zdd,d=d2d>d1d7d?d8d@dAdBZedCddDdEZedFddGdHZd!d!d8dIdJdKZd!d8dLdMdNZd8ddOdPZd8ddQdRZejdSddTdUZejdVddWdXZedSddYdZZ ed+dd[d\Z!d+dd]d^Z"d+dd_d`Z#dd8dadbdcZ$dddd1d8dedfdgZ%dhd8didjdkZ&dld!d8dmdndoZ'ddpd1d8dqdrdsZ(ddpd1d8dqdtduZ)e*dvdwe+d'd'fd,dxdyd3ddzd{d|Z,e+d'd'fd,dxdyd3ddzd}d~Z-Z.S)rSaRepresent 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 rqPrimaryKeyConstraintrcCsdSrnr]rr]r]r^ primary_key[szTable.primary_keySet[ForeignKey]cCsdSrnr]rr]r]r^ foreign_keys^szTable.foreign_keys#DedupeColumnCollection[Column[Any]]_columnsOptional[Column[Any]]_sentinel_columnSet[Constraint] constraintsz Set[Index]indexes*ReadOnlyColumnCollection[str, Column[Any]]cCsdSrnr]rr]r]r^columnssz Table.columnscCsdSrnr]rr]r]r^exported_columnsszTable.exported_columnscCsdSrnr]rr]r]r^rsszTable.crEzList[BindParameter[Any]]zTuple[Any, ...])rE bindparamsrdcCs|jr|f|jS|fSdSrn)Z _annotationsZ_annotations_cache_key)rrErr]r]r^_gen_cache_keys zTable._gen_cache_key)1.4z8Deprecated alias of :paramref:`_schema.Table.must_exist`) mustexistrrzcOs |j||Srn)_new)clsr{rmr]r]r^__new__sz Table.__new__c 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 | d |j | } |r| j||| S| r.t d | dt|} | j| ||||| z0| j||f|ddi|| j| || WStk rt|||W5QRXYnXdS)Nrrr/zJTable() takes at least two positional-only arguments 'name' and 'metadata'rc keep_existingFextend_existingz9keep_existing and extend_existing are mutually exclusive. must_existrTable 'z' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.z ' not defined_no_init)objectr IndexError TypeErrorgetrcr[r1r~poprftablesboolInvalidRequestError_init_existingrZbefore_parent_attach _add_table__init__after_parent_attach Exceptionr3Z safe_reraise _remove_table) rr{rmrbmetadatarcrrmsgrrrrqr]r]r^rsR $            z Table._newNTF)rcquote quote_schema autoload_withautoload_replacerr resolve_fksinclude_columnsimplicit_returningcommentr listenersprefixes _extend_onrr_MetaDatarQ7Optional[Union[str, Literal[SchemaConst.BLANK_SCHEMA]]]Optional[bool]z#Optional[Union[Engine, Connection]]rzOptional[Collection[str]]r`zOptional[Dict[Any, Any]]z:Optional[_typing_Sequence[Tuple[str, Callable[..., Any]]]]zOptional[_typing_Sequence[str]]zOptional[Set[Table]]ry)rbrr{rcrrrrrrrrrrrrrrrrmrdcsf|rdStt||||_|dkr2|j|_n.|tkrBd|_n|}t|tsTtt|||_d|_ t |_ t |_ t dd|t |_t |_|jdk rd|j|jf|_n|j|_| |_|dd}| |_|dk r||_|dk r|D]\}}t|||q|r|ng|_|jf||dk rD|j||| ||| d|j|| pX|pX|iddS)a6Constructor for :class:`_schema.Table`. :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:`.Connection` or :class:`.Engine`. :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_replace: Defaults to ``True``; when using :paramref:`_schema.Table.autoload_with` 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_with` :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. .. seealso:: :ref:`metadata_reflection_toplevel` :meth:`_events.DDLEvents.column_reflect` :ref:`metadata_reflection_dbagnostic_types` :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_with` 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_with`, :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_with` :paramref:`_schema.Table.autoload_replace` :paramref:`_schema.Table.keep_existing` :param implicit_returning: True by default - indicates that RETURNING can be used, typically by the ORM, in order to fetch server-generated values such as primary key values and server side defaults, on those backends which support RETURNING. In modern SQLAlchemy there is generally no reason to alter this setting, except for some backend specific cases (see :ref:`mssql_triggers` in the SQL Server dialect documentation for one such example). :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_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. .. note:: setting this flag to ``False`` will not provide case-insensitive behavior for table reflection; table reflection will always search for a mixed-case name in a case sensitive fashion. Case insensitive names are specified in SQLAlchemy only by stating the name with all lower case characters. :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`. 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. NT)_implicit_generated%s.%s _reflect_info)rrrallow_replacements all_names)superrr*rrcr[ror_AssertionErrorrsetrrrr|r_extra_dependenciesrbfullnamerrrrr0listen _prefixes _extra_kwargs _autoloadr)rrbrrcrrrrrrrrrrrrrrrr{rmrevtfn __class__r]r^rsjD         zTable.__init__r]Union[Engine, Connection]zCollection[str]z_ReflectionInfo | None)rrrexclude_columnsrrrrdc Cs8t|}|} | j||||||dW5QRXdS)Nrr)r2inspect_inspection_contextZ reflect_table) rrrrrrrrinspZ conn_inspr]r]r^rms  zTable._autoloadzList[Constraint]cCst|jdddS)zTReturn the set of constraints as a list, sorted by creation order. cSs|jSrn)_creation_order)rsr]r]r^z+Table._sorted_constraints..rr)sortedrrr]r]r^_sorted_constraintsszTable._sorted_constraintszSet[ForeignKeyConstraint]cCsdd|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` cSsh|]}|jdk r|jqSrn) constraint).0fkcr]r]r^ s z0Table.foreign_key_constraints..)rrr]r]r^foreign_key_constraintsszTable.foreign_key_constraints)r{kwargsrdc Os|dd}|d|dk }|dd}|dd}|dd}|dd}|dd } |d d } | slt| rtt|r||jkrtd |jd |d |dd} | dk r|jD]} | j| kr|j| q|dd} dD]}||krtdq|d|j |_ |d|j |_ |d|j |_ |rf|sHdd|jD}nd}|j |j || || ||ddd|jD}|jf||j|d|ddS)NrautoloadrTrcrrrFrz,Can't change schema of existing table from 'z' to ''rr)rrz2Can't redefine 'quote' or 'quote_schema' argumentsrrrcSsg|] }|jqSr]rbrrsr]r]r^ sz(Table._init_existing..r]rcSsi|] }|j|qSr]rrr]r]r^ sz(Table._init_existing..r)rrrcr1r~rsrbrremoverrrrrrr)rr{rrrrrcrrrrrrsrrrrrr]r]r^rs^             zTable._init_existingrrdcKs||dSrn_validate_dialect_kwargsrrr]r]r^rszTable._extra_kwargscCsdSrnr]rr]r]r^_init_collectionsszTable._init_collectionscCsdSrnr]rr]r]r^_reset_exportedszTable._reset_exportedOptional[Column[int]]cCs|jjSrn)r_autoincrement_columnrr]r]r^rszTable._autoincrement_columnr c Csd}d}d}|j}|dk r$|f}d}|j}|rH||krH|dk sBtd}n|dkrb|dk rb|f}d}tj}|r|d}|jr|jjr|rtdq|rd}d}d}ntj }n|j dkr|j dkr|j rtd|dtj }n|j dk rR|j jrtj}nRt|j r@|j jr8|r&tdn|r4d}d}d}tj}n|j jrtj}n.|j dk r|rztd|dd tj}|dkr|jr|dkst|jD]*}|j dk s|j r|j jsqqt|j}tj}t||||S) adetermine a candidate column (or columns, in case of a client generated composite primary key) which can be used as an "insert sentinel" for an INSERT statement. The returned structure, :class:`_SentinelColumnCharacterization`, includes all the details needed by :class:`.Dialect` and :class:`.SQLCompiler` to determine if these column(s) can be used as an INSERT..RETURNING sentinel for a particular database dialect. .. versionadded:: 2.0.10 FNTrzQCan't use IDENTITY default with negative increment as an explicit sentinel columnzColumn z has been marked as a sentinel column with no default generation function; it at least needs to be marked nullable=False assuming user-populated sentinel values will be used.zQCan't use SEQUENCE default with negative increment as an explicit sentinel columnzn can't be a sentinel column because it uses an explicit server side default that's not the Identity() default.)rrrr!UNKNOWNidentity_increment_is_negativer1rZIDENTITYrxserver_defaultnullableNONE is_sentinelZSENTINEL_DEFAULTdefault_is_sequenceZSEQUENCE is_callableZ CLIENTSIDEZ SERVERSIDErtupler ) rZsentinel_is_explicitZsentinel_is_autoincZ the_sentinelZexplicit_sentinel_colZ autoinc_colZdefault_characterizationZthe_sentinel_zeroZ_pkcr]r]r^ _sentinel_column_characteristicss            z&Table._sentinel_column_characteristicscCs|jS)aReturns the :class:`.Column` object which currently represents the "auto increment" column, if any, else returns None. This is based on the rules for :class:`.Column` as defined by the :paramref:`.Column.autoincrement` parameter, which generally means the column within a single integer column primary key constraint that is not constrained by a foreign key. If the table does not have such a primary key constraint, then there's no "autoincrement" column. A :class:`.Table` may have only one column defined as the "autoincrement" column. .. versionadded:: 2.0.4 .. seealso:: :paramref:`.Column.autoincrement` )rrr]r]r^autoincrement_columnwszTable.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``. )rfrbrcrr]r]r^rrs z Table.keycsDddtjgtjgddjDfdddDS)Nz Table(%s), cSsg|] }t|qSr]reprrxr]r]r^rsz"Table.__repr__..cs"g|]}d|tt|fqSz%s=%srgetattrrkrr]r^rsrc)joinrrbrrrr]rr^rs  zTable.__repr__cCst|j|jSrn)rf descriptionrcrr]r]r^__str__sz Table.__str__rqrdcCs|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)raddrrqr]r]r^add_is_dependent_ons zTable.add_is_dependent_onzColumnClause[Any])columnreplace_existingrdc Csbz |j||dd|jDdWn<tjk r\}zt|jdd|W5d}~XYnXdS)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 cSsi|] }|j|qSr]rrr]r]r^rsz'Table.append_column..rrzV Specify replace_existing=True to Table.append_column() to replace an existing column.N)r|rsr1DuplicateColumnErrorr{)rr#r$der]r]r^ append_columns zTable.append_columnzUnion[Index, Constraint])rrdcCs||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|)rrr]r]r^append_constraintszTable.append_constraintr%parentrmrdcKs.|}t|tst||j|j|||_dSrn)rorrrrbrcr)rr+rmrr]r]r^ _set_parentszTable._set_parent_CreateDropBindbind checkfirstrdcCs|jtj||ddS)zIssue a ``CREATE`` statement for this :class:`_schema.Table`, using the given :class:`.Connection` or :class:`.Engine` for connectivity. .. seealso:: :meth:`_schema.MetaData.create_all`. r0N_run_ddl_visitorrZSchemaGeneratorrr/r0r]r]r^creates z Table.createcCs|jtj||ddS)zIssue a ``DROP`` statement for this :class:`_schema.Table`, using the given :class:`.Connection` or :class:`.Engine` for connectivity. .. seealso:: :meth:`_schema.MetaData.drop_all`. r1Nr3rZ SchemaDropperr4r]r]r^drops z Table.droprzP:meth:`_schema.Table.tometadata` is renamed to :meth:`_schema.Table.to_metadata`z.Union[str, Literal[SchemaConst.RETAIN_SCHEMA]]z^Optional[Callable[[Table, Optional[str], ForeignKeyConstraint, Optional[str]], Optional[str]]])rrcreferred_schema_fnrbrdcCs|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. )rcr8rb) to_metadata)rrrcr8rbr]r]r^ tometadatas zTable.tometadatac sx|dkrj}|tkrj}n|dkr.|j}n|}t||}||jkrdtdjd|j|Sg}jD]}| |j |dqnt ||f||j dj jD]t} t| tr| j} |r||| | } n| jkr|nd} | j | dq| js| jr q| j |dqjD]D} | jr8q(t| jffdd| jD| jd | j q(S) aq 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. To reset the schema to "none", return the symbol :data:`.BLANK_SCHEMA`. To effect no change, return ``None`` or :data:`.RETAIN_SCHEMA`. .. versionchanged:: 1.4.33 The ``referred_schema_fn`` function may return the :data:`.BLANK_SCHEMA` or :data:`.RETAIN_SCHEMA` symbols. 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) :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. Nrz9' already exists within the given MetaData - not copying.r)rcrrcrkcsg|]}t|qSr])rvrexprr!r]r^rsz%Table.to_metadata..)unique_table)rbrZrcrfrr3warnrrappend_copyrSrrrroForeignKeyConstraint_referred_schemar) _type_bound _column_flagrIndex_table_bound_expressionsr>r) rrrcr8rbZ actual_schemarrr{colconstZreferred_schemaZfk_constraint_schemaindexr]r!r^r91sW           zTable.to_metadata)r]TNN)F)F)F)/rWrXrYrrrr3Zro_non_memoized_propertyrrrrrrsrtypingZdeprecated_paramsr classmethodrrrpropertyrrrrrrrro_memoized_propertyrrrrrrr"r'r)r,r5r7 deprecatedrZr:r9 __classcell__r]r]rr^rS;s  ;>B ) cseZdZUdZdZdZded<ded<d_ddd ejejddddde j dd dddd dd d dd d d ddddddddddddddddddddddddfddZ ded<ded <d!ed"<ded#<ded$<d%ed&<d'ed(<d)d*d+d,d-Z e jd.d/d0d1Ze jd.d/d2d3Zejdd/d4d5Zdd*d6d7d8Zdd/d9d:Zd;dd<d=d>Zd?d*d@dAdBZdd/dCdDZddEddd*dFdGdHZdId*dJdKdLZdId*dJdMdNZedOdPdd;dQdRdSZdd;dQdTdUZd;d*dVdWdXZd`dYddddZdd[d\d]d^Z Z!S)arpz(Represents a column in a database table.r#Tr_rrzOptional[FetchedValue]rNautoF)rbtype_ autoincrementrxinsert_defaultdocrrrKr>rr onupdaterrserver_onupdatersystemrinsert_sentinel_omit_from_statements_proxiesz@Optional[Union[str, _TypeEngineArgument[_T], SchemaEventTarget]]z;Optional[Union[_TypeEngineArgument[_T], SchemaEventTarget]]r%r`!Optional[_TypeEngineArgument[_T]]r;rrOptional[_InfoType]zrr rWrrrXrrYrrZr[r\dialect_kwargscs||gt|}~|rXt|dtrB|dk r6td|d}n|ddkrX|d|r|d}t|dr|dk rtd|d}n|ddkr|d|dk rt||}n|dk rtdt ||| dk r| n||_ ||_ ||_ ||_ | |_}|tk r||_n| |_| |_| |_||_||_||_t|_t|_||_d|_d|_|dk rp||_n ||j|tj k r|}n|tj k r|}nd}|dk rt|t!t"fst!|}||_#|$|nd|_#|dk rt|t!t"fst!|dd}||_%|$|nd|_%|dk rZt|t&rH|'d }|$|nt(|}|$|||_)|dk rt|t&r|'d}|$|nt(|dd}|$|||_*|j+t,t-t.|t/0|| dk r| |_1|j2f|dS) a!b 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. :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 with no foreign key dependencies** (see later in this docstring for a more specific definition). This may influence the :term:`DDL` that will be emitted for this column during a table create, as well as how the column will be considered when INSERT statements are compiled and executed. The default value is the string ``"auto"``, which indicates that a single-column (i.e. non-composite) primary key that is of an INTEGER type with no other client-side or server-side default constructs indicated should receive auto increment semantics automatically. Other values include ``True`` (force this column to have auto-increment semantics for a :term:`composite primary key` as well), ``False`` (this column should never have auto-increment semantics), and the string ``"ignore_fk"`` (special-case for foreign key columns, see below). The term "auto increment semantics" refers both to the kind of DDL that will be emitted for the column within a CREATE TABLE statement, when methods such as :meth:`.MetaData.create_all` and :meth:`.Table.create` are invoked, as well as how the column will be considered when an INSERT statement is compiled and emitted to the database: * **DDL rendering** (i.e. :meth:`.MetaData.create_all`, :meth:`.Table.create`): When used on a :class:`.Column` that has no other default-generating construct associated with it (such as a :class:`.Sequence` or :class:`.Identity` construct), the parameter will imply that database-specific keywords such as PostgreSQL ``SERIAL``, MySQL ``AUTO_INCREMENT``, or ``IDENTITY`` on SQL Server should also be rendered. Not every database backend has an "implied" default generator available; for example the Oracle backend always needs an explicit construct such as :class:`.Identity` to be included with a :class:`.Column` in order for the DDL rendered to include auto-generating constructs to also be produced in the database. * **INSERT semantics** (i.e. when a :func:`_sql.insert` construct is compiled into a SQL string and is then executed on a database using :meth:`_engine.Connection.execute` or equivalent): A single-row INSERT statement will be known to produce a new integer primary key value automatically for this column, which will be accessible after the statement is invoked via the :attr:`.CursorResult.inserted_primary_key` attribute upon the :class:`_result.Result` object. This also applies towards use of the ORM when ORM-mapped objects are persisted to the database, indicating that a new integer primary key will be available to become part of the :term:`identity key` for that object. This behavior takes place regardless of what DDL constructs are associated with the :class:`_schema.Column` and is independent of the "DDL Rendering" behavior discussed in the previous note above. The parameter may be set to ``True`` to indicate that a column which is part of a composite (i.e. 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. 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 effects on columns that meet the above criteria: * DDL issued for the column, if the column does not already include a default generating construct supported by the backend such as :class:`.Identity`, will include database-specific keywords intended to signify this column as an "autoincrement" column for specific backends. Behavior for primary SQLAlchemy dialects includes: * AUTO INCREMENT on MySQL and MariaDB * SERIAL on PostgreSQL * IDENTITY on MS-SQL - this occurs even without the :class:`.Identity` construct as the :paramref:`.Column.autoincrement` parameter pre-dates this construct. * SQLite - SQLite integer primary key columns are implicitly "auto incrementing" and no additional keywords are rendered; to render the special SQLite keyword ``AUTOINCREMENT`` is not included as this is unnecessary and not recommended by the database vendor. See the section :ref:`sqlite_autoincrement` for more background. * Oracle - The Oracle dialect has no default "autoincrement" feature available at this time, instead the :class:`.Identity` construct is recommended to achieve this (the :class:`.Sequence` construct may also be used). * Third-party dialects - consult those dialects' documentation for details on their specific behaviors. * When a single-row :func:`_sql.insert` construct is compiled and executed, which does not set the :meth:`_sql.Insert.inline` modifier, newly generated primary key values for this column will be automatically retrieved upon statement execution using a method specific to the database driver in use: * MySQL, SQLite - calling upon ``cursor.lastrowid()`` (see `https://www.python.org/dev/peps/pep-0249/#lastrowid `_) * PostgreSQL, SQL Server, Oracle - use RETURNING or an equivalent construct when rendering an INSERT statement, and then retrieving the newly generated primary key values after execution * PostgreSQL, Oracle for :class:`_schema.Table` objects that set :paramref:`_schema.Table.implicit_returning` to False - for a :class:`.Sequence` only, the :class:`.Sequence` is invoked explicitly before the INSERT statement takes place so that the newly generated primary key value is available to the client * SQL Server for :class:`_schema.Table` objects that set :paramref:`_schema.Table.implicit_returning` to False - the ``SELECT scope_identity()`` construct is used after the INSERT statement is invoked to retrieve the newly generated primary key value. * Third-party dialects - consult those dialects' documentation for details on their specific behaviors. * For multiple-row :func:`_sql.insert` constructs invoked with a list of parameters (i.e. "executemany" semantics), primary-key retrieving behaviors are generally disabled, however there may be special APIs that may be used to retrieve lists of new primary key values for an "executemany", such as the psycopg2 "fast insertmany" feature. Such features are very new and may not yet be well covered in documentation. :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 insert_default: An alias of :paramref:`.Column.default` for compatibility with :func:`_orm.mapped_column`. .. versionadded: 2.0.31 :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. This parameter can also accept complex combinations of contextually valid SQLAlchemy expressions or constructs:: from sqlalchemy import create_engine from sqlalchemy import Table, Column, MetaData, ARRAY, Text from sqlalchemy.dialects.postgresql import array engine = create_engine( 'postgresql+psycopg2://scott:tiger@localhost/mydatabase' ) metadata_obj = MetaData() tbl = Table( "foo", metadata_obj, Column("bar", ARRAY(Text), server_default=array(["biz", "bang", "bash"]) ) ) metadata_obj.create_all(engine) The above results in a table created with the following SQL:: CREATE TABLE foo ( bar TEXT[] DEFAULT ARRAY['biz', 'bang', 'bash'] ) 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`. :param insert_sentinel: Marks this :class:`_schema.Column` as an :term:`insert sentinel` used for optimizing the performance of the :term:`insertmanyvalues` feature for tables that don't otherwise have qualifying primary key configurations. .. versionadded:: 2.0.10 .. seealso:: :func:`_schema.insert_sentinel` - all in one helper for declaring sentinel columns :ref:`engine_insertmanyvalues` :ref:`engine_insertmanyvalues_sentinel_columns` rNz0May not pass name positionally and as a keyword.Z _sqla_typez1May not pass type_ positionally and as a keyword.z9Explicit 'name' is required when sending 'quote' argumentT for_updateF)3listror_r1r~rhasattrr*rrrrr_insert_sentinelr[_user_defined_nullabler\r rKr>rYrVrTrrrrcomputedrr\ _set_typetyperNO_ARG ColumnDefaultrrxrArWrT_as_for_update DefaultClauserrXrr_typing_SequencerQr3set_creation_orderrr)rr_r`rbrSrTrxrUrVrrrKr>rr rWrrrXrrYrrZr[r\r{raZl_argsZcoltypeZudnZresolved_defaultrr]r^rs                               zColumn.__init__rSrqrrrrrKr>zOptional[Computed]rhzOptional[Identity]rzTypeEngine[Any]ry)rSrdcCs^|jjs||jkst||_t|jtr4|j||jjD]}t|tr@||q@dSrn)rj_isnullrror%r|_variant_mappingvalues)rrSimplr]r]r^ris   zColumn._set_typerrcCs t|jSz1used by default.py -> _process_execute_defaults())r_from_column_defaultrxrr]r]r^_default_description_tuplesz!Column._default_description_tuplecCs t|jSru)rrvrWrr]r]r^_onupdate_description_tuplesz"Column._onupdate_description_tuplecCs|jdk o|jjS)zspecial attribute used by cache key gen, if true, we will use a static cache key for the annotations dictionary, else we will generate a new cache key for annotations each time. Added for #8790 N)rqZ _is_tablerr]r]r^!_gen_static_annotations_cache_keys z(Column._gen_static_annotations_cache_keyrcKs||dSrnrrr]r]r^rszColumn._extra_kwargscCsD|jdkrdS|jdk r:|jjr2|jjd|jS|jSn|jSdS)Nz (no name)re)rbrqZnamed_with_columnrrr]r]r^rs  zColumn.__str__ Column[Any]r#rdcCs&|jD]}|jj|jrdSqdS)zOReturn True if this Column references the given column via foreign key.TFN)rr#Z proxy_set intersectionrr#fkr]r]r^ referencess zColumn.references ForeignKeyr~rdcCs||dSrnr()rr~r]r]r^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)Nrrrr rWrxrrz Column(%s)rcSsg|]}|dk rt|qSrnrrr]r]r^rsz#Column.__repr__..cSsg|] }t|qSr]rrr]r]r^rsz table=<%s>z table=Nonecs"g|]}d|tt|fqSrrrrr]r^rs)rrrbrArr rWrxrrrrrjrrrqr)rkwargr]rr^rs@             zColumn.__repr__zDict[str, Column[Any]])r+rrrmrdc s|ttst|js"td||jdkr<|j|_t|dd}|dk rt|k rttd|jd|j dd}d}d}|jj krj |j}|j|jkrd}qd}n|j|kr||j}|h}d}|dk rP||k rP|st d |d |dkr|jn|jd jd |j D].} j | | jjkr j | jq |r|dk r|j|jkrtd |jd|jd|jdj j||d|||j<|_|jr|jjdk rtd||j_|jrj|n*|jjkrtd|jdjd|jrZt|jtr:tdtd|jt|jddn4|jrt|jtrztdt|jdd| fdd|j!rt|j"t#st|j$t#rtddS)NzfColumn must be constructed with a non-blank name or assign a non-blank .name before adding to a Table.rqzColumn object 'z' already assigned to Table 'rrbrrzA column with z 'z' is already present in table ''.z Column with user-specified key "z-" is being replaced with plain named column "z", key "zs" is being removed. If this is a reflection operation, specify autoload_replace=False to prevent this replacement.) extra_removez2a Table may have only one explicit sentinel columnz'Trying to redefine primary-key column 'z(' as a non-primary-key column on table '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)r>rFzThe '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.)rFcs |Srn)_set_remote_tabler~rqr]r^ro rz$Column._set_parent..z4An column cannot specify both Identity and Sequence.)%rorSrrbr1r~Z_reset_memoizationsrrrrrr%rrrrr3r@rurqrfrr_replacerrKr_r)rGrr>UniqueConstraint_setup_on_memoized_fksrrxrrW) rr+rrrmexistingrZ existing_colZ conflicts_onr~r]rr^r,s               zColumn._set_parentCallable[..., Any]rrdcCsj|jj|jfdf|jj|jfdfg}|D]<\}}||jjjkr(|jjj|D]}|j|krL||qLq(dS)NFT)rqrrrbr _fk_memos link_to_name)rrZfk_keysfk_keyrr~r]r]r^ry s  zColumn._setup_on_memoized_fkscCs*|jdk r|||jnt|d|dS)Nr)rqr0r)rrr]r]r^_on_table_attach s zColumn._on_table_attachrz]The :meth:`_schema.Column.copy` method is deprecated and will be removed in a future release.rmrdcKs |jf|SrnrBrrmr]r]r^r sz Column.copyc  sfdd|jDfdd|jD}i}|jD]2}|j|j}|D]\}}|||d|<qJq2|j}|j} t|tt fr| |j fd}} |j } t| t r| jf} |j||j| |j|j|j|j|j|j|j||j| |j|j|j|jd|} |j| _|j| _|| S)zCreate a copy of this ``Column``, uninitialized. This is used in :meth:`_schema.Table.to_metadata` and by the ORM. csg|]}|js|jfqSr])rErBrrmr]r^r sz Column._copy..csg|]}|js|jfqSr])rrBrrr]r^r s_N)rbrSrrrr>rYrKrTrxrrWrXrVrr[rZ) rrdialect_options _non_defaultsitemsrrXroComputedIdentityrArBrjr%r _constructorrbrrrr>rYrKrTrxrWrVrr[rfr rgr) rrmr{Z column_kwargs dialect_namerdialect_option_keydialect_option_valuerrXrSrsr]rr^rB s\     z Column._copy)otherrdc CsZ|jr d|_|jdkr(|jdkr(|j|_|jr6|j|_|jrJ|j|j|j}|js|jjrt|trp| }||_t|tr| ||j D]}t|tr| |q|j tk r|j tkr|j|_|j |_ |jdk r|jdkr|j}|||jr:|jdkr:|j}t|tr4|}||n||_|jrf|jdkrf|j}|}|||jr|jdkr|j}|||jdkr|jdkr|j|_|jdkr|jdkr|j|_|jr|jdkr|j|_|jr|jdkr|j|_|jD] }|js |} | |q |jD] } | js4| } | |q4dS)zmerge the elements of another column into this one. this is used by ORM pep-593 merge and will likely need a lot of fixes. TrRN)TF)rrTrYrupdaterjrqror%rr|rrrsrgr\r rxrBr,rrTrXrWrKr>rVrrrErr) rrrSrtZ new_defaultZnew_server_defaultZnew_server_onupdateZ new_onupdaterJZ new_constr~Znew_fkr]r]r^_merge sp               z Column._mergerMz.Optional[_typing_Sequence[ColumnElement[Any]]]zTuple[str, ColumnClause[_T]]) selectablerbrrname_is_truncatablecompound_select_colsrmrdc Ks.dddd|jDD}|dkr6|jdkr6tdzj|j|rXttj|rP|n|jn|p`|j|j f||rr|n |rz|n|j |j |j |rt |n|gd}Wn2tk r} ztd|j| W5d} ~ 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. cSs2g|]*\}}t|dk r|n|j|dk|jdqS)N) _unresolvable _constraint)r_colspecr)rfrIr]r]r^r? s z&Column._make_proxy..cSsg|]}||jddfqS)Fraiseerr_resolve_column)rr~r]r]r^rE sNz^Cannot initialize a sub-selectable with this Column object until its 'name' has been assigned.)rrrr r\zCould 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.)rrbr1rrrexpectrZTruncatedLabelRolerjrrrr rdrrrqZ_propagate_attrsZ _is_clone_ofrrr r) rrrbrrrrrmr~rsrr]r]r^ _make_proxy+ sZ        zColumn._make_proxy)NN)NNFN)"rWrXrYrrZ inherit_cacherrrkrUr\rrir4Zmemoized_attributerwrxr3rryrrrrrr,rrrPrrBrrrQr]r]rr^rps  F      } DXrpT)rxomit_from_statementsr]rrrz)rbrSrxrrdcCs.t||dkrtjn||dk r |nt|ddS)aProvides a surrogate :class:`_schema.Column` that will act as a dedicated insert :term:`sentinel` column, allowing efficient bulk inserts with deterministic RETURNING sorting for tables that don't otherwise have qualifying primary key configurations. Adding this column to a :class:`.Table` object requires that a corresponding database table actually has this column present, so if adding it to an existing model, existing database tables would need to be migrated (e.g. using ALTER TABLE or similar) to include this column. For background on how this object is used, see the section :ref:`engine_insertmanyvalues_sentinel_columns` as part of the section :ref:`engine_insertmanyvalues`. The :class:`_schema.Column` returned will be a nullable integer column by default and make use of a sentinel-specific default generator used only in "insertmanyvalues" operations. .. seealso:: :func:`_orm.orm_insert_sentinel` :paramref:`_schema.Column.insert_sentinel` :ref:`engine_insertmanyvalues` :ref:`engine_insertmanyvalues_sentinel_columns` .. versionadded:: 2.0.10 NT)rbrSrxr[rZ)rpr INTEGERTYPE_InsertSentinelColumnDefault)rbrSrxrr]r]r^rZz s'rZc@seZdZUdZdZded<ded<dTd d d d d d dd d d dd d ddddZddddZe ddddd dddddZ ddd dddddZ dUd d d dd!d"d#Z e d dd$d%Zddd&d'Ze e Zd(d d)d*d+Zd,dd)d-d.Zejd/dd0d1Zd2dd3d4Zd(d(d dd5d6d7Zdd8d9d:d;Zejdddd?d@ddAdBdCZed>d?d ddAdDdCZdEd?d ddAdFdCZdGdd8dHdIdJZd(d8d)dKdLZdMd8dNdOdPZdd(d8dQdRdSZdS)Vra;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_keyrzr+r _table_columnNFr<zOptional[ForeignKeyConstraint]r_ConstraintNameArgumentr`rr^r)r#r use_alterrbrWondelete deferrable initiallyrmatchrrr dialect_kwcKsttj||_| |_t|jtr*d|_n0|j|_t|jj t dt fsZt 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. :param comment: Optional string that will render an SQL comment on foreign key constraint creation. .. versionadded:: 2.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. Nz8ForeignKey received Column not bound to a Table, got: %r)rrrZDDLReferredColumnRolerrror_rrqrjr,r1r~rr+rrbrWrrrrrrr_unvalidated_dialect_kw)rr#rrrbrWrrrrrrrrrr]r]r^r s8X   zForeignKey.__init__r_rcCs d|S)NzForeignKey(%r)) _get_colspecrr]r]r^rY szForeignKey.__repr__rzaThe :meth:`_schema.ForeignKey.copy` method is deprecated and will be removed in a future release.r)rcrmrdcKs|jfd|i|S)Nrcr)rrcrmr]r]r^r\ szForeignKey.copyc KsJt|j|df|j|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) rrbrWrrrrrr) rrrrbrWrrrrrrrr)rrcrmr~r]r]r^rBd s    zForeignKey._copyzROptional[Union[str, Literal[SchemaConst.RETAIN_SCHEMA, SchemaConst.BLANK_SCHEMA]]])rc table_name_is_copyrdcCs|dtfkrH|j\}}}|dk r$|}|tkr8d||fSd|||fSn|rx|j\}}}|rjd|||fSd||fSnb|jdk r|jjdkr|rtd|jn|jjSd|jjj|jjfSt |j t st |j SdS)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. Nrz%s.%s.%szDCan't copy ForeignKey object which refers to non-table bound Column ) rZ_column_tokensr[rrqr1rrrrrorr_r)rrcrrZ_schematnamecolnamer]r]r^r s2       zForeignKey._get_colspeccCs |jdSNr)rrr]r]r^rD szForeignKey._referred_schemacCs@|jdk r&|jjdkrdS|jjjSn|j\}}}t||SdSrn)rrqrrrrf)rrcrrr]r]r^ _table_key s     zForeignKey._table_keyrSrcCs||jdk S)zrReturn True if the given :class:`_schema.Table` is referenced by this :class:`_schema.ForeignKey`.N)corresponding_columnr#r!r]r]r^r szForeignKey.referencesrMcCs|j|jS)a-Return the :class:`_schema.Column` in the given :class:`_schema.Table` (or any :class:`.FromClause`) referenced by this :class:`_schema.ForeignKey`. Returns None if this :class:`_schema.ForeignKey` does not reference the given :class:`_schema.Table`. )rrr#r!r]r]r^ get_referent s zForeignKey.get_referentz(Tuple[Optional[str], str, Optional[str]]cCsx|d}|dkr(td|jt|dkrB|}d}n|}|}t|dkrjd|}nd}|||fS)z7parse a string-based _colspec into its component parts.reNz*Invalid foreign key column specification: rr)rsplitr1r~rlenrr)rmrrrcr]r]r^r s    zForeignKey._column_tokensz Tuple[Table, str, Optional[str]]cCs|jdkrtdn|jjdkr,td|jj}|jrZ|j\}}}t||}|||fS|jjD] }t|t rb|j|ks~t qqbdst |j\}}}|dkr|j j dk r|j j }t||}|||fS)NzLthis ForeignKey object does not yet have a parent Column associated with it.zCthis ForeignKey's parent column is not yet associated with a Table.F) r+r1rrqrrrfZ base_columnsrorprrrc)r parenttablercrrtablekeyrsr]r]r^_resolve_col_tokens s.         zForeignKey._resolve_col_tokens)rrqrrdc Csd}|dkr4|j}|dk st|j}|j|d}n8|jrZ|}|jD]}|j|krD|}qDn|}|j|d}|dkrtd|j d|jd|jd|d |j||S)Nz3Could not initialize target column for ForeignKey 'z ' on table 'z ': table 'z' has no column named 'r) r+rrrrsrrrbr1NoReferencedColumnErrorr)rrrqr_columnr+rrrsr]r]r^_link_to_col_by_colstring s(   " z$ForeignKey._link_to_col_by_colstringryr{csL|jdk st|jjjr"j|j_dddfdd }|j||_dS)Nrryrcs|jjjrj|j_dSrn)r+rjrqrr#r]r^set_typeN s z/ForeignKey._set_target_column..set_type)r+rrjrqrr#)rr#rr]rr^_set_target_columnD s    zForeignKey._set_target_columncCs|S)zReturn the target :class:`_schema.Column` referenced by this :class:`_schema.ForeignKey`. If no target column has been established, an exception is raised. rrr]r]r^r#V s zForeignKey.column.rz Literal[True])rrdcCsdSrnr]rrr]r]r^rb szForeignKey._resolve_columncCsdSrnr]rr]r]r^rg sTc Cst|jtr|\}}}|js*||jkrV|s2dStd|jd|d|d|q|j |jkr~|sjdSt d|dq|jj |}| |||Sn$t |jdr|j}|S|j}|SdS)Nz$Foreign key associated with column 'z' could not find table 'z9' with which to generate a foreign key to target column 'rzTable z1 is no longer associated with its parent MetaData__clause_element__)rorr_rrrr1ZNoReferencedTableErrorr+rrrrrrer)rrrrrrqrr]r]r^rl s4      r%r*cKsRt|tst|jdk r,|j|k r,td||_|jj||j|j dS)Nz&This ForeignKey already has a parent !) rorprr+r1rrr r _set_tablerr+rmr]r]r^r, szForeignKey._set_parentcCsD|\}}}||||}|||jdk s4t|j|dSrn)rrrrr_validate_dest_table)rrqrrrrr]r]r^r s  zForeignKey._set_remote_tablerrrdcCs8|\}}}||f}||j|kr4|j||dSrn)rrr)rrr table_keyrrr]r]r^_remove_from_metadata sz ForeignKey._remove_from_metadatar#rqrdc Cs0t|tst|jdkrjtggf|j|j|j|j|j |j |j |j d|j |_|j|||j||j|t|jtr|\}}}||f}||jjkr|jj|}z||||}Wntjk rYn X|||jj||n4t|jdr|j}||n|j}||dS)N)rrbrWrrrrrr)rorSrrrCrrbrWrrrrrr_append_elementr|rr rr_rrrrr1rrrrArer)rr#rqrrrrrr]r]r^r sP           zForeignKey._set_table) NFNNNNNFNNNF)NNF) rWrXrYrrrrrr3rPrrBrrNrDrZtarget_fullnamerrrrrrrrOr#rrr,rrrr]r]r]r^r sj '*%1 ($ & rzOptional[DefaultGenerator]zTypeGuard[Sequence])objrdcCsdSrnr]rr]r]r^r  sr z%TypeGuard[ColumnElementColumnDefault]cCsdSrnr]rr]r]r^default_is_clause_element srz%TypeGuard[ScalarElementColumnDefault]cCsdSrnr]rr]r]r^default_is_scalar sr is_sequenceis_clause_element is_scalarc@seZdZUdZdZdZdZdZdZdZ dZ dZ dZ dZ ded<dddd d d Zd d ddddZddddZdddd dddZdddd dddZdS)DefaultGeneratorzBase class for column *default* values. This object is only present on column.default or column.onupdate. It's not valid as a server default. Zdefault_generatorTFrr#rryrcrdcCs ||_dSrnrbrrcr]r]r^r szDefaultGenerator.__init__r%rr*cKs4trt|tst||_|jr(||j_n||j_dSrn)rrorprr#rcrWrxrr]r]r^r, s  zDefaultGenerator._set_parentrcCs tdSrnNotImplementedErrorrr]r]r^rB szDefaultGenerator._copyrFrHrI) connectiondistilled_paramsexecution_optionsrdcCstdd||||S)NzoUsing the .execute() method to invoke a DefaultGenerator object is deprecated; please use the .scalar() method.z2.0)r3Zwarn_deprecated_execute_on_scalarrrrrr]r]r^_execute_on_connection sz'DefaultGenerator._execute_on_connectioncCs||||Srn)Z_execute_defaultrr]r]r^r% s z#DefaultGenerator._execute_on_scalarN)F)rWrXrYrrZ_is_default_generatorr is_identityis_server_defaultrr rhas_argr rrr,rBrrr]r]r]r^r s"  rc@seZdZUdZded<edddddd d Zedd dd dd d Zeddddddd Zddddddd ZddddZdS)rlaA 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)) rarg.rrCallableColumnDefaultrrcrdcCsdSrnr]rrrcr]r]r^rH szColumnDefault.__new__rgColumnElementColumnDefaultcCsdSrnr]rr]r]r^rM srcCsdSrnr]rr]r]r^rU sNFcCsJt|trtdn*t|r$t}nt|tr4t}n |dk r@t}t |S)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) rorTr1r~callablerr'rScalarElementColumnDefaultrrrr]r]r^rX s  r_rcCs|jjd|jdS)N())rrWrrr]r]r^r szColumnDefault.__repr__).).).)NF)rWrXrYrrrrrr]r]r]r^rl0 s *rlc@s:eZdZdZdZdZddddddd Zdd d d Zd S)rzQdefault generator for a fixed scalar Python value .. versionadded: 2.0 TFrrryrcCs||_||_dSrnrcrrrrcr]r]r^r sz#ScalarElementColumnDefault.__init__rcCst|j|jdSNrrc)rrrcrr]r]r^rB sz ScalarElementColumnDefault._copyN)F)rWrXrYrrrrrBr]r]r]r^r s rcs`eZdZdZdZdZdZddddZddd d Zd d dd fdd Z ddddZ Z S)rzDefault generator that's specific to the use of a "sentinel" column when using the insertmanyvalues feature. This default is used as part of the :func:`_schema.insert_sentinel` construct. TFNrcCs t|Srn)rr)rr]r]r^r sz$_InsertSentinelColumnDefault.__new__rycCsdSrnr]rr]r]r^r sz%_InsertSentinelColumnDefault.__init__r%rr*c s@td|}|jstdn|js,tdtj|f|dS)Nrzz_The _InsertSentinelColumnDefault may only be applied to a Column marked as insert_sentinel=TruezQThe _InsertSentinelColumnDefault may only be applied to a Column that is nullable)rrfr1r~r rr,rr+rmrIrr]r^r, s z(_InsertSentinelColumnDefault._set_parentcCstSrn)rrr]r]r^rB sz"_InsertSentinelColumnDefault._copy) rWrXrYrr rcrrrr,rBrQr]r]rr^r sr)rgr+c@sbeZdZUdZdZdZded<dddddd d Zdd d d Ze j e ddd ddZ dS)rzGdefault generator for a SQL expression .. versionadded:: 2.0 T_SQLExprDefaultrFrryrcCs||_||_dSrnrrr]r]r^r sz#ColumnElementColumnDefault.__init__rcCst|j|jdSr)rrrcrr]r]r^rB sz ColumnElementColumnDefault._copyzsqlalchemy.sql.sqltypescCstjj}t|jj|j Srn)r3 preloadedZ sql_sqltypesrorrjZNullType)rZsqltypesr]r]r^ _arg_is_typed sz(ColumnElementColumnDefault._arg_is_typedN)F) rWrXrYrrrrrrBr3rpreload_modulerr]r]r]r^r s rc@seZdZdddddZdS)_CallableColumnDefaultProtocolrJr)contextrdcCsdSrnr])rrr]r]r^__call__ rz'_CallableColumnDefaultProtocol.__call__N)rWrXrYrr]r]r]r^r src@sTeZdZUdZdZded<dZddddd d d Zdd d dZdddddZ dS)rzQdefault generator for a callable Python function .. versionadded:: 2.0 TrrFz8Union[_CallableColumnDefaultProtocol, Callable[[], Any]]rryrcCs||_|||_dSrn)rc_maybe_wrap_callablerrr]r]r^r szCallableColumnDefault.__init__rcCst|j|jdSr)rrrcrr]r]r^rB szCallableColumnDefault._copyrcsztjdd}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_selfcsSrnr]ctxrr]r^r rz.rVNrcsSrnr]r r r]r^rrrzDColumnDefault Python function takes zero or one positional arguments)r3Zget_callable_argspecrZ wrap_callablerr1r~)rrZargspecZ defaulted positionalsr]r r^r s z*CallableColumnDefault._maybe_wrap_callableN)F) rWrXrYrr rrrrBrr]r]r]r^r s rc @sDeZdZdZd ddddddddddd ddZed d d d ZdS)IdentityOptionszDefines options for a named database sequence or an identity column. .. versionadded:: 1.3.18 .. seealso:: :class:`.Sequence` N Optional[int]rry) start incrementminvaluemaxvalue nominvalue nomaxvaluecyclecacheorderrdc 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 rrrrrrrrr) rrrrrrrrrrr]r]r^r&szIdentityOptions.__init__rrcCs|jdk o|jdkSr)rrr]r]r^rOsz&IdentityOptions._increment_is_negative) NNNNNNNNN)rWrXrYrrrNrr]r]r]r^r s ")r cseZdZUdZdZdZded<ded<d3d d d d d d d d d d d ddd dd dddddZe dddddZ ddddfdd Z dddd Z d!d"dd#d$d%Z d&dd'd(d)Zd4d*ddd+d,d-Zd5d*ddd+d.d/Zd0dd1d2ZZS)6raRepresents 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', start=1), 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` sequenceTrr#zOptional[TypeEngine[int]] data_typeNFr_rrrz"Optional[_TypeEngineArgument[int]]rzOptional[MetaData]ry)rbrrrrrrrrcrrroptionalrrrrcrdc Cstj||dtj||||||||| | d d|_t|||_| |_| tkrXd|_} n2|dk r|| dkr||jr||j|_} nt | ||_||_ t || |_ |r| || dk rt| |_nd|_dS)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. .. versionchanged:: 2.0 The :paramref:`.Sequence.start` parameter is required in order to have DDL emit "START WITH". This is a reversal of a change made in version 1.4 which would implicitly render "START WITH 1" if the :paramref:`.Sequence.start` were not included. See :ref:`change_7211` for more detail. :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. :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. :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. :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. :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. :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. :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. :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. rbrN)rrr r#r*rbrr[rc constructrrf_key _set_metadatar-r)rrbrrrrrrrrcrrrrrrrrcr]r]r^r|s:      zSequence.__init__zsqlalchemy.sql.functionsz Function[int]rcCstjjj|S)zReturn a :class:`.next_value` function element which will render the appropriate increment function for this :class:`.Sequence` within any SQL expression. )r3rZ sql_functionsfunc next_valuerr]r]r^r 2szSequence.next_valuer%rr*c s.|}t|tstt|||jdSrn)rorprrr,rrrr+rmr#rr]r^r,;s zSequence._set_parentcCsDt|j|j|j|j|j|j|j|j|j |j |j |j |j |j|jdS)N)rbrrrrrrrrcrrrrrrc)rrbrrrrrrrrcrrrrrrcrr]r]r^rBAs"zSequence._copyrzrSrcCs||jdSrn)rr)rr#rqr]r]r^rTszSequence._set_tablerrcCs||_||jj|j<dSrn)r _sequencesr)rrr]r]r^rWszSequence._set_metadatar-r.cCs|jtj||ddS)z&Creates this sequence in the database.r1Nr2r4r]r]r^r5[szSequence.createcCs|jtj||ddS)z&Drops this sequence from the database.r1Nr6r4r]r]r^r7`sz Sequence.droprcCstd|jjddS)NzThis z 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.)r1rrrWrr]r]r^_not_a_column_expreszSequence._not_a_column_expr)NNNNNNNNNNNFNNNF)T)T)rWrXrYrrrrrr3rr r,rBrrr5r7r#rQr]r]rr^rTs@  27rc@seZdZUdZdZdZdZdZdZde d<ddddd d Z dddd d Z dd ddZ dddddZ ddddddZdd ddZdS)rTaA 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` TFrr#rryrcCs ||_dSrnrbrr]r]r^rszFetchedValue.__init__cCs||jkr|S||SdSrn)rc_clonerr]r]r^rms zFetchedValue._as_for_updatercCs t|jSrn)rTrcrr]r]r^rBszFetchedValue._copyr8cCs4|j|j}|j|j|jdd||_|S)Nr#)rrrrrrc)rrcnr]r]r^r$s zFetchedValue._cloner%rr*cKs4|}t|tst||_|jr(||j_n||j_dSrn)rorprr#rcrXrr!r]r]r^r,s  zFetchedValue._set_parentr_cCs t|Srnrrr]r]r^rszFetchedValue.__repr__N)F)rWrXrYrr reflected has_argumentrrrrrmrBr$r,rr]r]r]r^rTns  csNeZdZdZdZddddddfdd Zdd d d Zd d ddZZS)rna>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")) TFz%Union[str, ClauseElement, TextClause]rry)rrc _reflectedrdcs0t|tttfdt|||_||_dS)Nr) r3Zassert_arg_typer_r'r+rrrr&)rrrcr(rr]r^rs zDefaultClause.__init__rcCst|j|j|jdS)N)rrcr()rnrrcr&rr]r]r^rBs zDefaultClause._copyr_cCsd|j|jfS)Nz DefaultClause(%r, for_update=%r)rrr]r]r^rszDefaultClause.__repr__)FF) rWrXrYrr'rrBrrQr]r]rr^rns rnc @seZdZUdZdZded<ded<d'd d d d d d dddd ddZddddddZeddddZ ddddddZ e dd dd!d"d#d$Z dd!d"d%d&ZdS)( 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`. rintrrrFNFrrr`r^rrry) rbrrrr _create_rulerErrdc KsF||_||_||_|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. :param comment: Optional string that will render an SQL comment on foreign key constraint creation. .. versionadded:: 2.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) rbrrrr+rEr3rprr) rrbrrrrr+rErr]r]r^rs.  zConstraint.__init__rA)compilerrmrdcKsL|jdk r||sdS|jdk rD|jjt||dfd|i|SdSdS)NFr,T)r+rZ_should_executerZCreateConstraint)rr,rmr]r]r^_should_create_for_compiler!s z&Constraint._should_create_for_compilerrSrcCs<zt|jtr|jWSWntk r,YnXtddS)NzdThis constraint is not bound to a table. Did you mean to call table.append_constraint(constraint) ?)ror+rSr}r1rrr]r]r^rq-s  zConstraint.tabler%r*cKs(t|ttfst||_|j|dSrn)rorSrprr+rr rr]r]r^r,9szConstraint._set_parentrzaThe :meth:`_schema.Constraint.copy` method is deprecated and will be removed in a future release.r8rcKs |jf|Srnrrr]r]r^r>szConstraint.copycKs tdSrnrrr]r]r^rBFszConstraint._copy)NNNNNNF)rWrXrYrrrrr-rNrqr,r3rPrrBr]r]r]r^r)s,   9  r)c@seZdZUdZded<dZded<er8ddd d d d Zd dddddddd dddZd&dd dddZ e j ddddZ e j ddddZ dd d!d"d#Zddd d d$d%ZdS)'ColumnCollectionMixinzA :class:`_expression.ColumnCollection` of :class:`_schema.Column` objects. This collection represents the columns which are referred to by this object. rrFz'List[Optional[Union[str, Column[Any]]]]_pending_colargsr%rryr*cKsdSrnr]rr]r]r^r|[sz/ColumnCollectionMixin._set_parent_with_dispatchTN) _autoattachrF_gather_expressionsr<rz.Optional[List[Union[str, ColumnElement[Any]]]])rr0rFr1rdc Gsz||_t|_|}|dk rTg|_ttj|D]"\}}}}|j|||q.ndd|D|_|rv|jrv| dS)NcSsg|]}ttj|qSr])rrrDDLConstraintColumnRole)rr#r]r]r^r|sz2ColumnCollectionMixin.__init__..) rFr"rr/rZ expect_col_expression_collectionrr2rA _check_attach) rr0rFr1rZprocessed_expressionsr=rZ add_elementr]r]r^r_s,   zColumnCollectionMixin.__init__)rrdc s,ddjD}dd|D}t||r|r.cSsg|]}t|jtr|qSr])rorqrSrr]r]r^rs z#Should not reach here on event callcSsh|]}|dk r|qSrnr]rr]r]r^rsz6ColumnCollectionMixin._check_attach..rzrSryrcs(t|tr$|s$jdddS)NT)r)rorSdiscardr3)r#rq) cols_wo_tablerr]r^ _col_attacheds  z:ColumnCollectionMixin._check_attach.._col_attachedcSsh|] }|jqSr]rrr]r]r^rsrrcsg|]}|jk r|qSr]rrrr]r^rs rcss|]}d|VqdSz'%s'Nr]rr]r]r^ sz6ColumnCollectionMixin._check_attach..z Column(s) z are not part of table 'r)r/r differencerZ_cols_wo_tablerrr|r_allow_multiple_tablesrqrr1r~r) rrZcol_objsZ cols_w_tableZhas_string_colsr7rIrrZothersZ other_strr])r6rrqr^r3s8     z#ColumnCollectionMixin._check_attachrrcCs |jSrnrZ as_readonlyrr]r]r^rszColumnCollectionMixin.columnscCs |jSrnr<rr]r]r^rsszColumnCollectionMixin.czUnion[Table, Column[Any]]zList[Optional[Column[Any]]])r+rdc sttr4dd|jD}t|t|jks0t|Szfdd|jDWStk r}z0td|jj dj d|j dd|W5d}~XYnXdS) NcSsg|]}t|tr|qSr]r4rr]r]r^rs z:ColumnCollectionMixin._col_expressions..cs$g|]}t|trj|n|qSr])ror_rsrrIr+r]r^rsz Can't create z on table 'z': no column named 'rz ' is present.) rorpr/rrKeyErrorr1ZConstraintColumnNotFoundErrorrrWrr{)rr+resultZker]r>r^_col_expressionss   "z&ColumnCollectionMixin._col_expressionscKs:t|ttfst||D]}|dk r|j|qdSrn)rorSrprrArr rr]r]r^r,sz!ColumnCollectionMixin._set_parent)F)rWrXrYrrr;rr|rr3r3rOrrsrAr,r]r]r]r^r.Js" %0r.c @seZdZUdZdddddddddddd d d d d d dd ddZded<dd ddddZd d dddZe dddddd ddd d!Z dddd ddd"d#Z d$d d%d&d'Z d(d)d*d+Z d,d)d-d.ZdS)/ColumnCollectionConstraintz-A constraint that proxies a ColumnCollection.NTF)rbrrrr0rFr1r<rrr`r^rz"Optional[List[_DDLColumnArgument]]rry) rrbrrrr0rFr1rrdc Os8tj|f||||d| tj|f|||ddS)al :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 \**dialect_kw: other keyword arguments including dialect-specific arguments are propagated to the :class:`.Constraint` superclass. rbrrr)r0rFN)r)rr.) rrbrrrr0rFr1rrr]r]r^rs$ z#ColumnCollectionConstraint.__init__rrr%r*cKs.t|ttfstt||t||dSrn)rorprSrr)r,r.rr]r]r^r,s z&ColumnCollectionConstraint._set_parent)rrdcCs ||jkSrn)r)rrr]r]r^ __contains__sz'ColumnCollectionConstraint.__contains__rzqThe :meth:`_schema.ColumnCollectionConstraint.copy` method is deprecated and will be removed in a future release.rkrhrkrmrdcKs|jfd|i|SNrkrrrkrmr]r]r^rs zColumnCollectionConstraint.copyc  si}jD]2}j|j}|D]\}}|||d|<q"q tjtsNtjfddjDj j j j d|} |S)Nrcsg|]}t|jqSr])rvr+r<rrkr]r^r;sz4ColumnCollectionConstraint._copy..)rbrrr)rrrror+rSrrrrbrrrr) rrkrmZconstraint_kwargsrrrrrsr]rIr^rB$s,     z ColumnCollectionConstraint._copyrzrIrdcCs |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_columnrrIr]r]r^rKDs z*ColumnCollectionConstraint.contains_columnzIterator[Column[Any]]rcCs t|jSrn)iterrrr]r]r^__iter__Osz#ColumnCollectionConstraint.__iter__r*cCs t|jSrn)rrrr]r]r^__len__Rsz"ColumnCollectionConstraint.__len__)rWrXrYrrrr,rDr3rPrrBrKrNrOr]r]r]r^rBs. $,   rBcseZdZdZdZdZedddd!d d d d d ddddddd fdd ZeddddZ e ddddd dddddZ ddd ddddd Z 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`NFz#_TextCoercedExpressionArgument[Any]rrr`rhr^rrrry) rQrbrrrqrr+r0rErrdc sbttj||_g} t|jid| jitj | |||||| |d| |dk r^| |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. r#)rbrrr+rrEr0N) rrrDDLExpressionRolerQrtraverserArrr|) rrQrbrrrqrr+r0rErrrr]r^r`s"-  zCheckConstraint.__init__rcCst|jt Srn)ror+rSrr]r]r^is_column_levelszCheckConstraint.is_column_levelrzfThe :meth:`_schema.CheckConstraint.copy` method is deprecated and will be removed in a future release.rErFcKs|jfd|i|SrGrrHr]r]r^rszCheckConstraint.copyc KsP|dk rt|j|j|}n|j}t||j|j|j|j||jd|j d }| |S)NF)rbrrr+rqrr0rE) rvrQrqrPrbrrr+rrEr)rrkrmrQrsr]r]r^rBs zCheckConstraint._copy)NNNNNNTF)rWrXrYrr;rr&rrNrTr3rPrrBrQr]r]rr^rPVs6*:rPc@s$eZdZUdZdZd8dddddddd d dd d dd d dddZddd dddZded<ded<eddddZ eddddZ ed dd!d"Z d d d#d$d%Z ed&dd'd(Z ed)dd*d+Zd,d d d-d.d/Zed0d1ddd2dd d dd3d4d5Zddd2dd d dd3d6d7ZdS)9rCaA 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_constraintNFz$_typing_Sequence[_DDLColumnArgument]rr`rrrhr^rry)r refcolumnsrbrWrrrrrrrqrrrrdc stjf|||| | d||_|_| _|_| _tt|t|krztt|t|krpt 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. .. 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. :param comment: Optional string that will render an SQL comment on foreign key constraint creation. .. versionadded:: 2.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. )rbrrrrzOForeignKeyConstraint 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)) rrbrWrrrrrr) rrbrWrrrrrrra)rZrefcolrr]r^rMs  z1ForeignKeyConstraint.__init__..Nr+)r)rrWrrrrrrr1r~elementsr.rer+rr|)rrrUrbrWrrrrrrrqrrrr]rr^rs@T   zForeignKeyConstraint.__init__rzr)r#r~rdcCs|j||j|dSrn)rr rVrAr}r]r]r^rds z$ForeignKeyConstraint._append_elementrrzList[ForeignKey]rVz!util.OrderedDict[str, ForeignKey]rcCstt|j|jSrn)r3 OrderedDictzip column_keysrVrr]r]r^ _elementsyszForeignKeyConstraint._elementscCs|jD] }|jSdSrn)rVrD)relemr]r]r^rD~s  z%ForeignKeyConstraint._referred_schemarScCs|jdjjS)aKThe :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. r)rVr#rqrr]r]r^referred_tables z#ForeignKeyConstraint.referred_tablerc Csbdd|jD}d|kr^t|dkr^t|dd\}}td|jd|jd|d |dS) NcSsh|] }|qSr])r)rr[r]r]r^rsz.rrr/zForeignKeyConstraint on rz$) refers to multiple remote tables:  and )rVrrr1r~r_col_description)rrqZ table_keysZelem0Zelem1r]r]r^rs z)ForeignKeyConstraint._validate_dest_tablez_typing_Sequence[str]cCs(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. r+cSs$g|]}t|tr|jnt|qSr])ror)rrr_r=r]r]r^rsz4ForeignKeyConstraint.column_keys..N)rerkeysr/rr]r]r^rYs  z ForeignKeyConstraint.column_keysr_cCs d|jS)Nr)rrYrr]r]r^r^sz%ForeignKeyConstraint._col_descriptionr%r*cKsn|}t|tstt||t||t|j|jD]&\}}t |drT|j |k r8| |q8| |dS)Nr+) rorSrr)r,rBrXrrVrer+r|r)rr+rmrqrIr~r]r]r^r,s   z ForeignKeyConstraint._set_parentrzkThe :meth:`_schema.ForeignKeyConstraint.copy` method is deprecated and will be removed in a future release.r;)rcrkrmrdcKs|jf||d|S)Nr;r)rrcrkrmr]r]r^rs zForeignKeyConstraint.copyc sztdd|jDfdd|jD|j|j|j|j|j|j|j|j |j d }t |j|jD]\}}| |q\| |S)NcSsg|] }|jjqSr])r+rrrr]r]r^rsz.ForeignKeyConstraint._copy..cs<g|]4}|jdk r.||jjjkr.jndddqS)NT)rcrr)rrr+rqrrrbrr;r]r^rs ) rbrWrrrrrrr) rCrVrbrWrrrrrrrrXr)rrcrkrmrZself_fkZother_fkr]r;r^rBs$   zForeignKeyConstraint._copy) NNNNNFFNNNN)rWrXrYrrrrrrNrZrDr\rrYr^r,r3rPrrBr]r]r]r^rCsP  ,     rCc seZdZdZdZddddddddddd d d d d fddZdd d dfdd Zdd dddZdd dddZe ddddZ e j d dd!d"Z ZS)#ra 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. 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) ) Zprimary_key_constraintNF)rbrrrrr<r`rr^rrry)rrbrrrrrrdcs&||_tj|||||d|dS)NrC)rrr)rrbrrrrrrrr]r^r0s zPrimaryKeyConstraint.__init__r%r*c s|}t|tstt||j|k rH|j|j||_|j|dd|j D}|j r|rt |t |j krd dd|D}d dd|j D}t d|jd|d |d |d g|dd<|j D]}d |_|jtkrd |_q|r|j |dS)NcSsg|]}|jr|qSr])rrr]r]r^rNsz4PrimaryKeyConstraint._set_parent..rcss|]}d|jVqdSr8rrr]r]r^r9Usz3PrimaryKeyConstraint._set_parent..css|]}d|jVqdSr8rrr]r]r^r9Vsrz' specifies columns z= as primary_key=True, not matching locally specified columns z-; setting the current primary key columns to z:. This warning may become an exception in a future releaseTF)rorSrrr,rrr5r rsrrrr3r@rbrgr\r extend)rr+rmrqZ table_pksZ table_pk_strZcol_strrsrr]r^r,Ds4      z PrimaryKeyConstraint._set_parentzIterable[Column[Any]])rrdcCs8|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)rrr`rr_resetr|rq)rrrIr]r]r^_reloadls   zPrimaryKeyConstraint._reloadrzrJcCs*tj||j||j||dSrn)rrrarrurZ'_sa_event_column_added_to_pk_constraintrLr]r]r^rs  zPrimaryKeyConstraint._replacezList[Column[Any]]rcs6|jdk r(gfdd|jDSt|jSdS)Ncsg|]}|k r|qSr]r]rautoincr]r^rsz>PrimaryKeyConstraint.columns_autoinc_first..)rrrdrr]rcr^columns_autoinc_firstsz*PrimaryKeyConstraint.columns_autoinc_firstrcCsdddddd}t|jdkrdt|jd}|jdkrF||d|S|jd kr^||d r^|SdSnRd}|jD]B}|jdkrn||d|dk rtd |jd |jd qn|}qn|SdS)Nrzr)rI autoinc_truerdcSs|jjdks&t|jjtjjtjjfsL|rFtd|jd|dqdSnNt|j tdt fsh|shdS|j dk rt|j t s|sdS|j r|jdkrdSdS)Nz Column type z on column 'z+' is not compatible with autoincrement=TrueF)T ignore_fkT)rjZ_type_affinity issubclassrrZ NUMERICTYPEr1r~rorxrrrrrT)rIrfr]r]r^_validate_autoincs4 zEPrimaryKeyConstraint._autoincrement_column.._validate_autoincrrT)rRrgFz=Only one Column may be marked autoincrement=True, found both r]re)rrrdrTr1r~rb)rrirIrdr]r]r^rs*!      z*PrimaryKeyConstraint._autoincrement_column)rWrXrYrrrr,rbrrNrer3rOrrQr]r]rr^rs;$(rc@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)rWrXrYrrr]r]r]r^rsrc @seZdZUdZdZded<ded<ded<d d d d d d d d dddddddd ddZddddddZd$ddddddZd%ddddddZ d d!d"d#Z d S)&rGaA 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)")) ) .. 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. rKrhrqz0_typing_Sequence[Union[str, ColumnElement[Any]]] expressionsz$_typing_Sequence[ColumnElement[Any]]rHFN)r>rrr?rFr`r<rrr^rry) rbrjr>rrr?rFrrdc Osxd|_} t|||_||_|dk r,||_|dk r8|} ||g|_tj |f|||jd| dk rt| | dS)avConstruct 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. :param \**dialect_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. N)rFr1) rqr*rrbr>rrrjr.rr,) rrbr>rrr?rFrjrrqr]r]r^r4s&(  zIndex.__init__r%r*c Ks|}t|tstt|||jdk rX||jk rXtd|jd|jj d|j d||_|j ||j }| |}t|t|kstg}t||D]:\}}t|tr||q|dk r||qdstq||_ |_dS)NzIndex 'z' is against table 'z(', and cannot be associated with table 'rF)rorSrr.r,rqr1r~rbrrr rjrArrXr'rArH) rr+rmrqrjZcol_expressionsZexprsr=Zcolexprr]r]r^r,vs(       zIndex._set_parentr-r.cCs|jtj||ddS)zIssue a ``CREATE`` statement for this :class:`.Index`, using the given :class:`.Connection` or :class:`.Engine`` for connectivity. .. seealso:: :meth:`_schema.MetaData.create_all`. r1Nr2r4r]r]r^r5s z Index.createcCs|jtj||ddS)zIssue a ``DROP`` statement for this :class:`.Index`, using the given :class:`.Connection` or :class:`.Engine` for connectivity. .. seealso:: :meth:`_schema.MetaData.drop_all`. r1Nr6r4r]r]r^r7s z Index.dropr_rcCs6ddt|jgdd|jD|jr,dgp.gS)Nz Index(%s)rcSsg|] }t|qSr]r)rer]r]r^rsz"Index.__repr__..z unique=True)rrrbrjr>rr]r]r^rs zIndex.__repr__)F)F) rWrXrYrrrrr,r5r7rr]r]r]r^rGs E"B  rGc@s6eZdZUded<ded<ded<ded<ded<dS)_NamingSchemaTD_NamingSchemaDirectiver~pkixZckZuqN)rWrXrYrr]r]r]r^rls rlF)totalrozix_%(column_0_label)s_NamingSchemaParameterDEFAULT_NAMING_CONVENTIONc @sfeZdZUdZdZdAdddddd d d Zd ed <ddddZdddddZdddddddZ ddddddZ dddd Z ddd!d"d#Z ddd$d%Z ddd&d'd(Zed)dd*d+ZedBd-ddd.dddd/dd0 d1d2ZedCd3ddd.dddd/dd0 d4d2Zed5dDd8ddd.dddd/dd0 d9d2ZdEd:d;ddd<d=d>ZdFd:d;ddd<d?d@ZdS)GraDA 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 rNr`rz Optional[_NamingSchemaParameter]r^ry)rcrnaming_conventionrrdcCsv|dk r(t|ts(tdt|dt|_t |||_ |rH|nt |_ |rX||_ t|_i|_tt|_dS)aCreate a new MetaData object. :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. :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. Nz-expected schema argument to be a string, got re)ror_r1r~rjr3Z FacadeDictrr*rrcrrrsrr_schemasr" collections defaultdictrdr)rrcrrsrr]r]r^rs y zMetaData.__init__zutil.FacadeDict[str, Table]rr_rcCsdS)Nz MetaData()r]rr]r]r^rszMetaData.__repr__zUnion[str, Table]r) table_or_keyrdcCst|ts|j}||jkSrn)ror_rrr)rrwr]r]r^rDs zMetaData.__contains__rS)rbrcrqrdcCs,t||}|j|||r(|j|dSrn)rfrZ _insert_itemrtr )rrbrcrqrrr]r]r^rs zMetaData._add_tableracCsXt||}t|j|d}|dk r8|jD]}||q(|jrTdd|jD|_dS)NcSsh|]}|jdk r|jqSrnr)rtr]r]r^rs z)MetaData._remove_table..)rfdictrrrrrtrs)rrbrcrrZremovedr~r]r]r^rs   zMetaData._remove_tablezDict[str, Any]cCs|j|j|j|j|j|jdS)N)rrcschemas sequencesfk_memosrs)rrcrtr"rrsrr]r]r^ __getstate__szMetaData.__getstate__)rrdcCs@|d|_|d|_|d|_|d|_|d|_|d|_dS)Nrrcrsr{rzr|)rrcrsr"rtr)rrr]r]r^ __setstate__s      zMetaData.__setstate__cCs$t|j|j|jdS)z+Clear all Table objects from this MetaData.N)ryclearrrtrrr]r]r^rs  zMetaData.clearrcCs||j|jdS)z1Remove the given Table object from this MetaData.N)rrbrcr!r]r]r^rszMetaData.removez List[Table]cCstt|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|jSrnr)rxr]r]r^rrz(MetaData.sorted_tables..r)rZ sort_tablesrrrsrr]r]r^ sorted_tabless3zMetaData.sorted_tables.rGzCUnion[_typing_Sequence[str], Callable[[str, MetaData], bool], None]r) r/rcviewsonlyrrrrardc KsdSrnr] rr/rcrrrrrrar]r]r^reflects zMetaData.reflectrFc KsdSrnr]rr]r]r^r s zsqlalchemy.engine.reflectionFTrc s0t|} | ||td} | |dkr<jdk rL| d<tjjj j } t | |rtjjj j } | z| Wntk rYnXdk rt fddD} n} tjdkrfddt| D} ntr2fddt| D} nhfddD}|rrZd p\d }d |}td |j|d |dfddD} | jf| | tjjjj d|}|| d<| D]V}zt|f| Wn<tjk r}ztd|d|W5d}~XYnXqW5QRXdS)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:`.Connection` or :class:`.Engine` used to access the database. :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 (materialized and plain). :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`. :param autoload_replace: Passed along to each :class:`_schema.Table` as :paramref:`_schema.Table.autoload_replace`. :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. .. seealso:: :ref:`metadata_reflection_toplevel` :meth:`_events.DDLEvents.column_reflect` - Event used to customize the reflected columns. Usually used to generalize the types using :meth:`_types.TypeEngine.as_generic` :ref:`metadata_reflection_dbagnostic_types` - describes how to reflect tables using general types. )rrrrrNrccsg|]}d|qS)rer]rrbrr]r^rsz$MetaData.reflect..cs g|]\}}s|kr|qSr]r]rrbZschnamecurrentrr]r^rscs*g|]"\}}s|kr|r|qSr]r]r)rrrrr]r^rs  csg|]}|kr|qSr]r]r) availabler]r^rsz schema '%s'rrz7Could not reflect: requested table(s) not available in z: (rcsg|]}s|kr|qSr]r]rrr]r^rs)rcZ filter_namesrkindscoperzSkipping table z: )r2rrrrrcr3rZengine_reflectionZ ObjectKindZTABLEZ OrderedSetZget_table_namesANYZget_view_namesZget_materialized_view_namesrrrXrrr1rengineZ_get_reflection_infoZ ObjectScoperSZUnreflectableTableErrorr@)rr/rcrrrrrrarZ reflect_optsrZavailable_w_schemaloadmissingsZ missing_strrrbZuerrr])rrrrrcrr^rs|c          r-z!Optional[_typing_Sequence[Table]])r/rr0rdcCs|jtj|||ddS)aDCreate 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:`.Connection` or :class:`.Engine` used to access the database. :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. r0rNr2rr/rr0r]r]r^ create_alls zMetaData.create_allcCs|jtj|||ddS)a?Drop 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:`.Connection` or :class:`.Engine` used to access the database. :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. rNr6rr]r]r^drop_alls zMetaData.drop_all)NNNN)......)......)NFNFTT)NT)NT)rWrXrYrrrrrrDrrr}r~rrrNrrrr3rrrr]r]r]r^rsd   8"""9rc@seZdZUdZdZded<edddd"d d d d d dZddd dddZdddddZ e ddddddddddZ ddddddd d!Z dS)#raDefines 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', metadata_obj, 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_columnrr#rQz:class:`.Computed`z:paramref:`.Computed.sqltext`Nr<rry)rQ persistedrdcCs 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)rrrrRrQrr#)rrQrr]r]r^r&s"zComputed.__init__r%rr*cKs`t|tstt|jtdtfr6t|jtdtfs@td||_ ||_ ||j _||j _dS)NzPA generated column cannot specify a server_default or a server_onupdate argument) rorprrrjrrXr1r~r#rhrr]r]r^r,Ls zComputed._set_parentrrTrcCs|Srnr]rr]r]r^rm[szComputed._as_for_updaterz_The :meth:`_schema.Computed.copy` method is deprecated and will be removed in a future release.rErhrFcKs|jfd|i|SrGrrHr]r]r^r^sz Computed.copycKs8t|j|jdk r|jjnd|}t||jd}||S)N)r)rvrQr#rqrrr)rrkrmrQgr]r]r^rBhszComputed._copy)N)rWrXrYrrrr&rr,rmr3rPrrBr]r]r]r^r s( #rc@seZdZdZdZdZddddddddddddd d d d Zd dd dddZdddddZe dddddddZ dddddZ 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', metadata_obj, Column('id', Integer, Identity()) Column('description', Text), ) See the linked documentation below for complete details. .. versionadded:: 1.4 .. seealso:: :ref:`identity_ddl` Zidentity_columnTFNrrrry) alwayson_nullrrrrrrrrrrdc 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. rN)r rrrr#) rrrrrrrrrrrrr]r]r^rs; zIdentity.__init__r%rr*cKsvt|tstt|jtdtfr2t|jtdst|j|j|j|j|j|j|j|j|j |j |j d }| |S)N) rrrrrrrrrrr) rrrrrrrrrrrrr)rrmir]r]r^rBszIdentity._copy) FNNNNNNNNNN) rWrXrYrrrrr,rmr3rPrrBr]r]r]r^rus.&Kr)NN)r __future__rabcrruenumroperatorrLrrrrr r r r r rrrrrorrrrrrrrrrrbaserrrr r!r"r#r$r%r&rVr'r(r)r*r+rr,r-r.r0r1r2r3r4Z util.typingr5r6r7r8r9r:Z_typingr;r<r=r>r?r@r,rArBZ functionsrCrDrErrFrGZengine.interfacesrHrIrJZ engine.mockrKZengine.reflectionrLZsql.selectablerMrNrPrRr-r_rZ_ServerDefaultArgumentZ_ServerOnUpdateArgumentrUrZrr[r\rfrvZ_self_inspectsZ VisitablerQrrZ InspectablerSrprZrr rr attrgetterrrlrrrrrrr rTrnr)r.rBrPrCrrrGZ_NamingSchemaCallablermrlrqZ immutabledictrrrrrr]r]r]r^s                                                                             #    -3 !123   ?V& 49<,s|o/i Q    =j