|L iV<ddlmZddlZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd l mZd dlmZd dlmZddlmZddlmZddlmZ e rlddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z"ddl 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/d.d&Z0 d/d'Z1 d0 d1d(Z2 d2d)Z3Gd*d+Z4Gd,d-Z5y)3) annotationsN)Any)Dict)Iterator)List)Optional)Sequence)Set) TYPE_CHECKING)Union)inspect)compare)render)util)ops) sqla_compat) Connection)Dialect) Inspector)MetaData) SchemaItem)Table)Config) DowngradeOps)MigrationScript) UpgradeOps)NameFilterParentNames)NameFilterType)ProcessRevisionDirectiveFn) RenderItemFnMigrationContext)Script)ScriptDirectory) _GetRevArgcjt||}|jJ|jjS)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)contextmetadatamigration_scripts ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/alembic/autogenerate/api.pycompare_metadatar0/s9r*'8<  ' ' 33 3  ' ' 0 0 22ct||}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)sW$%Wx@O**NN2&&&r*  &&8HI r1c|||||d}|$ddlm} ddlm} | j| }t ||} t || _tjtj|| 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 )sqlalchemy_module_prefixalembic_module_prefix render_itemrender_as_batchuser_module_prefixrr#r)DefaultDialect)dialect)opts) runtime.migrationr$sqlalchemy.engine.defaultr? configurer6setimportsr_indent_render_cmd_body) up_or_down_opr:r;r=rFr<migration_contextr>rAr$r?r8s r/render_python_coderKs~:%=!6"*0  D 8<6,66"$ %%6TBO!'lO >> ? r1ct|}tjg}tj||tj d||j }tj|||y)z6legacy, used by test_autogen_composition at the momentNr3) r6rrr_produce_net_changesrreverser _render_python_into_templatevars)r, template_argsr8r*r.s r/_render_migration_diffsrQsg %W-O..$K   +>**!))+  ++)=r1cXeZdZUdZdZded< dZded< dZded< dZd ed < dZ d ed < d dd Z e jddZ ejddZ ddZ ddZeZe jddZe jddZy)r6zSMaintains configuration and state that's specific to an autogenerate operation.N)Union[MetaData, Sequence[MetaData], None]r-zOptional[Connection] connectionzOptional[Dialect]r@zSet[str]rFr$rJc|r#|!|jrtjd| |j}||j ddn|x|_}|r<|:|8|j ,tjd|j jz|j dd}|j dd}g}g}|r|j||r|j|||_ ||_ ||_ |j6|jj|_ |jj|_t|_||_d|_y)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 CommandErrorrAgetr-scriptenv_py_locationappend_object_filters _name_filtersrJbindrTr@rErF _has_batch) selfrJr-rA autogeneraterWrXobject_filters name_filterss r/__init__zAutogenContext.__init__Ls_ !-!((##6  <$))D2:1ADHH& -x    !-!((4##K%++;;= "2D9xx5    ! !. 1     --)!2  ! ! -"4499DO1199DLu $( %r1cZ|j tdt|jS)NzHcan't return inspector as this AutogenContext has no database connection)rT TypeErrorr rcs r/ inspectorzAutogenContext.inspectors/ ?? "< t''r1c#0Kd|_dd|_yw)NTF)rbrjs r/ _within_batchzAutogenContext._within_batchs scd|vr3|dk(r|}n|jdd}|r|d}|r |d||d<n||d<|jD]}||||ryy) 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)r[r`)rcnametype_ parent_namesrqrofns r/run_name_filterszAutogenContext.run_name_filterss L (! )--lDA *=9 #"CL!>? CML!>?$$ BdE<0 r1cB|jD]}||||||ryy)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)r_)rcobject_rtru reflected compare_torws r/run_object_filtersz!AutogenContext.run_object_filterss1$&& BgtUIzB r1cg}tj|jD]}|j|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)rcresultms r/rzAutogenContext.sorted_tabless:dmm, +A MM!// * + r1c @i}tj|jD]y}t|j t|j }|r-t ddjdt|Dz|j|j {|S)aReturn an aggregate of the :attr:`.MetaData.tables` dictionaries. The :attr:`.MetaData.tables` collection is a dictionary of table key to :class:`.Table`; this method aggregates the dictionary across multiple :class:`.MetaData` objects into one dictionary. Duplicate table keys are **not** supported; if two :class:`.MetaData` objects contain the same table key, an exception is raised. z9Duplicate table keys across multiple MetaData objects: %sz, c3&K|] }d|z yw)z"%s"N).0keys r/ z4AutogenContext.table_key_to_table..s K## Ks) rrr-rE intersectiontables ValueErrorjoinsortedupdate)rcrr intersects r/table_key_to_tablez!AutogenContext.table_key_to_tables$&dmm, $AF 00QXX?I +yy K 9J KKM MM!(( # $ r1)NNT) rJr$r-rSrAzOptional[Dict[str, Any]]rdboolreturnNone)rr)rzIterator[None])rt Optional[str]rur rvrrr) rzrrtzsqla_compat._ConstraintNamerur r{rr|zOptional[SchemaItem]rr)rz List[Table])rzDict[str, Table])__name__ __module__ __qualname____doc__r-__annotations__rTr@rFrJrgrmemoized_propertyrk contextlibcontextmanagerrmrxr} run_filtersrrrr1r/r6r6sy;?H7>"(,J$+"&G %GX +/'.N ?C)-! 9&+9&<9&' 9&  9&  9&v ((  ###, #  #J*    )  0%K    r1r6ceZdZUdZded<ded< d ddZ ddZ dd Z dd Z dd Z dd Z dd Z y)RevisionContextz^Maintains configuration and state that's specific to a revision file generation operation.zList[MigrationScript]generated_revisions$Optional[ProcessRevisionDirectiveFn]process_revision_directivesNcz||_||_||_||_d|i|_|j g|_y)Nconfig)rscript_directory command_argsrrP_default_revisionr)rcrrrrs r/rgzRevisionContext.__init__sH 0(+F( f %)$:$:$<#= r1c |jj}t|ddrc|j}t |_|j r%|j j |j tj||||jJ|jj|j|jfd|j|j|j|j |j"d|S)N _needs_renderFT)refreshheadsplice branch_labels version_path depends_on)rPcopygetattr_last_autogen_contextrErFrrrOr4rgenerate_revisionmessagerr branch_labelrr)rcr.rPr8s r/ _to_scriptzRevisionContext._to_scripts)-(:(:(?(?(A #_e <"88O'*eO #''''../?/G/GH  3 3!1=  &&2226t$$66  # #  $ $  !&&#***77)66'22    r1c*|j||dy)NT_run_environmentrcrevrJs r/run_autogeneratez RevisionContext.run_autogenerate7s c#4d;r1c*|j||dy)NFrrs r/run_no_autogeneratez#RevisionContext.run_no_autogenerate<s c#4e>*>% > & > >& /  <<<2B< < ==2B= = 62 62,62 62  62p 6r1r)r,r$r-rrr)r,r$r-rrr)zsa.zop.FrNNN)rIzUnion[UpgradeOps, DowngradeOps]r:strr;rr=rrFz Sequence[str]r<zOptional[RenderItemFn]rJzOptional[MigrationContext]r>rrr)r,r$rPzDict[Any, Any]rr)6 __future__rrtypingrrrrrr r r r sqlalchemyr rrr operationsrrsqlalchemy.enginerrrsqlalchemy.sql.schemarrrrroperations.opsrrrruntime.environmentrr r!r"rBr$ script.baser%r&script.revisionr'r0r)rKrQr6rrr1r/rsF" ,)+.0+-0+;4@24$-,{3| )1B%*!&!*.48(,020!00 0  0 ( 020&0 0f .< *hhVK6K6r1