bgTddlmZddlZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd l mZd dlmZd dlmZddlmZddlmZ e rZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddl"m#Z#ddl"m$Z$ddl"m%Z%ddl&m'Z'dd l(m)Z)dd!l(m*Z*dGd(Z+dHd*Z, dIdJd>Z-dKdBZ.GdCdDZ/GdEdFZ0dS)L) annotationsN)Any)Callable)Dict)Iterator)Optional)Sequence)Set) TYPE_CHECKING)Union)inspect)compare)render)util)ops) Connection)Dialect) Inspector)MetaData) SchemaItem)Config) DowngradeOps)MigrationScript) UpgradeOps)NameFilterParentNames)NameFilterType) RenderItemFnMigrationContext)Script)ScriptDirectorycontextr!metadatarreturnrcTt||}|jS)aB Compare a database schema to that given in a :class:`~sqlalchemy.schema.MetaData` instance. The database connection is presented in the context of a :class:`.MigrationContext` object, which provides database connectivity as well as optional comparison functions to use for datatypes and server defaults - see the "autogenerate" arguments at :meth:`.EnvironmentContext.configure` for details on these. The return format is a list of "diff" directives, each representing individual differences:: from alembic.migration import MigrationContext from alembic.autogenerate import compare_metadata from sqlalchemy import ( create_engine, MetaData, Column, Integer, String, Table, text, ) import pprint engine = create_engine("sqlite://") with engine.begin() as conn: conn.execute( text( ''' create table foo ( id integer not null primary key, old_data varchar, x integer ) ''' ) ) conn.execute(text("create table bar (data varchar)")) metadata = MetaData() Table( "foo", metadata, Column("id", Integer, primary_key=True), Column("data", Integer), Column("x", Integer, nullable=False), ) Table("bat", metadata, Column("info", String)) mc = MigrationContext.configure(engine.connect()) diff = compare_metadata(mc, metadata) pprint.pprint(diff, indent=2, width=20) Output:: [ ( "add_table", Table( "bat", MetaData(), Column("info", String(), table=), schema=None, ), ), ( "remove_table", Table( "bar", MetaData(), Column("data", VARCHAR(), table=), schema=None, ), ), ( "add_column", None, "foo", Column("data", Integer(), table=), ), [ ( "modify_nullable", None, "foo", "x", { "existing_comment": None, "existing_server_default": False, "existing_type": INTEGER(), }, True, False, ) ], ( "remove_column", None, "foo", Column("old_data", VARCHAR(), table=), ), ] :param context: a :class:`.MigrationContext` instance. :param metadata: a :class:`~sqlalchemy.schema.MetaData` instance. .. seealso:: :func:`.produce_migrations` - produces a :class:`.MigrationScript` structure based on metadata comparison. )produce_migrations upgrade_opsas_diffs)r$r%migration_scripts O/opt/cloudlinux/venv/lib64/python3.11/site-packages/alembic/autogenerate/api.pycompare_metadatar-+s*r*'8<<  ' 0 0 2 22rct||}tjdtjgtjg}t j|||S)aProduce a :class:`.MigrationScript` structure based on schema comparison. This function does essentially what :func:`.compare_metadata` does, but then runs the resulting list of diffs to produce the full :class:`.MigrationScript` object. For an example of what this looks like, see the example in :ref:`customizing_revision`. .. seealso:: :func:`.compare_metadata` - returns more fundamental "diff" data from comparing a schema. )r%Nrev_idr) downgrade_ops)AutogenContextrrrrr_populate_migration_script)r$r%autogen_contextr+s r,r(r(sh$%Wx@@@O*N2&&&r**  &8HIII r.sa.op.F up_or_down_opUnion[UpgradeOps, DowngradeOps]sqlalchemy_module_prefixstralembic_module_prefixrender_as_batchboolimports Sequence[str] render_itemOptional[RenderItemFn]migration_contextOptional[MigrationContext]user_module_prefix Optional[str]c|||||d}|%ddlm} ddlm} | j| }t ||} t || _tj tj || S) a*Render Python code given an :class:`.UpgradeOps` or :class:`.DowngradeOps` object. This is a convenience function that can be used to test the autogenerate output of a user-defined :class:`.MigrationScript` structure. :param up_or_down_op: :class:`.UpgradeOps` or :class:`.DowngradeOps` object :param sqlalchemy_module_prefix: module prefix for SQLAlchemy objects :param alembic_module_prefix: module prefix for Alembic constructs :param render_as_batch: use "batch operations" style for rendering :param imports: sequence of import symbols to add :param render_item: callable to render items :param migration_context: optional :class:`.MigrationContext` :param user_module_prefix: optional string prefix for user-defined types .. versionadded:: 1.11.0 )r;r=rBr>rFNrr r)DefaultDialect)dialect)opts) runtime.migrationr!sqlalchemy.engine.defaultrI configurer3setr@r_indent_render_cmd_body) r9r;r=r>r@rBrDrFrKr!rIr5s r,render_python_coderRs:%=!6"*0   D 888888<<<<<<6,6"N$$   %%6TBBBO!'llO > ??  r. template_argsDict[Any, Any]Nonect|}tjg}tj||tjd||}tj|||dS)z6legacy, used by test_autogen_composition at the momentNr0) r3rrr_produce_net_changesrreverser _render_python_into_templatevars)r$rSr5r)r+s r,_render_migration_diffsrZs %W--O.$$K  +>>>*!))++  +)=r.c eZdZUdZdZded< dZded< dZded< dZd ed < dZ d ed < d(d)dZ e j d*dZ ejd+dZd,dZd-d%ZeZe j d&Ze j d'ZdS).r3zSMaintains configuration and state that's specific to an autogenerate operation.NOptional[MetaData]r%zOptional[Connection] connectionzOptional[Dialect]rJzSet[str]r@r!rDTrKOptional[dict] autogenerater?r&rUcn|r||jrtjd||j}||ddn|x|_}|r,|*|(|j!tjd|jjz|dd}|dd}g}g}|r|||r||||_ ||_ ||_ |j "|j j |_ |j j|_t|_||_d|_dS)Nz^autogenerate can't use as_sql=True as it prevents querying the database for schema informationtarget_metadatazCan't proceed with --autogenerate option; environment script %s does not provide a MetaData object or sequence of objects to the context.include_object include_nameF)as_sqlr CommandErrorrKgetr%scriptenv_py_locationappend_object_filters _name_filtersrDbindr]rJrOr@ _has_batch) selfrDr%rKr_rbrcobject_filters name_filterss r,__init__zAutogenContext.__init__Gs~  !-!(.#6  <$)D2:1ADHH& - - -x     !-!(4#K%+;= "2D99xx55   2  ! !. 1 1 1  .    - - --)!2  ! -"49DO19DLuu $( %r.rcV|jtdt|jS)NzHcan't return inspector as this AutogenContext has no database connection)r] TypeErrorr rns r, inspectorzAutogenContext.inspectors3 ? "< t'''r.Iterator[None]c#.Kd|_dVd|_dS)NTF)rmrts r, _within_batchzAutogenContext._within_batchs! r.namerGtype_r parent_namesrcd|vr;|dkr|}n|dd}|r|d}|r |d||d<n||d<|jD]}||||sdSdS) aRun the context's name filters and return True if the targets should be part of the autogenerate operation. This method should be run for every kind of name encountered within the reflection side of an autogenerate operation, giving the environment the chance to filter what names should be reflected as database objects. The filters here are produced directly via the :paramref:`.EnvironmentContext.configure.include_name` parameter. schema_nametable table_nameN.schema_qualified_table_nameFT)rfrk)rnryrzr{rr}fns r,run_name_filterszAutogenContext.run_name_filterss L ( (! )--lDAA  M*=9 M# " CL!>?? CML!>?$  B2dE<00 uu 4r.object_r reflected compare_toOptional[SchemaItem]c>|jD]}||||||sdSdS)aRun the context's object filters and return True if the targets should be part of the autogenerate operation. This method should be run for every kind of object encountered within an autogenerate operation, giving the environment the chance to filter what objects should be included in the comparison. The filters here are produced directly via the :paramref:`.EnvironmentContext.configure.include_object` parameter. FT)rj)rnrryrzrrrs r,run_object_filtersz!AutogenContext.run_object_filterssC$&  B2gtUIzBB uu 4r.cvg}tj|jD]}||j|S)aiReturn an aggregate of the :attr:`.MetaData.sorted_tables` collection(s). For a sequence of :class:`.MetaData` objects, this concatenates the :attr:`.MetaData.sorted_tables` collection for each individual :class:`.MetaData` in the order of the sequence. It does **not** collate the sorted tables collections. )rto_listr%extend sorted_tables)rnresultms r,rzAutogenContext.sorted_tabless@dm,, + +A MM!/ * * * * r.c Zi}tj|jD]}t|t|j}|rz4AutogenContext.table_key_to_table..s& K K## K K K K K Kr.) rrr%rO intersectiontables ValueErrorjoinsortedupdate)rnrr intersects r,table_key_to_tablez!AutogenContext.table_key_to_tablesdm,, $ $AF 00QX??I  +yy K K 9J9J K K KKKM MM!( # # # # r.)NNT) rDr!r%r\rKr^r_r?r&rU)r&r)r&rv)ryrGrzrr{rr&r?) rrryrGrzrrr?rrr&r?)__name__ __module__ __qualname____doc__r%__annotations__r]rJr@rDrqrmemoized_propertyru contextlibcontextmanagerrxrr run_filtersrrr8r.r,r3r3sp$(H''''"(,J++++"&G%%%%G +/....N (,#! :&:&:&:&:&x ((((    $$$$L0%K     r.r3cNeZdZdZ ddd Zd dZd!dZd!dZd"dZd#dZ d$dZ dS)%RevisionContextz^Maintains configuration and state that's specific to a revision file generation operation.Nconfigrscript_directoryr# command_argsDict[str, Any]process_revision_directivesOptional[Callable]r&rUc||_||_||_||_d|i|_|g|_dS)Nr)rrrrrS_default_revisiongenerated_revisions)rnrrrrs r,rqzRevisionContext.__init__sQ 0(+F( f %)$:$:$<$<#=   r.r+rOptional[Script]c |j}t|ddrV|j}t |_|jr|j|jtj||||j J|j j |j |j fd|j |j|j|j|jd|S)N _needs_renderFT)refreshheadsplice branch_labels version_path depends_on)rScopygetattr_last_autogen_contextrOr@rrrYr1rgenerate_revisionmessagerr branch_labelrr)rnr+rSr5s r, _to_scriptzRevisionContext._to_scripts)-(:(?(?(A(A #_e < < "8O'*eeO #' I'../?/GHHH  3!1=    &2226t$6  #  $  !&#**7)6'2      r.revtuplerDr!c4|||ddS)NT_run_environmentrnrrDs r,run_autogeneratez RevisionContext.run_autogenerate/s# c#4d;;;;;r.c4|||ddS)NFrrs r,run_no_autogeneratez#RevisionContext.run_no_autogenerate4s# c#4e<<<<>>>>"    <<<<< ==== 62626262p    666666r.r)r$r!r%rr&r)r$r!r%rr&r)r6r7Fr8NNN)r9r:r;r<r=r<r>r?r@rArBrCrDrErFrGr&r<)r$r!rSrTr&rU)1 __future__rrtypingrrrrrr r r r sqlalchemyr rrr operationsrsqlalchemy.enginerrrsqlalchemy.sql.schemarrrroperations.opsrrrruntime.environmentrrrrLr! script.baser"r#r-r(rRrZr3rr8r.r,rs"""""" .,,,,,,))))))++++++......000000------000000++++++;;;;;;444444222222444444$$$$$$------z3z3z3z3zB%*!&!*.48(,00000f*jjjjjjjjZF6F6F6F6F6F6F6F6F6F6r.