o
    8cxF                     @   s   d 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 Z
dd Z						dddZdd ZG dd deZG dd deZdS )zXProvide the 'autogenerate' feature which can produce migration operations
automatically.    N)inspect   )compare)render   )util)opsc                 C   s   t | |}|j S )a
  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.schema import SchemaItem
        from sqlalchemy.types import TypeEngine
        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(bind=None),
                Column('info', String(), table=<bat>), schema=None)),
          ( 'remove_table',
            Table(u'bar', MetaData(bind=None),
                Column(u'data', VARCHAR(), table=<bar>), schema=None)),
          ( 'add_column',
            None,
            'foo',
            Column('data', Integer(), table=<foo>)),
          ( 'remove_column',
            None,
            'foo',
            Column(u'old_data', VARCHAR(), table=None)),
          [ ( 'modify_nullable',
              None,
              'foo',
              u'x',
              { 'existing_server_default': None,
                'existing_type': INTEGER()},
              True,
              False)]]


    :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_script r   N/var/www/html/gps/gps/lib/python3.10/site-packages/alembic/autogenerate/api.pycompare_metadata   s   
[
r   c                 C   s8   t | |d}tjdtg tg d}t|| |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   MigrationScript
UpgradeOpsDowngradeOpsr   _populate_migration_script)r   r   autogen_contextr   r   r   r   r	   m   s   r	   sa.op.Fr   c                 C   sd   ||||d}|du rddl m} ddlm}	 |j|	 d}t||d}
t||
_t	t
| |
S )	zRender 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.

    )sqlalchemy_module_prefixalembic_module_prefixrender_itemrender_as_batchNr   )MigrationContextr   )DefaultDialect)dialect)opts)runtime.migrationr!   sqlalchemy.engine.defaultr"   	configurer   setimportsr   _indent_render_cmd_body)up_or_down_opr   r   r    r)   r   migration_contextr$   r!   r"   r   r   r   r   render_python_code   s    

r.   c                 C   sD   t | }tg }t|| tjd|| d}t||| dS )z6legacy, used by test_autogen_composition at the momentNr   )	r   r   r   r   _produce_net_changesr   reverser    _render_python_into_templatevars)r   template_argsr   r
   r   r   r   r   _render_migration_diffs   s   
r3   c                   @   s   e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 	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dS )r   zSMaintains configuration and state that's specific to an
    autogenerate operation.NTc           	      C   s   |r|d ur|j rtd|d u r|j}|d u r|dd n| | _}|r<|d u r<|d ur<|jd ur<td|jj |dd }|dd }g }g }|rS|| |rZ|| || _	|| _
|| _| jd urr| jj| _| jj| _t | _|| _d| _d S )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   CommandErrorr$   getr   scriptenv_py_locationappend_object_filters_name_filtersr-   bind
connectionr#   r(   r)   
_has_batch)	selfr-   r   r$   autogenerater5   r6   object_filtersname_filtersr   r   r   __init__   sV   





zAutogenContext.__init__c                 C   s
   t | jS N)r   r@   rB   r   r   r   	inspector3  s   
zAutogenContext.inspectorc                 c   s    d| _ d V  d| _ d S )NTF)rA   rH   r   r   r   _within_batch7  s   
zAutogenContext._within_batchc                 C   sn   d|v r&|dkr|}n| dd}|r&|d }|r"d||f |d< n||d< | jD ]}||||s4 dS q)dS )	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_nameNz%s.%sschema_qualified_table_nameFT)r9   r>   )rB   nametype_parent_namesrM   rK   fnr   r   r   run_name_filters=  s"   
zAutogenContext.run_name_filtersc                 C   s&   | j D ]}||||||s dS qdS )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=   )rB   object_rO   rP   	reflected
compare_torR   r   r   r   run_object_filters_  s
   
z!AutogenContext.run_object_filtersc                 C   s&   g }t | jD ]}||j q|S )aa  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)rB   resultmr   r   r   rZ   r  s   
zAutogenContext.sorted_tablesc                 C   s^   i }t | jD ]$}t|t|j}|r&tdddd t|D  |	|j q|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                 s   s    | ]}d | V  qdS )z"%s"Nr   ).0keyr   r   r   	<genexpr>  s    z4AutogenContext.table_key_to_table.<locals>.<genexpr>)
r   rX   r   r(   intersectiontables
ValueErrorjoinsortedupdate)rB   r[   r\   	intersectr   r   r   table_key_to_table  s   z!AutogenContext.table_key_to_table)NNT)__name__
__module____qualname____doc__r   r@   r#   r)   r-   rF   r   memoized_propertyrI   
contextlibcontextmanagerrJ   rS   rW   run_filtersrZ   rg   r   r   r   r   r      s2    
8

"
r   c                   @   sL   e Zd ZdZ	dddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dS )RevisionContextz^Maintains configuration and state that's specific to a revision
    file generation operation.Nc                 C   s2   || _ || _|| _|| _d|i| _|  g| _d S )Nconfig)rq   script_directorycommand_argsprocess_revision_directivesr2   _default_revisiongenerated_revisions)rB   rq   rr   rs   rt   r   r   r   rF     s   zRevisionContext.__init__c              	   C   s   i }| j  D ]
\}}||| qt|ddr0| j}t |_|jr)|j|j t	||| | 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)r2   items
setdefaultgetattr_last_autogen_contextr(   r)   re   r   r1   rr   generate_revisionr   messagery   rz   branch_labelr|   r}   )rB   r   r2   kvr   r   r   r   
_to_script  s0   	zRevisionContext._to_scriptc                 C      |  ||d d S )NT_run_environmentrB   revr-   r   r   r   run_autogenerate     z RevisionContext.run_autogeneratec                 C   r   )NFr   r   r   r   r   run_no_autogenerate  r   z#RevisionContext.run_no_autogeneratec           	      C   s"  |r!| j d rtdt| j|t| jdkr!td|jd }|jd }| jd }t|dd	sF||j	d _
||jd _d
|_n|jtjg |d |jtjg |d t||d | _}|rmt|| | jrx| ||| j |jd }|r|||| j | jD ]}d
|_qd S )Nsqlz7Using --sql with --autogenerate does not make any senseheadsz"Target database is not up to date.upgrade_tokendowngrade_tokenrw   FT)r   )r   )rC   rt   )rs   r   r8   r(   rr   get_revisionsr$   rv   r   upgrade_ops_listr   downgrade_ops_listr   rw   _upgrade_opsr<   r   r   _downgrade_opsr   r   r   r   r   rt   )	rB   r   r-   rC   r   r   r   r   hookr   r   r   r     sV   







z RevisionContext._run_environmentc                 C   s^   t j| jd p
t | jd t g t g | jd | jd | jd | jd | jd d	}|S )	Nr   r   ry   rz   r   r|   r}   )	r   r   r
   r   ry   rz   r   r|   r}   )r   r   rs   r   r   r   r   )rB   opr   r   r   ru     s   z!RevisionContext._default_revisionc                 c   s    | j D ]}| |V  qd S rG   )rv   r   )rB   generated_revisionr   r   r   generate_scripts  s   
z RevisionContext.generate_scriptsrG   )rh   ri   rj   rk   rF   r   r   r   r   ru   r   r   r   r   r   rp     s    
2rp   )r   r   Fr   NN)rk   rm   
sqlalchemyr    r   r   r   
operationsr   r   r	   r.   r3   objectr   rp   r   r   r   r   <module>   s(    _
& Y