
    +hV                    <   d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d d	lm
Z
 d d
lmZ d dlmZ d dlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ 	 erld dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ ddlmZ ddl m!Z! ddl m"Z" ddl m#Z# ddl$m%Z% ddl$m&Z& dd l$m'Z' dd!l$m(Z( dd"l)m*Z* dd#l+m,Z, dd$l+m-Z- dd%l.m/Z/ d.d&Z0	 	 	 	 	 	 d/d'Z1	 	 	 	 	 	 	 d0	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d1d(Z2	 	 	 	 	 	 d2d)Z3 G d* d+      Z4 G d, 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)RenderItemFnMigrationContext)Script)ScriptDirectory)
_GetRevArgc                j    t        | |      }|j                  J |j                  j                         S )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=<bat>),
                    schema=None,
                ),
            ),
            (
                "remove_table",
                Table(
                    "bar",
                    MetaData(),
                    Column("data", VARCHAR(), table=<bar>),
                    schema=None,
                ),
            ),
            (
                "add_column",
                None,
                "foo",
                Column("data", Integer(), table=<foo>),
            ),
            [
                (
                    "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=<foo>),
            ),
        ]

    :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_opsas_diffs)contextmetadatamigration_scripts      K/var/www/html/venv/lib/python3.12/site-packages/alembic/autogenerate/api.pycompare_metadatar0   /   s9    r *'8<''333''0022    c                    t        | |      }t        j                  dt        j                  g       t        j                  g             }t        j                  ||       |S )a  Produce 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-   Nrev_idr*   downgrade_ops)AutogenContextr   r   r   r   r   _populate_migration_script)r,   r-   autogen_contextr.   s       r/   r)   r)      sW    $ %Wx@O**NN2&&&r* &&8HIr1   c                    |||||d}|$ddl m}	 ddlm}
  |	j                   |
             }t        ||      }t        |      |_        t        j                  t        j                  | |            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_prefixalembic_module_prefixrender_itemrender_as_batchuser_module_prefixr   r#   r   )DefaultDialect)dialect)opts)runtime.migrationr$   sqlalchemy.engine.defaultr?   	configurer6   setimportsr   _indent_render_cmd_body)up_or_down_opr:   r;   r=   rF   r<   migration_contextr>   rA   r$   r?   r8   s               r/   render_python_coderK      s~    : %=!6"*0D  8<6,66"$
 %%6TBO!'lO>>? r1   c                    t        |       }t        j                  g       }t        j                  ||       t        j
                  d||j                               }t        j                  |||       y)z6legacy, used by test_autogen_composition at the momentNr3   )	r6   r   r   r   _produce_net_changesr   reverser    _render_python_into_templatevars)r,   template_argsr8   r*   r.   s        r/   _render_migration_diffsrQ      sg    
 %W-O..$K  +>**!))+ ++)=r1   c                  X   e Zd ZU dZdZded<   	 dZded<   	 dZded<   	 dZd	ed
<   	 dZ	ded<   	 	 	 	 d	 	 	 	 	 	 	 	 	 ddZ
ej                  dd       Zej                  dd       Z	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 	 	 ddZeZej                  dd       Zej                  dd       Zy)r6   zSMaintains configuration and state that's specific to an
    autogenerate operation.N)Union[MetaData, Sequence[MetaData], None]r-   zOptional[Connection]
connectionzOptional[Dialect]r@   zSet[str]rF   r$   rJ   c                   |r#|!|j                   rt        j                  d      ||j                  }||j	                  dd       n|x| _        }|r<|:|8|j                  ,t        j                  d|j                  j                  z        |j	                  dd       }|j	                  dd       }g }g }|r|j                  |       |r|j                  |       || _	        || _
        || _        | j                  6| j                  j                  | _        | j                  j                  | _        t               | _        || _        d| _        y )Nz^autogenerate can't use as_sql=True as it prevents querying the database for schema informationtarget_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   CommandErrorrA   getr-   scriptenv_py_locationappend_object_filters_name_filtersrJ   bindrT   r@   rE   rF   
