U ofp @szddlmZddlmZddlZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZerNddlmZddl m!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'l)m.Z.dd(l)m/Z/dd)l)m0Z0dd*l)m1Z1dd+l)m2Z2dd,l)m3Z3dd-l)m4Z4dd.l)m5Z5dd/l6m7Z7dd0l8m9Z9dd1l:m;Z;dd2lm?Z?ed4ed5Z@ed6d7d5ZAGd8d9d9ZBGd:d7d7eBZCeDd;eDd;d<Gd=d>d>eBZEeDd?eDd?d@eCFdAGdBdCdCeCZGeDdDeDdDdEeCFdFGdGdHdHeCZHeDdIeDdIdJeCFdKGdLdMdMeCZIeDdNeDdNdOeCFdPeCFdQeCFdRGdSdTdTeCZJeDdUeDdUdVGdWdXdXeBZKeDdYeDdYdZGd[d\d\eBZLeDd]Gd^d_d_eBZMeDd`GdadbdbeBZNGdcddddeBZOeDdeGdfdgdgeOZPeDdheDdhdiGdjdkdkeOZQeDdleDdldmGdndodoeOZReDdpeDdpdqGdrdsdseOZSeDdteDdtduGdvdwdweOZTeDdxeDdxdyGdzd{d{eOZUeDd|Gd}d~d~eBZVeDdeDddGdddeBZWGdddeBZXGdddeXZYGdddeXZZGdddeXZ[GdddeBZ\dS)) annotations)abstractmethodN)Any)Callable)cast)Dict) FrozenSet)Iterator)List)MutableMapping)Optional)Sequence)Set)Tuple)Type) TYPE_CHECKING)TypeVar)Union)NULLTYPE) schemaobj)BatchOperations) Operations)util) sqla_compat)Literal) Executable) ColumnElement)conv) quoted_name) TextClause)Function)CheckConstraint)Column)Computed) Constraint)ForeignKeyConstraint)Identity)Index)MetaData)PrimaryKeyConstraint) SchemaItem)Table)UniqueConstraint) TableClause) TypeEngine)Rewriter)MigrationContext) _RevIdType_T)bound_ACAddConstraintOpc@sPeZdZUdZejddddZeZde d<dddd Z d dd d Z d S)MigrateOperationzbase class for migration command and organization objects. This system is part of the operation extensibility API. .. seealso:: :ref:`operation_objects` :ref:`operation_plugins` :ref:`customizing_revision` zDict[Any, Any]returncCsiS)zA dictionary that may be used to store arbitrary information along with this :class:`.MigrateOperation` object. selfr;r;D/opt/hc_python/lib/python3.8/site-packages/alembic/operations/ops.pyinfoMszMigrateOperation.infozFrozenSet[Rewriter] _mutationscCstdSNNotImplementedErrorr<r;r;r>reverseWszMigrateOperation.reverseTuple[Any, ...]cCstdSrArBr<r;r;r> to_diff_tupleZszMigrateOperation.to_diff_tupleN) __name__ __module__ __qualname____doc__rZmemoized_propertyr? frozensetr@__annotations__rDrFr;r;r;r>r8>s r8c@seZdZdZeZeddddZe ddddd Z e d dd d d Z e ddd dddZ ddddZddddZdS)r7z&Represent an add constraint operation.strr9cCs tdSrArBr<r;r;r>constraint_typecszAddConstraintOp.constraint_typez Callable[[Type[_AC]], Type[_AC]])type_r:csdddfdd }|S)Nz Type[_AC])klassr:csj|j|SrA)add_constraint_opsZ dispatch_forfrom_constraint)rPclsrOr;r>goksz3AddConstraintOp.register_add_constraint..gor;)rTrOrUr;rSr>register_add_constraintgsz'AddConstraintOp.register_add_constraintr& constraintr:cCs|j|j|SrA)rQdispatch__visit_name__)rTrXr;r;r>rRqs zAddConstraintOp.from_constraintNOptional[MigrationContext]migration_contextr:cCsdSrAr;)r=r]r;r;r> to_constraintwszAddConstraintOp.to_constraintDropConstraintOpcCst|SrA)r_rRr^r<r;r;r>rD}szAddConstraintOp.reversezTuple[str, Constraint]cCs d|fS)NZadd_constraintr^r<r;r;r>rFszAddConstraintOp.to_diff_tuple)N)rGrHrIrJrZ DispatcherrQpropertyrN classmethodrVrRrr^rDrFr;r;r;r>r7^s drop_constraintbatch_drop_constraintc @seZdZdZd"dddddddddd d d Zd d ddZdd ddZedddddZdd ddZ ed#dddddddddddZ ed$dddddd d!Z dS)%r_z&Represent a drop constraint operation.Nschema_reverse,Optional[sqla_compat._ConstraintNameDefined]rM Optional[str]zOptional[AddConstraintOp]None)constraint_name table_namerOrfrgr:cCs"||_||_||_||_||_dSrA)rkrlrNrfrg)r=rkrlrOrfrgr;r;r>__init__s zDropConstraintOp.__init__r7r9cCst|SrA)r7rRr^r<r;r;r>rDszDropConstraintOp.reversezTuple[str, SchemaItem]cCs&|jdkrd|fSd|fSdS)N foreignkeyZ remove_fkZremove_constraint)rNr^r<r;r;r>rFs  zDropConstraintOp.to_diff_tupler&rWcCsHddddddd}t|}|t|j|j|j||jt|dS)Nuniquernprimarycheck)unique_constraintforeign_key_constraintprimary_key_constraintcheck_constraintcolumn_check_constraint table_or_column_check_constraint)rfrOrg) r_table_for_constraintconstraint_name_or_nonenamerfgetrZr7rR)rTrXtypesconstraint_tabler;r;r>rRs   z DropConstraintOp.from_constraintcCsF|jdk r:|j}|j|_t|}|j|_|j|_|StddS)NzAconstraint cannot be produced; original constraint is not present) rgr^rkrzrrxrlrf ValueError)r=rXr}r;r;r>r^s   zDropConstraintOp.to_constraintrfr) operationsrkrlrOrfr:cCs|||||d}||S)a Drop a constraint of the given name, typically via DROP CONSTRAINT. :param constraint_name: name of the constraint. :param table_name: table name. :param type\_: optional, required on MySQL. can be 'foreignkey', 'primary', 'unique', or 'check'. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. rOrfinvoke)rTrrkrlrOrfopr;r;r>rcsz DropConstraintOp.drop_constraintr)rrkrOr:cCs"|||jj||jjd}||S)aIssue a "drop constraint" instruction using the current batch migration context. The batch form of this call omits the ``table_name`` and ``schema`` arguments from the call. .. seealso:: :meth:`.Operations.drop_constraint` rimplrlrfr)rTrrkrOrr;r;r>rdsz&DropConstraintOp.batch_drop_constraint)N)N)N) rGrHrIrJrmrDrFrbrRr^rcrdr;r;r;r>r_s&r_create_primary_keybatch_create_primary_keyrtc @seZdZdZdZddddddd d d d d ZedddddZd dddddZedddddddd dddZ edddd dddZ dS)!CreatePrimaryKeyOpz)Represent a create primary key operation.Z primarykeyNrrhrM Sequence[str]rirrjrkrlcolumnsrfkwr:cKs"||_||_||_||_||_dSrArkrlrrfrr=rkrlrrfrr;r;r>rms zCreatePrimaryKeyOp.__init__r&rWcCs@t|}td|}|t|j|j|jfd|ji|jS)Nr+rf) rrxrryrzrkeysrfdialect_kwargs)rTrXr}Z pk_constraintr;r;r>rRs   z"CreatePrimaryKeyOp.from_constraintr[r+r\cCs.t|}|j|j|j|jfd|ji|jSNrf)r SchemaObjectsrtrkrlrrfrr=r] schema_objr;r;r>r^ s z CreatePrimaryKeyOp.to_constraintr List[str])rrkrlrrfr:cCs|||||d}||S)a"Issue a "create primary key" instruction using the current migration context. e.g.:: from alembic import op op.create_primary_key("pk_my_table", "my_table", ["id", "version"]) This internally generates a :class:`~sqlalchemy.schema.Table` object containing the necessary columns, then generates a new :class:`~sqlalchemy.schema.PrimaryKeyConstraint` object which it then associates with the :class:`~sqlalchemy.schema.Table`. Any event listeners associated with this action will be fired off normally. The :class:`~sqlalchemy.schema.AddConstraint` construct is ultimately used to generate the ALTER statement. :param constraint_name: Name of the primary key constraint. The name is necessary so that an ALTER statement can be emitted. For setups that use an automated naming scheme such as that described at :ref:`sqla:constraint_naming_conventions` ``name`` here can be ``None``, as the event listener will apply the name to the constraint object when it is associated with the table. :param table_name: String name of the target table. :param columns: a list of string column names to be applied to the primary key constraint. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. rr)rTrrkrlrrfrr;r;r>r-s,z%CreatePrimaryKeyOp.create_primary_keyr)rrkrr:cCs"|||jj||jjd}||S)aIssue a "create primary key" instruction using the current batch migration context. The batch form of this call omits the ``table_name`` and ``schema`` arguments from the call. .. seealso:: :meth:`.Operations.create_primary_key` rr)rTrrkrrr;r;r>r\sz+CreatePrimaryKeyOp.batch_create_primary_key)N) rGrHrIrJrNrmrbrRr^rrr;r;r;r>rs  .rcreate_unique_constraintbatch_create_unique_constraintrrc @seZdZdZdZddddddd d d d d ZedddddZddddddZedddddddd d dddZ edddd d dddZ dS) CreateUniqueConstraintOpz/Represent a create unique constraint operation.roNrrhrMrrirrjrcKs"||_||_||_||_||_dSrArrr;r;r>rms z!CreateUniqueConstraintOp.__init__r&rWcCstt|}td|}i}|jr(|j|d<|jr8|j|d<||j|t|j|jdd|j Dfd|j i|S)Nr. deferrable initiallycSsg|] }|jqSr;)rz).0cr;r;r> sz.rf) rrxrrrupdaterryrzrrf)rTrXr}Z uq_constraintrr;r;r>rRs"      z(CreateUniqueConstraintOp.from_constraintr[r.r\cCs.t|}|j|j|j|jfd|ji|jSr)rrrrrkrlrrfrrr;r;r>r^s z&CreateUniqueConstraintOp.to_constraintr)rrkrlrrfrr:cKs"||||fd|i|}||S)aIssue a "create unique constraint" instruction using the current migration context. e.g.:: from alembic import op op.create_unique_constraint("uq_user_name", "user", ["name"]) This internally generates a :class:`~sqlalchemy.schema.Table` object containing the necessary columns, then generates a new :class:`~sqlalchemy.schema.UniqueConstraint` object which it then associates with the :class:`~sqlalchemy.schema.Table`. Any event listeners associated with this action will be fired off normally. The :class:`~sqlalchemy.schema.AddConstraint` construct is ultimately used to generate the ALTER statement. :param name: Name of the unique constraint. The name is necessary so that an ALTER statement can be emitted. For setups that use an automated naming scheme such as that described at :ref:`sqla:constraint_naming_conventions`, ``name`` here can be ``None``, as the event listener will apply the name to the constraint object when it is associated with the table. :param table_name: String name of the source table. :param columns: a list of string column names in the source table. :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 schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. rfr)rTrrkrlrrfrrr;r;r>rs1z1CreateUniqueConstraintOp.create_unique_constraintr)rrkrrr:cKs*|jj|d<|||jj|f|}||S)a%Issue a "create unique constraint" instruction using the current batch migration context. The batch form of this call omits the ``source`` and ``schema`` arguments from the call. .. seealso:: :meth:`.Operations.create_unique_constraint` rf)rrfrlr)rTrrkrrrr;r;r>rs z7CreateUniqueConstraintOp.batch_create_unique_constraint)N) rGrHrIrJrNrmrbrRr^rrr;r;r;r>rws  3rcreate_foreign_keybatch_create_foreign_keyrsc@seZdZdZdZddddddddd d Zd d d dZedddddZd%dddddZ eddddddddddddddddddddddddddZ eddddddd d!ddddddddddddd" d#d$Z dS)&CreateForeignKeyOpz4Represent a create foreign key constraint operation.rnrhrMrrrj)rk source_tablereferent_table local_cols remote_colsrr:cKs(||_||_||_||_||_||_dSrA)rkrrrrr)r=rkrrrrrr;r;r>rms zCreateForeignKeyOp.__init__z Tuple[str, ForeignKeyConstraint]r9cCs d|fS)NZadd_fkr`r<r;r;r>rFsz CreateForeignKeyOp.to_diff_tupler&rWc Cstd|}i}|jr|j|d<|jr.|j|d<|jr>|j|d<|jrN|j|d<|jr^|j|d<|jrn|j|d<t|\ }}}}}} } } } } ||d<||d <| |j |t |j |||| f|S) Nr'onupdateondeleterr use_altermatch source_schemareferent_schema) rrrrrrrrZ_fk_specrrryrz)rTrXZ fk_constraintrrrZsource_columnsZ target_schemaZ target_tableZtarget_columnsrrrrr;r;r>rRsL         z"CreateForeignKeyOp.from_constraintNr[r'r\cCs,t|}|j|j|j|j|j|jf|jSrA) rrrsrkrrrrrrr;r;r>r^Es z CreateForeignKeyOp.to_constraint)rrrrrrrrriOptional[bool])rrkrrrrrrrrrrr dialect_kwr:c Ks2||||||f||| | | | | d|}||S)aIssue a "create foreign key" instruction using the current migration context. e.g.:: from alembic import op op.create_foreign_key( "fk_user_address", "address", "user", ["user_id"], ["id"], ) This internally generates a :class:`~sqlalchemy.schema.Table` object containing the necessary columns, then generates a new :class:`~sqlalchemy.schema.ForeignKeyConstraint` object which it then associates with the :class:`~sqlalchemy.schema.Table`. Any event listeners associated with this action will be fired off normally. The :class:`~sqlalchemy.schema.AddConstraint` construct is ultimately used to generate the ALTER statement. :param constraint_name: Name of the foreign key constraint. The name is necessary so that an ALTER statement can be emitted. For setups that use an automated naming scheme such as that described at :ref:`sqla:constraint_naming_conventions`, ``name`` here can be ``None``, as the event listener will apply the name to the constraint object when it is associated with the table. :param source_table: String name of the source table. :param referent_table: String name of the destination table. :param local_cols: a list of string column names in the source table. :param remote_cols: a list of string column names in the remote table. :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 source_schema: Optional schema name of the source table. :param referent_schema: Optional schema name of the destination table. rrrrrrrr)rTrrkrrrrrrrrrrrrrr;r;r>rRs$E z%CreateForeignKeyOp.create_foreign_key)rrrrrrr) rrkrrrrrrrrrrr:c Ks:|||jj|||f||| |jj|| | d| } || S)a+Issue a "create foreign key" instruction using the current batch migration context. The batch form of this call omits the ``source`` and ``source_schema`` arguments from the call. e.g.:: with batch_alter_table("address") as batch_op: batch_op.create_foreign_key( "fk_user_address", "user", ["user_id"], ["id"], ) .. seealso:: :meth:`.Operations.create_foreign_key` rr)rTrrkrrrrrrrrrrrr;r;r>rs$& z+CreateForeignKeyOp.batch_create_foreign_key)N) rGrHrIrJrNrmrFrbrRr^rrr;r;r;r>rs2*  0U rcreate_check_constraintbatch_create_check_constraintrurwrvc @seZdZdZdZddddddd d d d d ZedddddZd dddddZedddddddd d dddZ edddd d dddZ dS)!CreateCheckConstraintOpz.Represent a create check constraint operation.rqNrrhrMz*Union[str, TextClause, ColumnElement[Any]]rirrj)rkrl conditionrfrr:cKs"||_||_||_||_||_dSrA)rkrlrrfr)r=rkrlrrfrr;r;r>rms z CreateCheckConstraintOp.__init__r&rWcCsBt|}td|}|t|j|jtd|jfd|ji|jS)Nr#zColumnElement[Any]rf)rrxrryrzsqltextrfr)rTrXr}Z ck_constraintr;r;r>rRs    z'CreateCheckConstraintOp.from_constraintr[r#r\cCs.t|}|j|j|j|jfd|ji|jSr)rrrurkrlrrfrrr;r;r>r^ s z%CreateCheckConstraintOp.to_constraintrz+Union[str, ColumnElement[bool], TextClause])rrkrlrrfrr:cKs"||||fd|i|}||S)aIssue a "create check constraint" instruction using the current migration context. e.g.:: from alembic import op from sqlalchemy.sql import column, func op.create_check_constraint( "ck_user_name_len", "user", func.len(column("name")) > 5, ) CHECK constraints are usually against a SQL expression, so ad-hoc table metadata is usually needed. The function will convert the given arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound to an anonymous table in order to emit the CREATE statement. :param name: Name of the check constraint. The name is necessary so that an ALTER statement can be emitted. For setups that use an automated naming scheme such as that described at :ref:`sqla:constraint_naming_conventions`, ``name`` here can be ``None``, as the event listener will apply the name to the constraint object when it is associated with the table. :param table_name: String name of the source table. :param condition: SQL expression that's the condition of the constraint. Can be a string or SQLAlchemy expression language structure. :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 schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. rfr)rTrrkrlrrfrrr;r;r>rs3z/CreateCheckConstraintOp.create_check_constraintr)rrkrrr:cKs*|||jj|fd|jji|}||S)a#Issue a "create check constraint" instruction using the current batch migration context. The batch form of this call omits the ``source`` and ``schema`` arguments from the call. .. seealso:: :meth:`.Operations.create_check_constraint` rfr)rTrrkrrrr;r;r>rLsz5CreateCheckConstraintOp.batch_create_check_constraint)N) rGrHrIrJrNrmrbrRr^rrr;r;r;r>rs  5r create_indexbatch_create_indexc @seZdZdZdddddddddd d d d d dZddddZddddZedddddZd(dddddZ eddddddddddd d d d d!d"Z ed#dd$d d d%d&d'Z dS)) CreateIndexOpz#Represent a create index operation.NFrfro if_not_existsrirMz4Sequence[Union[str, TextClause, ColumnElement[Any]]]boolrrrj) index_namerlrrfrorrr:cKs.||_||_||_||_||_||_||_dSrA)rrlrrfrorr)r=rrlrrfrorrr;r;r>rmns zCreateIndexOp.__init__ DropIndexOpr9cCst|SrA)r from_indexto_indexr<r;r;r>rDszCreateIndexOp.reverseTuple[str, Index]cCs d|fS)NZ add_indexrr<r;r;r>rFszCreateIndexOp.to_diff_tupler)indexr:cCs8|jdk st||j|jj|jf|jj|jd|jSN)rfro)tableAssertionErrorrzZ expressionsrfrokwargsrTrr;r;r>rszCreateIndexOp.from_indexr[r\cCs6t|}|j|j|j|jf|j|jd|j}|Sr) rrrrrlrrfror)r=r]ridxr;r;r>rs zCreateIndexOp.to_indexrz/Sequence[Union[str, TextClause, Function[Any]]]) rrrlrrfrorrr:c Ks&||||f|||d|} || S)aIssue a "create index" instruction using the current migration context. e.g.:: from alembic import op op.create_index("ik_test", "t1", ["foo", "bar"]) Functional indexes can be produced by using the :func:`sqlalchemy.sql.expression.text` construct:: from alembic import op from sqlalchemy import text op.create_index("ik_test", "t1", [text("lower(foo)")]) :param index_name: name of the index. :param table_name: name of the owning table. :param columns: a list consisting of string column names and/or :func:`~sqlalchemy.sql.expression.text` constructs. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. :param unique: If True, create a unique index. :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 if_not_exists: If True, adds IF NOT EXISTS operator when creating the new index. .. versionadded:: 1.12.0 :param \**kw: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``_``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. rr) rTrrrlrrfrorrrr;r;r>rs< zCreateIndexOp.create_indexrr)rrrrr:cKs*|||jj|fd|jji|}||S)zIssue a "create index" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.create_index` rfr)rTrrrrrr;r;r>rsz CreateIndexOp.batch_create_index)N) rGrHrIrJrmrDrFrbrrrrr;r;r;r>ris$  $Fr drop_indexbatch_drop_indexc @seZdZdZd&ddddddddddd d d d Zd dddZddddZedddddZd'dddddZ ed(dddddddddd dd d!Z ed"ddd d#d$d%Z dS))rz!Represent a drop index operation.N)rf if_existsrgzUnion[quoted_name, str, conv]rirzOptional[CreateIndexOp]rrj)rrlrfrrgrr:cKs(||_||_||_||_||_||_dSrA)rrlrfrrgr)r=rrlrfrrgrr;r;r>rm s zDropIndexOp.__init__rr9cCs d|fS)NZ remove_indexrr<r;r;r>rFszDropIndexOp.to_diff_tuplercCst|SrA)rrrr<r;r;r>rDszDropIndexOp.reverser)rcCs<|jdk st||jf|jj|jjt||jd|jS)N)rlrfrgro)rrrzrfrrrorrr;r;r>r szDropIndexOp.from_indexr[r\cCs<t|}|j|j|j|jr$|jjndgfd|ji|jS)Nxrf) rrrrrlrgrrfrrr;r;r>r,s zDropIndexOp.to_index)rfrrrM)rrrlrfrrr:cKs"||f|||d|}||S)aIssue a "drop index" instruction using the current migration context. e.g.:: drop_index("accounts") :param index_name: name of the index. :param table_name: name of the owning table. Some backends such as Microsoft SQL Server require this. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. :param if_exists: If True, adds IF EXISTS operator when dropping the index. .. versionadded:: 1.12.0 :param \**kw: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``_``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. )rlrfrr)rTrrrlrfrrrr;r;r>r;s&zDropIndexOp.drop_indexr)rrrr:cKs(||f|jj|jjd|}||S)zIssue a "drop index" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.drop_index` rlrfr)rTrrrrr;r;r>rjs zDropIndexOp.batch_drop_index)N)N)N) rGrHrIrJrmrFrDrbrrrrr;r;r;r>rs*  .r create_tablec @seZdZdZddddddddd d d d d dZddddZddddZeddddddddZd$dddddZ eddd d dd!d"d#Z dS)% CreateTableOpz#Represent a create table operation.NF)rf_namespace_metadata_constraints_includedrMzSequence[SchemaItem]riOptional[MetaData]rrrj)rlrrfrrrr:cKsR||_||_||_|di|_|dd|_|dd|_||_||_||_ dS)Nr?commentprefixes) rlrrfpopr?rrrrr)r=rlrrfrrrr;r;r>rms zCreateTableOp.__init__ DropTableOpr9cCstj||jdS)Nr)r from_tableto_tablerr<r;r;r>rDszCreateTableOp.reverseTuple[str, Table]cCs d|fS)NZ add_tablerr<r;r;r>rFszCreateTableOp.to_diff_tuplerr-rrr:c CsR|dkr|j}||jt|jt|jf|j|d|jt|jt|j d|j S)NT)rfrrrr?r) metadatarzlistr constraintsrfrdictr? _prefixesrrTrrr;r;r>rszCreateTableOp.from_tabler[r\cCsXt|}|j|jf|j|j|jr.t|jng|j|j rD|j ni|j d|j S)N)rfrrr?r) rrrrlrrfrrrr?copyrrrr;r;r>rs zCreateTableOp.to_tablerr,)rrlrrr:cOs|||f|}||S)aM Issue a "create table" instruction using the current migration context. This directive receives an argument list similar to that of the traditional :class:`sqlalchemy.schema.Table` construct, but without the metadata:: from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column from alembic import op op.create_table( "account", Column("id", INTEGER, primary_key=True), Column("name", VARCHAR(50), nullable=False), Column("description", NVARCHAR(200)), Column("timestamp", TIMESTAMP, server_default=func.now()), ) Note that :meth:`.create_table` accepts :class:`~sqlalchemy.schema.Column` constructs directly from the SQLAlchemy library. In particular, default values to be created on the database side are specified using the ``server_default`` parameter, and not ``default`` which only specifies Python-side defaults:: from alembic import op from sqlalchemy import Column, TIMESTAMP, func # specify "DEFAULT NOW" along with the "timestamp" column op.create_table( "account", Column("id", INTEGER, primary_key=True), Column("timestamp", TIMESTAMP, server_default=func.now()), ) The function also returns a newly created :class:`~sqlalchemy.schema.Table` object, corresponding to the table specification given, which is suitable for immediate SQL operations, in particular :meth:`.Operations.bulk_insert`:: from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column from alembic import op account_table = op.create_table( "account", Column("id", INTEGER, primary_key=True), Column("name", VARCHAR(50), nullable=False), Column("description", NVARCHAR(200)), Column("timestamp", TIMESTAMP, server_default=func.now()), ) op.bulk_insert( account_table, [ {"name": "A1", "description": "account 1"}, {"name": "A2", "description": "account 2"}, ], ) :param table_name: Name of the table :param \*columns: collection of :class:`~sqlalchemy.schema.Column` objects within the table, as well as optional :class:`~sqlalchemy.schema.Constraint` objects and :class:`~.sqlalchemy.schema.Index` objects. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. :param \**kw: Other keyword arguments are passed to the underlying :class:`sqlalchemy.schema.Table` object created for the command. :return: the :class:`~sqlalchemy.schema.Table` object corresponding to the parameters given. r)rTrrlrrrr;r;r>rsUzCreateTableOp.create_table)N) rGrHrIrJrmrDrFrbrrrr;r;r;r>rsr drop_tablec@seZdZdZdddddddddd d d Zd d ddZdd ddZeddddddddZd#dddddZ edddddddd d!d"Z dS)$rz!Represent a drop table operation.Nrftable_kwrgrMriz"Optional[MutableMapping[Any, Any]]zOptional[CreateTableOp]rj)rlrfrrgr:cCsP||_||_|pi|_|jdd|_|jdd|_|jdd|_||_dS)Nrr?r)rlrfrrrr?rrg)r=rlrfrrgr;r;r>rm&s zDropTableOp.__init__rr9cCs d|fS)NZ remove_tablerr<r;r;r>rF6szDropTableOp.to_diff_tuplercCst|SrA)rrrr<r;r;r>rD9szDropTableOp.reverserr-rrcCs:||j|j|jt|jt|jd|jtj ||ddS)N)rr?rrr) rzrfrrr?rrrrrrr;r;r>r<szDropTableOp.from_tabler[r\cCsz|jr|jj}ng}t|}|j|jf||j|jr@|jni|j rRt |j ng|j |jrf|jj ndd|j }|S)NF)rr?rrfr)rgrrrrrlrr?rrrrfrr)r=r]Zcols_and_constraintsrtr;r;r>rNs$    zDropTableOp.to_tablerrr)rrlrfrr:cKs||||d}||dS)a8Issue a "drop table" instruction using the current migration context. e.g.:: drop_table("accounts") :param table_name: Name of the table :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. :param \**kw: Other keyword arguments are passed to the underlying :class:`sqlalchemy.schema.Table` object created for the command. )rfrNr)rTrrlrfrrr;r;r>reszDropTableOp.drop_table)N) rGrHrIrJrmrFrDrbrrrr;r;r;r>r"src@s(eZdZdZdddddddd ZdS) AlterTableOpz#Represent an alter table operation.NrrMrirj)rlrfr:cCs||_||_dSrAr)r=rlrfr;r;r>rmszAlterTableOp.__init__)rGrHrIrJrmr;r;r;r>rsr rename_tablecsReZdZdZdddddddfdd Zeddd ddddd d d ZZS) RenameTableOpz#Represent a rename table operation.NrrMrirj)old_table_namenew_table_namerfr:cstj||d||_dSNr)superrmr)r=rrrf __class__r;r>rmszRenameTableOp.__init__r)rrrrfr:cCs||||d}||S)alEmit an ALTER TABLE to rename a table. :param old_table_name: old name. :param new_table_name: new name. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. rr)rTrrrrfrr;r;r>rszRenameTableOp.rename_table)rGrHrIrJrmrbr __classcell__r;r;rr>rs  rcreate_table_commentbatch_create_table_commentc @seZdZdZddddddddddd Zeddd d dddddd d dZedddddddddZddddZd dddddZ ddddZ dS)!CreateTableCommentOpz)Represent a COMMENT ON `table` operation.Nrfexisting_commentrMrirj)rlrrfrr:cCs||_||_||_||_dSrA)rlrrrf)r=rlrrfrr;r;r>rmszCreateTableCommentOp.__init__rrfr)rrlrrrfr:cCs|||||d}||S)aQEmit a COMMENT ON operation to set the comment for a table. :param table_name: string name of the target table. :param comment: string value of the comment being registered against the specified table. :param existing_comment: String value of a comment already registered on the specified table, used within autogenerate so that the operation is reversible, but not required for direct use. .. seealso:: :meth:`.Operations.drop_table_comment` :paramref:`.Operations.alter_column.comment` rr)rTrrlrrrfrr;r;r>rsz)CreateTableCommentOp.create_table_commentrr)rrrr:cCs"||jj|||jjd}||S)aEmit a COMMENT ON operation to set the comment for a table using the current batch migration context. :param comment: string value of the comment being registered against the specified table. :param existing_comment: String value of a comment already registered on the specified table, used within autogenerate so that the operation is reversible, but not required for direct use. rr)rTrrrrr;r;r>rsz/CreateTableCommentOp.batch_create_table_commentz/Union[CreateTableCommentOp, DropTableCommentOp]r9cCs:|jdkrt|j|j|jdSt|j|j|j|jdSdS)2Reverses the COMMENT ON operation against a table.Nr)rDropTableCommentOprlrrfrr<r;r;r>rD s zCreateTableCommentOp.reverser[r-r\cCs t|}|j|j|j|jdS)N)rfr)rrrrlrfrrr;r;r>rs  zCreateTableCommentOp.to_tablerEcCsd||jfS)NZadd_table_comment)rrr<r;r;r>rF"sz"CreateTableCommentOp.to_diff_tuple)N) rGrHrIrJrmrbrrrDrrFr;r;r;r>rs # rdrop_table_commentbatch_drop_table_commentc@seZdZdZdddddddddd Zeddd d ddddd d dZeddddddddZddddZd dddddZ ddddZ dS)!rz:Represent an operation to remove the comment from a table.NrrMrirj)rlrfrr:cCs||_||_||_dSrA)rlrrf)r=rlrfrr;r;r>rm-szDropTableCommentOp.__init__rr)rrlrrfr:cCs||||d}||S)aIssue a "drop table comment" operation to remove an existing comment set on a table. :param table_name: string name of the target table. :param existing_comment: An optional string value of a comment already registered on the specified table. .. seealso:: :meth:`.Operations.create_table_comment` :paramref:`.Operations.alter_column.comment` rr)rTrrlrrfrr;r;r>r8sz%DropTableCommentOp.drop_table_commentrr)rrr:cCs ||jj||jjd}||S)aIssue a "drop table comment" operation to remove an existing comment set on a table using the current batch operations context. :param existing_comment: An optional string value of a comment already registered on the specified table. rr)rTrrrr;r;r>rSs z+DropTableCommentOp.batch_drop_table_commentrr9cCst|j|j|jdS)rr)rrlrrfr<r;r;r>rDjs zDropTableCommentOp.reverser[r-r\cCst|}|j|j|jdSr)rrrrlrfrr;r;r>rps zDropTableCommentOp.to_tablerEcCs d|fS)NZremove_table_commentrr<r;r;r>rFwsz DropTableCommentOp.to_diff_tuple)N) rGrHrIrJrmrbrrrDrrFr;r;r;r>r&s r alter_columnbatch_alter_columncseZdZdZddddddddddd dddddd dd d ddddd d fd dZddddZddddZddddZeddddddddddd dddd d dddddd dddd dddZ edddddddddddd ddd d dddddd ddddd d d!d"Z Z S)# AlterColumnOpz$Represent an alter column operation.NF) rf existing_typeexisting_server_defaultexisting_nullablermodify_nullablemodify_commentmodify_server_default modify_name modify_typerMriz Optional[Any]rrz$Optional[Union[str, Literal[False]]]rj)rl column_namerfrrrrrrrrrrr:c  sVtj||d||_||_||_||_||_||_| |_| |_ | |_ | |_ | |_ dSr) rrmrrrrrrrrrrr)r=rlrrfrrrrrrrrrrrr;r>rmszAlterColumnOp.__init__r9c Csg}|j|j|j}}}|jdk rN|d||||j|j|jd|j|jf|j dk r|d||||j|j|jd|j|j f|j dk r|d||||j|j|jd|j|j f|j dk r|d||||j|j|jd |j|j f|S) Nr)rrrr)rrrFZmodify_default)rrrr)rrr) rfrlrrappendrrrrrrr)r=Zcol_diffrftnamecnamer;r;r>rFsv    zAlterColumnOp.to_diff_tuplercCsP|jdk p&|jdk p&|jdk p&|jdk }|r0dS|jD]}|dr6dSq6dS)NFTZmodify_)rrrrr startswith)r=Zhc1rr;r;r> has_changess   zAlterColumnOp.has_changescCs|j}|j|d<|j|d<|j|d<|j|d<|jdk rF|j|d<|jdk rZ|j|d<|jdk rn|j|d<|j dk r|j |d <d d d d |DD}|D]<}d||kr|d|}|d||d|<||d|<q|j |j |j fd|j i|S)NrrrrrrFrrcSsh|]}|r|dqS)r)group)rmr;r;r> sz(AlterColumnOp.reverse..cSsg|]}td|qS)z^(?:existing_|modify_)(.+)$)rer)rkr;r;r>rsz)AlterColumnOp.reverse..z modify_%sz existing_%srf)rrrrrrrrrrrrlrrf)r=rall_keysrZswapr;r;r>rDs:                zAlterColumnOp.reverse) nullablerserver_defaultnew_column_namerOrrrrrfrz7Optional[Union[TypeEngine[Any], Type[TypeEngine[Any]]]]z.Optional[Union[str, bool, Identity, Computed]])rrlrrrrrrOrrrrrfrr:c  Ks2|||f| | | | | |||||d |}||S)agIssue an "alter column" instruction using the current migration context. Generally, only that aspect of the column which is being changed, i.e. name, type, nullability, default, needs to be specified. Multiple changes can also be specified at once and the backend should "do the right thing", emitting each change either separately or together as the backend allows. MySQL has special requirements here, since MySQL cannot ALTER a column without a full specification. When producing MySQL-compatible migration files, it is recommended that the ``existing_type``, ``existing_server_default``, and ``existing_nullable`` parameters be present, if not being altered. Type changes which are against the SQLAlchemy "schema" types :class:`~sqlalchemy.types.Boolean` and :class:`~sqlalchemy.types.Enum` may also add or drop constraints which accompany those types on backends that don't support them natively. The ``existing_type`` argument is used in this case to identify and remove a previous constraint that was bound to the type object. :param table_name: string name of the target table. :param column_name: string name of the target column, as it exists before the operation begins. :param nullable: Optional; specify ``True`` or ``False`` to alter the column's nullability. :param server_default: Optional; specify a string SQL expression, :func:`~sqlalchemy.sql.expression.text`, or :class:`~sqlalchemy.schema.DefaultClause` to indicate an alteration to the column's default value. Set to ``None`` to have the default removed. :param comment: optional string text of a new comment to add to the column. :param new_column_name: Optional; specify a string name here to indicate the new name within a column rename operation. :param type\_: Optional; a :class:`~sqlalchemy.types.TypeEngine` type object to specify a change to the column's type. For SQLAlchemy types that also indicate a constraint (i.e. :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`), the constraint is also generated. :param autoincrement: set the ``AUTO_INCREMENT`` flag of the column; currently understood by the MySQL dialect. :param existing_type: Optional; a :class:`~sqlalchemy.types.TypeEngine` type object to specify the previous type. This is required for all MySQL column alter operations that don't otherwise specify a new type, as well as for when nullability is being changed on a SQL Server column. It is also used if the type is a so-called SQLAlchemy "schema" type which may define a constraint (i.e. :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`), so that the constraint can be dropped. :param existing_server_default: Optional; The existing default value of the column. Required on MySQL if an existing default is not being changed; else MySQL removes the default. :param existing_nullable: Optional; the existing nullability of the column. Required on MySQL if the existing nullability is not being changed; else MySQL sets this to NULL. :param existing_autoincrement: Optional; the existing autoincrement of the column. Used for MySQL's system of altering a column that specifies ``AUTO_INCREMENT``. :param existing_comment: string text of the existing comment on the column to be maintained. Required on MySQL if the existing comment on the column is not being changed. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. :param postgresql_using: String argument which will indicate a SQL expression to render within the Postgresql-specific USING clause within ALTER COLUMN. This string is taken directly as raw SQL which must explicitly include any necessary quoting or escaping of tokens within the expression. ) rfrrrrrrrrrr)rTrrlrrrrrrOrrrrrfraltr;r;r>rs$j zAlterColumnOp.alter_column) rrrrrOrrrr insert_before insert_afterr)rrrrrrrOrrrrrrrr:c Ks>||jj|f|jj|| | | |||||| | d |}||S)a2Issue an "alter column" instruction using the current batch migration context. Parameters are the same as that of :meth:`.Operations.alter_column`, as well as the following option(s): :param insert_before: String name of an existing column which this column should be placed before, when creating the new table. :param insert_after: String name of an existing column which this column should be placed after, when creating the new table. If both :paramref:`.BatchOperations.alter_column.insert_before` and :paramref:`.BatchOperations.alter_column.insert_after` are omitted, the column is inserted after the last existing column in the table. .. seealso:: :meth:`.Operations.alter_column` ) rfrrrrrrrrrrrr)rTrrrrrrrOrrrrrrrrr;r;r>rs(-z AlterColumnOp.batch_alter_column) rGrHrIrJrmrFr rDrbrrrr;r;rr>r{sP0P 0{r add_columnbatch_add_columncseZdZdZdddddddd fd d Zd d ddZdd ddZdd ddZedddddZ edddddddZ eddddddddddZ edddd ddddd!d"d#Z Z S)$ AddColumnOpz"Represent an add column operation.NrrM Column[Any]rirrj)rlcolumnrfrr:c s tj||d||_||_dSr)rrmrr)r=rlrrfrrr;r>rmszAddColumnOp.__init__ DropColumnOpr9cCst|j|j|jSrA)rfrom_column_and_tablenamerfrlrr<r;r;r>rDs zAddColumnOp.reverse+Tuple[str, Optional[str], str, Column[Any]]cCsd|j|j|jfS)Nr)rfrlrr<r;r;r>rFszAddColumnOp.to_diff_tuplecCs|jSrA)rr<r;r;r> to_columnszAddColumnOp.to_column)colr:cCs||jj||jjdSr)rrzrf)rTr#r;r;r> from_columnszAddColumnOp.from_columnrfr r#r:cCs||||dSrr;rTrfr r#r;r;r>r sz%AddColumnOp.from_column_and_tablenamer)rrlrrfr:cCs||||d}||S)a Issue an "add column" instruction using the current migration context. e.g.:: from alembic import op from sqlalchemy import Column, String op.add_column("organization", Column("name", String())) The :meth:`.Operations.add_column` method typically corresponds to the SQL command "ALTER TABLE... ADD COLUMN". Within the scope of this command, the column's name, datatype, nullability, and optional server-generated defaults may be indicated. .. note:: With the exception of NOT NULL constraints or single-column FOREIGN KEY constraints, other kinds of constraints such as PRIMARY KEY, UNIQUE or CHECK constraints **cannot** be generated using this method; for these constraints, refer to operations such as :meth:`.Operations.create_primary_key` and :meth:`.Operations.create_check_constraint`. In particular, the following :class:`~sqlalchemy.schema.Column` parameters are **ignored**: * :paramref:`~sqlalchemy.schema.Column.primary_key` - SQL databases typically do not support an ALTER operation that can add individual columns one at a time to an existing primary key constraint, therefore it's less ambiguous to use the :meth:`.Operations.create_primary_key` method, which assumes no existing primary key constraint is present. * :paramref:`~sqlalchemy.schema.Column.unique` - use the :meth:`.Operations.create_unique_constraint` method * :paramref:`~sqlalchemy.schema.Column.index` - use the :meth:`.Operations.create_index` method The provided :class:`~sqlalchemy.schema.Column` object may include a :class:`~sqlalchemy.schema.ForeignKey` constraint directive, referencing a remote table name. For this specific type of constraint, Alembic will automatically emit a second ALTER statement in order to add the single-column FOREIGN KEY constraint separately:: from alembic import op from sqlalchemy import Column, INTEGER, ForeignKey op.add_column( "organization", Column("account_id", INTEGER, ForeignKey("accounts.id")), ) The column argument passed to :meth:`.Operations.add_column` is a :class:`~sqlalchemy.schema.Column` construct, used in the same way it's used in SQLAlchemy. In particular, values or functions to be indicated as producing the column's default value on the database side are specified using the ``server_default`` parameter, and not ``default`` which only specifies Python-side defaults:: from alembic import op from sqlalchemy import Column, TIMESTAMP, func # specify "DEFAULT NOW" along with the column add op.add_column( "account", Column("timestamp", TIMESTAMP, server_default=func.now()), ) :param table_name: String name of the parent table. :param column: a :class:`sqlalchemy.schema.Column` object representing the new column. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. rr)rTrrlrrfrr;r;r>rsWzAddColumnOp.add_column)rrr)rrrrr:cCsDi}|r||d<|r||d<||jj|fd|jji|}||S)zIssue an "add column" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.add_column` rrrfr)rTrrrrrrr;r;r>r`szAddColumnOp.batch_add_column)rGrHrIrJrmrDrFr"rbr$r rrrr;r;rr>rs" Yr drop_columnbatch_drop_columnc seZdZdZdddddddddd fd d Zd d ddZdd ddZedddddddZd$dddddZ edddddddddddZ ed dddd!d"d#Z Z S)%rz"Represent a drop column operation.NrerMrizOptional[AddColumnOp]rrj)rlrrfrgrr:c s&tj||d||_||_||_dSr)rrmrrrg)r=rlrrfrgrrr;r>rms zDropColumnOp.__init__r!r9cCsd|j|j|fS)NZ remove_column)rfrlr"r<r;r;r>rFs zDropColumnOp.to_diff_tuplercCs(|jdkrtdt|j|j|jjS)Nz;operation is not reversible; original column is not present)rgr~rr rfrlrr<r;r;r>rDs zDropColumnOp.reverserr%c Cs|||j|t|||dS)Nre)rzrr r&r;r;r>r s  z&DropColumnOp.from_column_and_tablenamer[r\cCs*|jdk r|jjSt|}||jtSrA)rgrrrrrrr;r;r>r"s  zDropColumnOp.to_columnrr)rrlrrfrr:cKs |||fd|i|}||S)ayIssue a "drop column" instruction using the current migration context. e.g.:: drop_column("organization", "account_id") :param table_name: name of table :param column_name: name of column :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. :param mssql_drop_check: Optional boolean. When ``True``, on Microsoft SQL Server only, first drop the CHECK constraint on the column using a SQL-script-compatible block that selects into a @variable from sys.check_constraints, then exec's a separate DROP CONSTRAINT for that constraint. :param mssql_drop_default: Optional boolean. When ``True``, on Microsoft SQL Server only, first drop the DEFAULT constraint on the column using a SQL-script-compatible block that selects into a @variable from sys.default_constraints, then exec's a separate DROP CONSTRAINT for that default. :param mssql_drop_foreign_key: Optional boolean. When ``True``, on Microsoft SQL Server only, first drop a single FOREIGN KEY constraint on the column using a SQL-script-compatible block that selects into a @variable from sys.foreign_keys/sys.foreign_key_columns, then exec's a separate DROP CONSTRAINT for that default. Only works if the column has exactly one FK constraint which refers to it, at the moment. rfr)rTrrlrrfrrr;r;r>r's/zDropColumnOp.drop_columnr)rrrr:cKs(||jj|fd|jji|}||S)zIssue a "drop column" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.drop_column` rfr)rTrrrrr;r;r>r(s zDropColumnOp.batch_drop_column)N) rGrHrIrJrmrFrDrbr r"r'r(rr;r;rr>rs   1r bulk_insertc@sJeZdZdZdddddddd d Zeddd ddddd d dZdS) BulkInsertOpz"Represent a bulk insert operation.T multiinsertzUnion[Table, TableClause]zList[Dict[str, Any]]rrj)rrowsr,r:cCs||_||_||_dSrA)rr-r,)r=rr-r,r;r;r>rm szBulkInsertOp.__init__r)rrr-r,r:cCs||||d}||dS)axIssue a "bulk insert" operation using the current migration context. This provides a means of representing an INSERT of multiple rows which works equally well in the context of executing on a live connection as well as that of generating a SQL script. In the case of a SQL script, the values are rendered inline into the statement. e.g.:: from alembic import op from datetime import date from sqlalchemy.sql import table, column from sqlalchemy import String, Integer, Date # Create an ad-hoc table to use for the insert statement. accounts_table = table( "account", column("id", Integer), column("name", String), column("create_date", Date), ) op.bulk_insert( accounts_table, [ { "id": 1, "name": "John Smith", "create_date": date(2010, 10, 5), }, { "id": 2, "name": "Ed Williams", "create_date": date(2007, 5, 27), }, { "id": 3, "name": "Wendy Jones", "create_date": date(2008, 8, 15), }, ], ) When using --sql mode, some datatypes may not render inline automatically, such as dates and other special types. When this issue is present, :meth:`.Operations.inline_literal` may be used:: op.bulk_insert( accounts_table, [ { "id": 1, "name": "John Smith", "create_date": op.inline_literal("2010-10-05"), }, { "id": 2, "name": "Ed Williams", "create_date": op.inline_literal("2007-05-27"), }, { "id": 3, "name": "Wendy Jones", "create_date": op.inline_literal("2008-08-15"), }, ], multiinsert=False, ) When using :meth:`.Operations.inline_literal` in conjunction with :meth:`.Operations.bulk_insert`, in order for the statement to work in "online" (e.g. non --sql) mode, the :paramref:`~.Operations.bulk_insert.multiinsert` flag should be set to ``False``, which will have the effect of individual INSERT statements being emitted to the database, each with a distinct VALUES clause, so that the "inline" values can still be rendered, rather than attempting to pass the values as bound parameters. :param table: a table object which represents the target of the INSERT. :param rows: a list of dictionaries indicating rows. :param multiinsert: when at its default of True and --sql mode is not enabled, the INSERT statement will be executed using "executemany()" style, where all elements in the list of dictionaries are passed as bound parameters in a single list. Setting this to False results in individual INSERT statements being emitted per parameter set, and is needed in those cases where non-literal values are present in the parameter sets. r+Nr)rTrrr-r,rr;r;r>r) sizBulkInsertOp.bulk_insertN)rGrHrIrJrmrbr)r;r;r;r>r* s  r*execute batch_executec@sreZdZdZdddddddd Zeddd dddd d d Zeddd dddd ddZddddZdS) ExecuteSQLOpz#Represent an execute SQL operation.Nexecution_optionszUnion[Executable, str]zOptional[dict[str, Any]]rj)rr2r:cCs||_||_dSrA)rr2)r=rr2r;r;r>rm szExecuteSQLOp.__init__r)rrr2r:cCs|||d}||S)a Execute the given SQL using the current migration context. The given SQL can be a plain string, e.g.:: op.execute("INSERT INTO table (foo) VALUES ('some value')") Or it can be any kind of Core SQL Expression construct, such as below where we use an update construct:: from sqlalchemy.sql import table, column from sqlalchemy import String from alembic import op account = table("account", column("name", String)) op.execute( account.update() .where(account.c.name == op.inline_literal("account 1")) .values({"name": op.inline_literal("account 2")}) ) Above, we made use of the SQLAlchemy :func:`sqlalchemy.sql.expression.table` and :func:`sqlalchemy.sql.expression.column` constructs to make a brief, ad-hoc table construct just for our UPDATE statement. A full :class:`~sqlalchemy.schema.Table` construct of course works perfectly fine as well, though note it's a recommended practice to at least ensure the definition of a table is self-contained within the migration script, rather than imported from a module that may break compatibility with older migrations. In a SQL script context, the statement is emitted directly to the output stream. There is *no* return result, however, as this function is oriented towards generating a change script that can run in "offline" mode. Additionally, parameterized statements are discouraged here, as they *will not work* in offline mode. Above, we use :meth:`.inline_literal` where parameters are to be used. For full interaction with a connected database where parameters can also be used normally, use the "bind" available from the context:: from alembic import op connection = op.get_bind() connection.execute( account.update() .where(account.c.name == "account 1") .values({"name": "account 2"}) ) Additionally, when passing the statement as a plain string, it is first coerced into a :func:`sqlalchemy.sql.expression.text` construct before being passed along. In the less likely case that the literal SQL string contains a colon, it must be escaped with a backslash, as:: op.execute(r"INSERT INTO table (foo) VALUES ('\:colon_value')") :param sqltext: Any legal SQLAlchemy expression, including: * a string * a :func:`sqlalchemy.sql.expression.text` construct. * a :func:`sqlalchemy.sql.expression.insert` construct. * a :func:`sqlalchemy.sql.expression.update` construct. * a :func:`sqlalchemy.sql.expression.delete` construct. * Any "executable" described in SQLAlchemy Core documentation, noting that no result set is returned. .. note:: when passing a plain string, the statement is coerced into a :func:`sqlalchemy.sql.expression.text` construct. This construct considers symbols with colons, e.g. ``:foo`` to be bound parameters. To avoid this, ensure that colon symbols are escaped, e.g. ``\:foo``. :param execution_options: Optional dictionary of execution options, will be passed to :meth:`sqlalchemy.engine.Connection.execution_options`. r1r)rTrrr2rr;r;r>r. sX zExecuteSQLOp.executecCs|j|||dS)zExecute the given SQL using the current migration context. .. seealso:: :meth:`.Operations.execute` r1)r.)rTrrr2r;r;r>r/ s zExecuteSQLOp.batch_executez"Tuple[str, Union[Executable, str]]r9cCs d|jfS)Nr.)rr<r;r;r>rF szExecuteSQLOp.to_diff_tuple) rGrHrIrJrmrbr.r/rFr;r;r;r>r0 s Zr0c@sReZdZdZddddddZdd d d Zd d d dZedddddZdS) OpContainerz-Represent a sequence of operations operation.r;Sequence[MigrateOperation]rj)opsr:cCst||_dSrA)rr5)r=r5r;r;r>rm szOpContainer.__init__rr9cCs|j SrAr5r<r;r;r>is_empty szOpContainer.is_emptyrcCstt|SrA)rr3 _ops_as_diffsr<r;r;r>as_diffs szOpContainer.as_diffszIterator[Tuple[Any, ...]]) migrationsr:ccs<|jD]0}t|dr,|td|EdHq|VqdS)Nr5r3)r5hasattrr8rrF)rTr:rr;r;r>r8 s  zOpContainer._ops_as_diffsN)r;) rGrHrIrJrmr7r9rbr8r;r;r;r>r3 s r3cs@eZdZdZdddddddfd d Zdd d d ZZS)ModifyTableOpszCContains a sequence of operations that all apply to a single Table.NrrMr4rirj)rlr5rfr:cst|||_||_dSrA)rrmrlrf)r=rlr5rfrr;r>rm s zModifyTableOps.__init__r9cCs&t|jttdd|jD|jdS)NcSsg|] }|qSr;rDrrr;r;r>r* sz*ModifyTableOps.reverse..)r5rf)r<rlrreversedr5rfr<r;r;r>rD' s zModifyTableOps.reverserGrHrIrJrmrDrr;r;rr>r< s r<csJeZdZdZdddddfdd Zd d d d d Zd dddZZS) UpgradeOpszcontains a sequence of operations that would apply to the 'upgrade' stream of a script. .. seealso:: :ref:`customizing_revision` r;upgradesr4rMrj)r5 upgrade_tokenr:cstj|d||_dSNr6)rrmrC)r=r5rCrr;r>rm9 szUpgradeOps.__init__ DowngradeOps downgrade_opsr:cCs&ttdd|jD|jdd<|S)NcSsg|] }|qSr;r=r>r;r;r>rC sz+UpgradeOps.reverse_into..)rr?r5)r=rGr;r;r> reverse_intoA szUpgradeOps.reverse_intor9cCs|tgdSrD)rHrEr<r;r;r>rDG szUpgradeOps.reverse)r;rB)rGrHrIrJrmrHrDrr;r;rr>rA/ s  rAcs:eZdZdZdddddfdd Zd d d d ZZS)rEzcontains a sequence of operations that would apply to the 'downgrade' stream of a script. .. seealso:: :ref:`customizing_revision` r; downgradesr4rMrj)r5downgrade_tokenr:cstj|d||_dSrD)rrmrJ)r=r5rJrr;r>rmU szDowngradeOps.__init__rAr9cCstttdd|jDdS)NcSsg|] }|qSr;r=r>r;r;r>r_ sz(DowngradeOps.reverse..r6)rArr?r5r<r;r;r>rD] szDowngradeOps.reverse)r;rIr@r;r;rr>rEK s  rEc @seZdZUdZded<ded<ded<dedddddd d d d d d d ddd ddd ddZeddddZej dddddZeddddZ e j dddddZ eddd d!Z eddd"d#Z dS)$MigrationScriptaprepresents a migration script. E.g. when autogenerate encounters this object, this corresponds to the production of an actual script file. A normal :class:`.MigrationScript` object would contain a single :class:`.UpgradeOps` and a single :class:`.DowngradeOps` directive. These are accessible via the ``.upgrade_ops`` and ``.downgrade_ops`` attributes. In the case of an autogenerate operation that runs multiple times, such as the multiple database example in the "multidb" template, the ``.upgrade_ops`` and ``.downgrade_ops`` attributes are disabled, and instead these objects should be accessed via the ``.upgrade_ops_list`` and ``.downgrade_ops_list`` list-based attributes. These latter attributes are always available at the very least as single-element lists. .. seealso:: :ref:`customizing_revision` rZ _needs_renderzList[UpgradeOps] _upgrade_opszList[DowngradeOps]_downgrade_opsN)messageimportsheadsplice branch_label version_path depends_onrirArEzSet[str]zOptional[_RevIdType]rj) rev_id upgrade_opsrGrNrOrPrQrRrSrTr:c Cs@||_||_||_||_||_||_| |_| |_||_||_ dSrA) rUrNrOrPrQrRrSrTrVrG) r=rUrVrGrNrOrPrQrRrSrTr;r;r>rm szMigrationScript.__init__zOptional[UpgradeOps]r9cCs0t|jdkrtdn|js"dS|jdSdS)zzAn instance of :class:`.UpgradeOps`. .. seealso:: :attr:`.MigrationScript.upgrade_ops_list` rzrThis MigrationScript instance has a multiple-entry list for UpgradeOps; please use the upgrade_ops_list attribute.Nr)lenrLr~r<r;r;r>rV szMigrationScript.upgrade_opsz#Union[UpgradeOps, List[UpgradeOps]])rVr:cCs*t||_|jD]}t|tstqdSrA)rto_listrL isinstancerAr)r=rVelemr;r;r>rV s  zOptional[DowngradeOps]cCs0t|jdkrtdn|js"dS|jdSdS)z~An instance of :class:`.DowngradeOps`. .. seealso:: :attr:`.MigrationScript.downgrade_ops_list` rzvThis MigrationScript instance has a multiple-entry list for DowngradeOps; please use the downgrade_ops_list attribute.Nr)rWrMr~r<r;r;r>rG szMigrationScript.downgrade_opsz'Union[DowngradeOps, List[DowngradeOps]]rFcCs*t||_|jD]}t|tstqdSrA)rrXrMrYrEr)r=rGrZr;r;r>rG s  cCs|jS)zA list of :class:`.UpgradeOps` instances. This is used in place of the :attr:`.MigrationScript.upgrade_ops` attribute when dealing with a revision operation that does multiple autogenerate passes. )rLr<r;r;r>upgrade_ops_list s z MigrationScript.upgrade_ops_listcCs|jS)zA list of :class:`.DowngradeOps` instances. This is used in place of the :attr:`.MigrationScript.downgrade_ops` attribute when dealing with a revision operation that does multiple autogenerate passes. )rMr<r;r;r>downgrade_ops_list s z"MigrationScript.downgrade_ops_list) rGrHrIrJrLsetrmrarVsetterrGr[r\r;r;r;r>rKc s0 & rK)] __future__rabcrrtypingrrrrrr r r r r rrrrrrZsqlalchemy.typesrrbaserrrrrZsqlalchemy.sqlrZsqlalchemy.sql.elementsrrr r!Zsqlalchemy.sql.functionsr"Zsqlalchemy.sql.schemar#r$r%r&r'r(r)r*r+r,r-r.Zsqlalchemy.sql.selectabler/Zsqlalchemy.sql.type_apir0Zautogenerate.rewriterr1Zruntime.migrationr2Zscript.revisionr3r4r6r8r7Zregister_operationr_rVrrrrrrrrrrrrrrrr*r0r3r<rArErKr;r;r;r>s                                                   & uw^  z"` $mQ ` % { ~