_has_batch)	selfrJ   r-   rA   autogeneraterW   rX   object_filtersname_filterss	            r/   __init__zAutogenContext.__init__L  s_    !-!((##6 
 <$))D 2:1ADHH&-x	

  !-!((4##K %++;;=  "2D9xx5!!.1--)!2!!-"4499DO1199DLu$(	 %r1   c                Z    | j                   t        d      t        | j                         S )NzHcan't return inspector as this AutogenContext has no database connection)rT   	TypeErrorr   rc   s    r/   	inspectorzAutogenContext.inspector  s/    ??"<  t''r1   c              #  0   K   d| _         d  d| _         y w)NTF)rb   rj   s    r/   _within_batchzAutogenContext._within_batch  s     s   c                    d|v r3|dk(  r|}n|j                  dd      }|r|d   }|r|d||d<   n||d<   | j                  D ]  } ||||      r y y)	a  Run 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_nametable
table_nameN.schema_qualified_table_nameFT)r[   r`   )rc   nametype_parent_namesrq   ro   fns          r/   run_name_filterszAutogenContext.run_name_filters  s      L(!
)--lDA
*=9#"CL!>?
 CML!>?$$ 	BdE<0	 r1   c                B    | j                   D ]  } ||||||      r y y)a  Run 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_   )rc   object_rt   ru   	reflected
compare_torw   s          r/   run_object_filtersz!AutogenContext.run_object_filters  s1    $ && 	BgtUIzB	 r1   c                    g }t        j                  | j                        D ]  }|j                  |j                          |S )ai  Return 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.

        )r   to_listr-   extendsorted_tables)rc   resultms      r/   r   zAutogenContext.sorted_tables  s:     dmm, 	+AMM!//*	+r1   c           
     @   i }t        j                  | j                        D ]y  }t        |      j	                  t        |j
                              }|r-t        ddj                  d t        |      D              z        |j                  |j
                         { |S )a  Return 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, c              3  &   K   | ]	  }d |z    yw)z"%s"N ).0keys     r/   	<genexpr>z4AutogenContext.table_key_to_table.<locals>.<genexpr>  s      K## Ks   )
r   r   r-   rE   intersectiontables
ValueErrorjoinsortedupdate)rc   r   r   	intersects       r/   table_key_to_tablez!AutogenContext.table_key_to_table  s     $&dmm, 		$AF00QXX?I +yy K	9J KKM  MM!((#		$ r1   )NNT)
rJ   r$   r-   rS   rA   zOptional[Dict[str, Any]]rd   boolreturnNone)r   r   )r   zIterator[None])rt   Optional[str]ru   r    rv   r   r   r   )rz   r   rt   zsqla_compat._ConstraintNameru   r    r{   r   r|   zOptional[SchemaItem]r   r   )r   zList[Table])r   zDict[str, Table])__name__
__module____qualname____doc__r-   __annotations__rT   r@   rF   rJ   rg   r   memoized_propertyrk   
contextlibcontextmanagerrm   rx   r}   run_filtersr   r   r   r1   r/   r6   r6     sy    ;?H7>" (,J$+ "&G% GX +/'.N
 ?C)-!9&+9& <9& '	9&
 9& 
9&v 
( (    
## # ,	#
 
#J * 	
  ) 
0 %K	  
 r1   r6   c                      e Zd ZU dZded<   ded<   	 d	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 ddZ	 	 	 	 	 	 dd	Z	 	 	 	 	 	 dd
Z	 	 	 	 	 	 	 	 ddZ	ddZ
ddZy)RevisionContextz^Maintains configuration and state that's specific to a revision
    file generation operation.zList[MigrationScript]generated_revisions$Optional[ProcessRevisionDirectiveFn]process_revision_directivesNc                z    || _         || _        || _        || _        d|i| _        | j                         g| _        y )Nconfig)r   script_directorycommand_argsr   rP   _default_revisionr   )rc   r   r   r   r   s        r/   rg   zRevisionContext.__init__  sH      0(+F(f
 %)$:$:$<#= r1   c           
        | j                   j                         }t        |dd      rc| j                  }t	               |_        |j
                  r%|j
                  j                  |j
                         t        j                  |||       |j                  J  | j                  j                  |j                  |j                  fd|j                  |j                  |j                  |j                   |j"                  d|S )N_needs_renderFT)refreshheadsplicebranch_labelsversion_path
depends_on)rP   copygetattr_last_autogen_contextrE   rF   r   r   rO   r4   r   generate_revisionmessager   r   branch_labelr   r   )rc   r.   rP   r8   s       r/   
_to_scriptzRevisionContext._to_script  s     )-(:(:(?(?(A#_e<"88O '*eO#''''../?/G/GH33!1=  &&2226t$$66##$$

 !&&#***77)66'22

 

 
	
r1   c                *    | j                  ||d       y )NT_run_environmentrc   revrJ   s      r/   run_autogeneratez RevisionContext.run_autogenerate7  s     	c#4d;r1   c                *    | j                  ||d       y )NFr   r   s      r/   run_no_autogeneratez#RevisionContext.run_no_autogenerate<  s     	c#4e<r1   c                   |r| j                   d   rt        j                  d      t        | j                  j                  |            t        | j                  j                  d            k7  rt        j                  d      |j                  d   }|j                  d   }| j                  d   }t        |dd	      s0||j                  d   _
        ||j                  d   _        d
|_        n`|j                  j                  t!        j"                  g |             |j$                  j                  t!        j&                  g |             t)        ||      }|| _        |rt-        j.                  ||       | j0                  r| j1                  ||| j                         |j                  d   }|r |||| j                         | j                  D ]	  }d
|_         y )Nsqlz7Using --sql with --autogenerate does not make any senseheadsz"Target database is not up to date.upgrade_tokendowngrade_tokenr   FT)r   )r   )rd   r   )r   r   rZ   rE   r   get_revisionsrA   r   r   upgrade_ops_listr   downgrade_ops_listr   r   _upgrade_opsr^   r   r   _downgrade_opsr   r6   r   r   r7   r   )	rc   r   rJ   rd   r   r   r.   r8   hooks	            r/   r   z RevisionContext._run_environmentA  s      '''M  4((66s;<%%33G<A  ''(LMM)..?+001BC33B7'%@BO--b1? //3C .2*))00r? ++22  _E )L
 6E"..!1 ++,,!3(@(@ !%%&CD"C)A)AB $ 8 8 	2-1*	2r1   c                    | j                   }t        j                  |d   xs t        j                         |d   t        j
                  g       t        j                  g       |d   |d   |d   |d   |d   	      }|S )	Nr4   r   r   r   r   r   r   )	r4   r   r*   r5   r   r   r   r   r   )r   r   r   r   r4   r   r   )rc   r   ops      r/   r   z!RevisionContext._default_revisiony  s    '+'8'8  ):T[[] +r***2.f%)%n5%n5#L1

 	r1   c              #  T   K   | j                   D ]  }| j                  |        y wN)r   r   )rc   generated_revisions     r/   generate_scriptsz RevisionContext.generate_scripts  s,     "&":": 	6//"455	6s   &(r   )
r   r   r   r&   r   zDict[str, Any]r   r   r   r   )r.   r   r   zOptional[Script])r   r'   rJ   r$   r   r   )r   r'   rJ   r$   rd   r   r   r   )r   r   )r   zIterator[Optional[Script]])r   r   r   r   r   rg   r   r   r   r   r   r   r   r1   r/   r   r     s    " /.!EE >> *> %	>
&
> 
>&
 /
	
<<<2B<	<
==2B=	=
6262 ,62 	62
 
62p6r1   r   )r,   r$   r-   r   r   r   )r,   r$   r-   r   r   r   )zsa.zop.Fr   NNN)rI   zUnion[UpgradeOps, DowngradeOps]r:   strr;   r   r=   r   rF   zSequence[str]r<   zOptional[RenderItemFn]rJ   zOptional[MigrationContext]r>   r   r   r   )r,   r$   rP   zDict[Any, Any]r   r   )6
__future__r   r   typingr   r   r   r   r   r	   r
   r   r   
sqlalchemyr    r   r   r   
operationsr   r   sqlalchemy.enginer   r   r   sqlalchemy.sql.schemar   r   r   r   r   operations.opsr   r   r   runtime.environmentr   r    r!   r"   rB   r$   script.baser%   r&   script.revisionr'   r0   r)   rK   rQ   r6   r   r   r1   r/   <module>r      sF   "                  ,)+.0+-0+;4@24$-,{3|)1B %*!&!*.48(,020!0 0 	0
 0 (0 20 &0 	0f.<	*h hVK6 K6r1   