
    ɯei              
       Z   d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	m
Z
mZ d dlZd dlmc mc mc mc mZ d dlmZ d dlmZ d dlmZmZmZmZmZmZ d dlm Z  d dl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( d d	l)m*Z* d d
l+m,Z,m-Z- d dl.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6m7Z7 d dl8m9Z9 d dl:m;Z; e jx                  dk  rd dlm=Z= nd dl>m=Z=  ee?      Z@ G d de      ZA G d de      ZB G d de      ZC G d d      ZD G d d      ZEdee9   deAfdZFdee9   deBfd ZGdee9   d!eHd"eHd#eHdeCf
d$ZI G d% d&e6      ZJy)'    N)	getLogger)DictListLiteral
NamedTupleOptionalUnionoverload)create_join_type)SnowflakeTable)DeleteMergeExpressionInsertMergeExpressionTableDelete
TableMergeTableUpdateUpdateMergeExpression)Sample)build_expr_from_python_valbuild_expr_from_dict_str_strbuild_expr_from_snowpark_column-build_expr_from_snowpark_column_or_python_valwith_src_positionDATAFRAME_AST_PARAMETERbuild_table_name)SnowparkClientExceptionMessages)add_api_callset_api_call_source)ColumnOrLiteral)	publicapiTimeTravelConfig)Column)	DataFrame_disambiguate)Row)TimestampTimeZone)   	   )Iterablec                   0    e Zd ZU dZeed<   dZee   ed<   y)UpdateResultz,Result of updating rows in a :class:`Table`.rows_updatedNmulti_joined_rows_updated)__name__
__module____qualname____doc__int__annotations__r,   r        Z/var/www/html/glpi_dashboard/venv/lib/python3.12/site-packages/snowflake/snowpark/table.pyr*   r*   8   s$    6 	 x  r4   r*   c                       e Zd ZU dZeed<   y)DeleteResultz,Result of deleting rows in a :class:`Table`.rows_deletedNr-   r.   r/   r0   r1   r2   r3   r4   r5   r7   r7   A   s    6r4   r7   c                   0    e Zd ZU dZeed<   eed<   eed<   y)MergeResultz=Result of merging a :class:`DataFrame` into a :class:`Table`.rows_insertedr+   r8   Nr9   r3   r4   r5   r;   r;   G   s    Gr4   r;   c                   N    e Zd ZdZ	 d
dee   deddfdZdee	e
f   dd fdZd	 Zy)WhenMatchedClausea  
    A matched clause for the :meth:`Table.merge` action. It matches all
    remaining rows in the target :class:`Table` that satisfy ``join_expr``
    while also satisfying ``condition``, if it is provided. You can use
    :func:`functions.when_matched` to instantiate this class.

    Args:
        condition: An optional :class:`Column` object representing the
            specified condition. For example, ``col("a") == 1``.
    N	condition	_emit_astreturnc                 J    ||j                   nd | _        || _        d | _        y N_expression_condition_expr
_condition_clauseselfr?   r@   s      r5   __init__zWhenMatchedClause.__init__[   )     9B8My44SW#r4   assignmentsc                     | j                   r7t        j                  t        | j                   t              rdd      dd      t	        | j
                  |      | _         | S )a  
        Defines an update action for the matched clause and
        returns an updated :class:`WhenMatchedClause` with the new
        update action added.

        Args:
            assignments: A list of values or a ``dict`` that associates
                the names of columns with the values that should be updated.
                The value of ``assignments`` can either be a literal value or
                a :class:`Column` object.

        Example::

            >>> # Adds a matched clause where a row in source is matched
            >>> # if its key is equal to the key of any row in target.
            >>> # For all such rows, update its value to the value of the
            >>> # corresponding row in source.
            >>> from snowflake.snowpark.functions import when_matched, lit
            >>> target_df = session.create_dataframe([(10, "old"), (10, "too_old"), (11, "old")], schema=["key", "value"])
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> target = session.table("my_table")
            >>> source = session.create_dataframe([(10, "new")], schema=["key", "value"])
            >>> target.merge(source, (target["key"] == source["key"]) & (target["value"] == lit("too_old")), [when_matched().update({"value": source["value"]})])
            MergeResult(rows_inserted=0, rows_updated=1, rows_deleted=0)
            >>> target.sort("key", "value").collect() # the value in the table is updated
            [Row(KEY=10, VALUE='new'), Row(KEY=10, VALUE='old'), Row(KEY=11, VALUE='old')]

        Note:
            An exception will be raised if this method or :meth:`WhenMatchedClause.delete`
            is called more than once on the same :class:`WhenMatchedClause` object.
        updatedeleter>   )rH   r   $MERGE_TABLE_ACTION_ALREADY_SPECIFIED
isinstancer   rF   )rJ   rM   s     r5   rO   zWhenMatchedClause.updateb   se    @ <<1VVdll,AB  $	  #	  -T-A-A;Or4   c                     | j                   r7t        j                  t        | j                   t              rdd      dd      t        | j                        | _         | S )a  
        Defines a delete action for the matched clause and
        returns an updated :class:`WhenMatchedClause` with the new
        delete action added.

        Example::

            >>> # Adds a matched clause where a row in source is matched
            >>> # if its key is equal to the key of any row in target.
            >>> # For all such rows, delete them.
            >>> from snowflake.snowpark.functions import when_matched
            >>> target_df = session.create_dataframe([(10, "old"), (10, "too_old"), (11, "old")], schema=["key", "value"])
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> target = session.table("my_table")
            >>> source = session.create_dataframe([(10, "new")], schema=["key", "value"])
            >>> target.merge(source, target["key"] == source["key"], [when_matched().delete()])
            MergeResult(rows_inserted=0, rows_updated=0, rows_deleted=2)
            >>> target.collect() # the rows are deleted
            [Row(KEY=11, VALUE='old')]

        Note:
            An exception will be raised if this method or :meth:`WhenMatchedClause.update`
            is called more than once on the same :class:`WhenMatchedClause` object.
        rO   rP   r>   )rH   r   rQ   rR   r   r   rF   rJ   s    r5   rP   zWhenMatchedClause.delete   sb    2 <<1VVdll,AB  $	  #	  -T-A-ABr4   NT)r-   r.   r/   r0   r   r!   boolrK   r   strr   rO   rP   r3   r4   r5   r>   r>   O   sT    	 EI!&)=A	($sO';"< (AT (T!r4   r>   c                   X    e Zd ZdZ	 d	dee   deddfdZdee	e
   eee
f   f   dd fdZy)
WhenNotMatchedClausea  
    A not-matched clause for the :meth:`Table.merge` action. It matches all
    remaining rows in the target :class:`Table` that do not satisfy ``join_expr``
    but satisfy ``condition``, if it is provided. You can use
    :func:`functions.when_not_matched` to instantiate this class.

    Args:
        condition: An optional :class:`Column` object representing the
            specified condition.
    Nr?   r@   rA   c                 J    ||j                   nd | _        || _        d | _        y rC   rD   rI   s      r5   rK   zWhenNotMatchedClause.__init__   rL   r4   rM   c                 "   | j                   rt        j                  dd      t        |t              r3t        |j                               }t        |j                               }ng }t        |      }t        | j                  ||      | _         | S )a5
  
        Defines an insert action for the not-matched clause and
        returns an updated :class:`WhenNotMatchedClause` with the new
        insert action added.

        Args:
            assignments: A list of values or a ``dict`` that associates
                the names of columns with the values that should be inserted.
                The value of ``assignments`` can either be a literal value or
                a :class:`Column` object.

        Examples::

            >>> # Adds a not-matched clause where a row in source is not matched
            >>> # if its key does not equal the key of any row in target.
            >>> # For all such rows, insert a row into target whose ley and value
            >>> # are assigned to the key and value of the not matched row.
            >>> from snowflake.snowpark.functions import when_not_matched
            >>> from snowflake.snowpark.types import IntegerType, StringType, StructField, StructType
            >>> schema = StructType([StructField("key", IntegerType()), StructField("value", StringType())])
            >>> target_df = session.create_dataframe([(10, "old"), (10, "too_old"), (11, "old")], schema=schema)
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> target = session.table("my_table")

            >>> source = session.create_dataframe([(12, "new")], schema=schema)
            >>> target.merge(source, target["key"] == source["key"], [when_not_matched().insert([source["key"], source["value"]])])
            MergeResult(rows_inserted=1, rows_updated=0, rows_deleted=0)
            >>> target.sort("key", "value").collect() # the rows are inserted
            [Row(KEY=10, VALUE='old'), Row(KEY=10, VALUE='too_old'), Row(KEY=11, VALUE='old'), Row(KEY=12, VALUE='new')]

            >>> # For all such rows, insert a row into target whose key is
            >>> # assigned to the key of the not matched row.
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> target.merge(source, target["key"] == source["key"], [when_not_matched().insert({"key": source["key"]})])
            MergeResult(rows_inserted=1, rows_updated=0, rows_deleted=0)
            >>> target.sort("key", "value").collect() # the rows are inserted
            [Row(KEY=10, VALUE='old'), Row(KEY=10, VALUE='too_old'), Row(KEY=11, VALUE='old'), Row(KEY=12, VALUE=None)]

        Note:
            An exception will be raised if this method is called more than once
            on the same :class:`WhenNotMatchedClause` object.
        insertrY   )
rH   r   rQ   rR   dictlistkeysvaluesr   rF   )rJ   rM   r_   r`   s       r5   r\   zWhenNotMatchedClause.insert   s    Z <<1VV0  k4(((*+D+,,./FD+&F,T-A-A4Pr4   rU   )r-   r.   r/   r0   r   r!   rV   rK   r	   r(   r   r   rW   r\   r3   r4   r5   rY   rY      s^    	 EI!&)=A	8 /!:DoAU<V!VW8	8r4   rY   rowsrA   c                     t        | d         dk(  r*t        t        | d   d         t        | d   d               S t        t        | d   d               S )Nr         )lenr*   r1   ra   s    r5   _get_update_resultrg      sN    
47|qCQ
OSa_==DGAJ((r4   c                 6    t        t        | d   d               S )Nr   )r7   r1   rf   s    r5   _get_delete_resultri     s    DGAJ((r4   insertedupdateddeletedc                     d}d\  }}}|rt        | d   |         }|dz  }|rt        | d   |         }|dz  }|rt        | d   |         }t        |||      S )Nr   )r   r   r   rd   )r1   r;   )ra   rj   rk   rl   idxr<   r+   r8   s           r5   _get_merge_resultro     su     C07-M<DGCL)q473<(q473<(}lLAAr4   c                       e Zd ZdZe	 	 	 	 d3ddddddddeded   d	ed
eej                     dedee
d      dee   dee   deeeej                  f      deeeef      dee   ddf fd       Zd Zd4dZd Zd Ze	 	 d5dddddee   dee   dee   dee   deddfd       Zee	 	 d5dddd d!eeef   d"ee   d#ee   d$eeeef      d%ededefd&              Zee	 	 d5dddd d!eeef   d"ee   d#ee   d$eeeef      d%ededd'fd(              Ze	 	 d5dddd d!eeef   d"ee   d#ee   d$eeeef      d%ededeed'f   fd)       Zee	 	 d5dddd d"ee   d#ee   d$eeeef      d%ededefd*              Zee	 	 d5dddd d"ee   d#ee   d$eeeef      d%ededd'fd+              Ze	 	 d5dddd d"ee   d#ee   d$eeeef      d%ededeed'f   fd,       Zeedddd d#ed-ed.eee e!f      d$eeeef      d%edede"fd/              Z#eedddd d#ed-ed.eee e!f      d$eeeef      d%ededd'fd0              Z#edddd d#ed-ed.eee e!f      d$eeeef      d%ededee"d'f   fd1       Z#ed6deddfd2       Z$ xZ%S )7Tablea,  
    Represents a lazily-evaluated Table. It extends :class:`DataFrame` so all
    :class:`DataFrame` operations can be applied to it.

    You can create a :class:`Table` object by calling :meth:`Session.table`
    with the name of the table in Snowflake. See examples in :meth:`Session.table`.
    NFTtime_travel_mode	statementoffset	timestamptimestamp_typestream
table_namesessionz"snowflake.snowpark.session.Sessionis_temp_table_for_cleanup	_ast_stmtr@   rs   )atbeforert   ru   rv   rw   rx   rA   c                v   |||r|j                   j                         }t        |j                  j                  |      }t        |j                  |       d|j                  _        ||_	        |||j                  _        |||j                  _        |||j                  _        |	t        |j                  |	       |
t!        |
      |j"                  _        |||j$                  _        t'        j(                  ||||	|
|      }t+        ||||      }|j,                  rM|j.                  j1                  |j.                  j3                  ||j.                        |j.                        }n|}t4        | m  ||||       | j8                  | _        || _        || _        || _        tA        | d       y )NTrr   )rz   r{   time_travel_configanalyzerfrom_r   )r|   r@   zTable.__init__)!
_ast_batchbindr   exprtabler   namevariant
table_initr{   rs   valuert   ru   r   rv   rW   rw   rx   r    validate_and_normalize_paramsr   sql_simplifier_enabled	_analyzercreate_select_statementcreate_selectable_entitysuperrK   	is_cachedry   _is_temp_table_for_cleanup_time_travel_configr   )rJ   ry   rz   r{   r|   r@   rs   rt   ru   rv   rw   rx   astr   snowflake_table_planplan	__class__s                   r5   rK   zTable.__init__!  s     !4**//1I#INN$8$8)DCSXXz2%)CKK",EC)+-=$$*$&/#!#)

 $*3==)D)+.~+>""(!#)

 -KK-)
  .&?1	 
 ))$$<<''@@(73D3D A  !**	 = D (D$)yQ#~~)*C'#5 
 	D"23r4   c                     i }| j                   r)|j                  | j                   j                                t        | j                  f| j
                  | j                  dd|S )NFrz   r{   r@   )r   rO   _asdictrq   ry   _sessionr   rJ   kwargss     r5   _copy_without_astzTable._copy_without_astg  sa    ##MM$22::<=OO
MM&*&E&E	

 
 	
r4   c                     i }| j                   r)|j                  | j                   j                                t        | j                  f| j
                  | j                  | j
                  j                  d|S )Nr   )r   rO   r   rq   ry   r   r   ast_enabledr   s     r5   __copy__zTable.__copy__t  sk    ##MM$22::<=OO
MM&*&E&Emm//	

 
 	
r4   c                     | S rC   r3   rT   s    r5   	__enter__zTable.__enter__  s    r4   c                 $    | j                          y rC   )
drop_table)rJ   exc_typeexc_valexc_tbs       r5   __exit__zTable.__exit__  s    r4   )seedsampling_methodr@   fracnr   r   r"   c                   t        j                  ||       |r!|j                         dvrt        d| d      ddlm} d}|r| j                  j                  j                         }t        |j                  j                  |      }|r||j                  _        |r||j                  _        |r||j                  _        |r||j                   _        | j#                  |j$                         t'        | j                  j(                  |      r|dv rt*        j-                  d       t/        | j0                  |||	      }	| j3                  | j                  j4                  j7                  | j                  j4                  j9                  |	| j                  j4                  
      | j                  j4                        |      S |xs d}
|t;        |dz        n| d}|d| dnd}d| j<                   d|
 d| d| }| j                  j?                  ||      }| j                  j@                  r%| j0                  jB                  |j0                  _!        |S )aU  Samples rows based on either the number of rows to be returned or a percentage of rows to be returned.

        Sampling with a seed is not supported on views or subqueries. This method works on tables so it supports ``seed``.
        This is the main difference between :meth:`DataFrame.sample` and this method.

        Args:
            frac: The percentage of rows to be sampled.
            n: The fixed number of rows to sample in the range of 0 to 1,000,000 (inclusive). Either ``frac`` or ``n`` should be provided.
            seed: Specifies a seed value to make the sampling deterministic. Can be any integer between 0 and 2147483647 inclusive.
                Default value is ``None``.
            sampling_method: Specifies the sampling method to use:
                - "BERNOULLI" (or "ROW"): Includes each row with a probability of p/100. Similar to flipping a weighted coin for each row.
                - "SYSTEM" (or "BLOCK"): Includes each block of rows with a probability of p/100. Similar to flipping a weighted coin for each block of rows. This method does not support fixed-size sampling.
                Default is ``None``. Then the Snowflake database will use "ROW" by default.

        Note:
            - SYSTEM | BLOCK sampling is often faster than BERNOULLI | ROW sampling.
            - Sampling without a seed is often faster than sampling with a seed.
            - Fixed-size sampling can be slower than equivalent fraction-based sampling because fixed-size sampling prevents some query optimization.
            - Fixed-size sampling doesn't work with SYSTEM | BLOCK sampling.

        )	BERNOULLIROWSYSTEMBLOCKz'sampling_method' value zA must be None or one of 'BERNOULLI', 'ROW', 'SYSTEM', or 'BLOCK'.r   MockServerConnectionN)r   r   zf[Local Testing] SYSTEM/BLOCK sampling is not supported for Local Testing, falling back to ROW sampling)probability_fraction	row_countr   r   r   r|    g      Y@z ROWSz SEED ()zSELECT * FROM z SAMPLE z (z) )"r"   _validate_sample_inputupper
ValueError#snowflake.snowpark.mock._connectionr   r   r   r   r   r   table_sampler   r   numr   r   _set_ast_refdfrR   _conn_loggerwarningr   _plan
_with_planr   r   create_select_snowflake_planrW   ry   sqlreduce_describe_query_enabled	_metadata)rJ   r   r   r   r   r@   r   stmtr   sample_plansampling_method_textfrac_or_rowcount_text	seed_textsql_textnew_dfs                  r5   samplezTable.sample  s>   @ 	((q1446 ?
  
 *?*;;|}  	M==++002D#DII$:$:DAC15((. !!%,;##)cff%dmm))+?@"55| !

K ??''??--11NN#dmm.E.E O  "]]44	 @   #    /4"595ED5L 1aSPU;)-)9gdV1%r	#DOO#4H=Q<RRTUjTkkmnwmxy""8t"<==66%)ZZ%9%9FLL"r4   )statement_paramsblockr@   rM   r?   sourcer   r   c                     y rC   r3   rJ   rM   r?   r   r   r   r@   s          r5   rO   zTable.update       	r4   zsnowflake.snowpark.AsyncJobc                     y rC   r3   r   s          r5   rO   zTable.update  r   r4   c                   |r	|J d       i }d}|rX| j                   j                  j                         }t        |j                  j
                  |      }	| j                  |	j                         |O|j                         D ]<  \  }
}|	j                  j                         }|
|_        t        |j                  |       > |t        |	j                  |       ||j                  |	j                          |t#        |	j$                  |       ||	_        | j                   j                  j)                  |       | j                   j                  j+                  |      \  }|t,        <   | j/                  t1        | j2                  |j                         D 
ci c].  \  }
}t5        |
      j6                  t5        j8                  |      0 c}}
||j6                  nd|r$t;        | |t=        d      g       d   j>                  nd      |      }tA        |d        |jB                  d||tD        jF                  jH                  jJ                  jL                  d|}|rtO        |      S |S c c}}
w )	aT  
        Updates rows in the Table with specified ``assignments`` and returns a
        :class:`UpdateResult`, representing the number of rows modified and the
        number of multi-joined rows modified.

        Args:
            assignments: A ``dict`` that associates the names of columns with the
                values that should be updated. The value of ``assignments`` can
                either be a literal value or a :class:`Column` object.
            condition: An optional :class:`Column` object representing the
                specified condition. It must be provided if ``source`` is provided.
            source: An optional :class:`DataFrame` that is included in ``condition``.
                It can also be another :class:`Table`.
            statement_params: Dictionary of statement level parameters to be set while executing this action.
            block: A bool value indicating whether this function will wait until the result is available.
                When it is ``False``, this function executes the underlying queries of the dataframe
                asynchronously and returns an :class:`AsyncJob`.

        Examples::

            >>> target_df = session.create_dataframe([(1, 1),(1, 2),(2, 1),(2, 2),(3, 1),(3, 2)], schema=["a", "b"])
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> t = session.table("my_table")

            >>> # update all rows in column "b" to 0 and all rows in column "a"
            >>> # to the summation of column "a" and column "b"
            >>> t.update({"b": 0, "a": t.a + t.b})
            UpdateResult(rows_updated=6, multi_joined_rows_updated=0)
            >>> t.sort("a", "b").collect()
            [Row(A=2, B=0), Row(A=3, B=0), Row(A=3, B=0), Row(A=4, B=0), Row(A=4, B=0), Row(A=5, B=0)]

            >>> # update all rows in column "b" to 0 where column "a" has value 1
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> t.update({"b": 0}, t["a"] == 1)
            UpdateResult(rows_updated=2, multi_joined_rows_updated=0)
            >>> t.sort("a", "b").collect()
            [Row(A=1, B=0), Row(A=1, B=0), Row(A=2, B=1), Row(A=2, B=2), Row(A=3, B=1), Row(A=3, B=2)]

            >>> # update all rows in column "b" to 0 where column "a" in this
            >>> # table is equal to column "a" in another dataframe
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> source_df = session.create_dataframe([1, 2, 3, 4], schema=["a"])
            >>> t.update({"b": 0}, t["a"] == source_df.a, source_df)
            UpdateResult(rows_updated=6, multi_joined_rows_updated=0)
            >>> t.sort("a", "b").collect()
            [Row(A=1, B=0), Row(A=1, B=0), Row(A=2, B=0), Row(A=2, B=0), Row(A=3, B=0), Row(A=3, B=0)]
        N7condition should also be provided if source is providedleftrd   r   Table.updater   r   	data_typer3   )(r   r   r   r   r   table_updater   r   itemsrM   add_1r   _2r   r?   r   r   r   r   evalflushr   r   r   ry   r!   rE   _to_exprr#   r   r   r   _internal_collect_with_tag	snowflakesnowpark	async_job_AsyncResultTypeUPDATErg   )rJ   rM   r?   r   r   r   r@   r   r   r   kvt_r   results                   r5   rO   zTable.update  sK   t %IHI% ==++002D#DII$:$:DACcff%&'--/ KDAq++-AADA!$$JK $/yI!##CJJ/+,S-A-ACSTCIMM$$))$/ 261I1I1O1OPT1U.Av-. !, 1 1 31 1I))6??1+== *3)>	%%D dF,<V,DbI!LRR
  ! 
 	V^,222 
-((22CCJJ
 	
 .3!&)>>'s   3I-c                     y rC   r3   rJ   r?   r   r   r   r@   s         r5   rP   zTable.deletek       	r4   c                     y rC   r3   r   s         r5   rP   zTable.deletex  r   r4   c                   |r	|J d       i }d}|r| j                   j                  j                         }t        |j                  j
                  |      }| j                  |j                         |t        |j                  |       ||j                  |j                         |t        |j                  |       ||_        | j                   j                  j                  |       | j                   j                  j                  |      \  }	|t         <   | j#                  t%        | j&                  ||j(                  nd|r$t+        | |t-        d      g       d   j.                  nd      |      }
t1        |
d        |
j2                  d||t4        j6                  j8                  j:                  j<                  d|}|rt?        |      S |S )	aU  
        Deletes rows in a Table and returns a :class:`DeleteResult`,
        representing the number of rows deleted.

        Args:
            condition: An optional :class:`Column` object representing the
                specified condition. It must be provided if ``source`` is provided.
            source: An optional :class:`DataFrame` that is included in ``condition``.
                It can also be another :class:`Table`.
            statement_params: Dictionary of statement level parameters to be set while executing this action.
            block: A bool value indicating whether this function will wait until the result is available.
                When it is ``False``, this function executes the underlying queries of the dataframe
                asynchronously and returns an :class:`AsyncJob`.

        Examples::

            >>> target_df = session.create_dataframe([(1, 1),(1, 2),(2, 1),(2, 2),(3, 1),(3, 2)], schema=["a", "b"])
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> t = session.table("my_table")

            >>> # delete all rows in a table
            >>> t.delete()
            DeleteResult(rows_deleted=6)
            >>> t.collect()
            []

            >>> # delete all rows where column "a" has value 1
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> t.delete(t["a"] == 1)
            DeleteResult(rows_deleted=2)
            >>> t.sort("a", "b").collect()
            [Row(A=2, B=1), Row(A=2, B=2), Row(A=3, B=1), Row(A=3, B=2)]

            >>> # delete all rows in this table where column "a" in this
            >>> # table is equal to column "a" in another dataframe
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> source_df = session.create_dataframe([2, 3, 4, 5], schema=["a"])
            >>> t.delete(t["a"] == source_df.a, source_df)
            DeleteResult(rows_deleted=4)
            >>> t.sort("a", "b").collect()
            [Row(A=1, B=1), Row(A=1, B=2)]
        Nr   r   rd   r   zTable.deleter   r3   ) r   r   r   r   r   table_deleter   r   r   r?   r   r   r   r   r   r   r   r   r   ry   rE   r#   r   r   r   r   r   r   r   r   DELETEri   )rJ   r?   r   r   r   r@   r   r   r   r   r   r   s               r5   rP   zTable.delete  s   h %IHI% ==++002D#DII$:$:DACcff%$/yI!##CJJ/+,S-A-ACSTCIMM$$))$/ 261I1I1O1OPT1U.Av-.)2)>	%%D dF,<V,DbI!LRR  ! 	
 	V^,222 
-((22CCJJ
 	
 .3!&)>>r4   	join_exprclausesc                     y rC   r3   rJ   r   r   r   r   r   r@   s          r5   mergezTable.merge  r   r4   c                     y rC   r3   r   s          r5   r   zTable.merge  r   r4   c                
   d\  }}}	g }
|D ]k  }t        |t              r t        |j                  t              rd}n!d}	nt        |t              rd}nt        d      |
j                  |j                         m i }d}|r| j                  j                  j                         }t        |j                  j                  |      }| j                  |j                         |j                  |j                         t!        |j"                  |       |D ]  }||j                  |j$                  j'                         }t        |t              r^t        |j                  t              r|j(                  j+                          |j                  j,                  }|h|j/                         D ]U  \  }}|j(                  j0                  j'                         }t!        |j2                  |       t!        |j4                  |       W |j6                  t!        |j(                  j8                  |j6                         -t        |j                  t:              sI|j<                  j+                          |j6                  qt!        |j<                  j8                  |j6                         t        |t              r2t        |j                  t>              s|j@                  j+                          |j                  jB                  K|j                  jB                  D ]2  }|j@                  jD                  j'                         }t!        ||       4 |j                  jF                  K|j                  jF                  D ]2  }|j@                  jH                  j'                         }t!        ||       4 |j6                  t!        |j@                  j8                  |j6                         t        tK        |       d       |tM        |jN                  |       ||_(        | j                  j                  jS                  |       | j                  j                  jU                  |      \  }|tV        <   | jY                  t[        | j\                  t_        | |ta        d      g       d   jb                  |jd                  |
      |      }tg        |d	        |jh                  d||tj        jl                  jn                  jp                  jr                  d
|}ddl:m;} |s5t        | j                  jx                  |      s||_=        ||_>        |	|_?        |rt        ||||	      S |S )at
  
        Merges this :class:`Table` with :class:`DataFrame` source on the specified
        join expression and a list of matched or not-matched clauses, and returns
        a :class:`MergeResult`, representing the number of rows inserted,
        updated and deleted by this merge action.
        See `MERGE <https://docs.snowflake.com/en/sql-reference/sql/merge.html#merge>`_
        for details.

        Args:
            source: A :class:`DataFrame` to join with this :class:`Table`.
                It can also be another :class:`Table`.
            join_expr: A :class:`Column` object representing the expression on which
                to join this :class:`Table` and ``source``.
            clauses: A list of matched or not-matched clauses specifying the actions
                to perform when the values from this :class:`Table` and ``source``
                match or not match on ``join_expr``. These actions can only be instances
                of :class:`WhenMatchedClause` and :class:`WhenNotMatchedClause`, and will
                be performed sequentially in this list.
            statement_params: Dictionary of statement level parameters to be set while executing this action.
            block: A bool value indicating whether this function will wait until the result is available.
                When it is ``False``, this function executes the underlying queries of the dataframe
                asynchronously and returns an :class:`AsyncJob`.

        Example::

            >>> from snowflake.snowpark.functions import when_matched, when_not_matched
            >>> from snowflake.snowpark.types import IntegerType, StringType, StructField, StructType
            >>> schema = StructType([StructField("key", IntegerType()), StructField("value", StringType())])
            >>> target_df = session.create_dataframe([(10, "old"), (10, "too_old"), (11, "old")], schema=schema)
            >>> target_df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
            >>> target = session.table("my_table")
            >>> source = session.create_dataframe([(10, "new"), (12, "new"), (13, "old")], schema=schema)
            >>> target.merge(source, (target["key"] == source["key"]) & (target["value"] == "too_old"),
            ...              [when_matched().update({"value": source["value"]}), when_not_matched().insert({"key": source["key"]})])
            MergeResult(rows_inserted=2, rows_updated=1, rows_deleted=0)
            >>> target.sort("key", "value").collect()
            [Row(KEY=10, VALUE='new'), Row(KEY=10, VALUE='old'), Row(KEY=11, VALUE='old'), Row(KEY=12, VALUE=None), Row(KEY=13, VALUE=None)]
        )FFFTzHclauses only accepts WhenMatchedClause or WhenNotMatchedClause instancesNz* is not a valid type for merge clause AST.r   rd   r   r   r   r   r   )rj   rk   rl   r3   )ArR   r>   rH   r   rY   	TypeErrorappendr   r   r   r   r   table_merger   r   r   r   r   r   r    merge_update_when_matched_clauseClear_assignmentsr   update_assignmentsr   r   rG   r?   r    merge_delete_when_matched_clauser   $merge_insert_when_not_matched_clause_keysinsert_keys_valuesinsert_valuestyper   r   r   r   r   r   r   r   ry   r#   r   r   rE   r   r   r   r   r   r   MERGEr   r   r   	_inserted_updated_deletedro   )rJ   r   r   r   r   r   r@   rj   rk   rl   merge_exprscr   r   r   r   matched_clauserM   r   r   r   r   r   r   r   s                            r5   r   zTable.merge   s   b &9"'7 	*A!./aii)>?"G"GA34^  qyy)	* ==++002D#DII$9$94@Ccff%

+9#--S  6$)B%([[__%6N!%):;%emm5JK*KKQQS*/--*D*DK*6,7,=,=,? 	!&DAq(6(W(W(j(j(n(n(p %& %R()a%& %R()a%&	!&  %//; M$2$S$S$]$]$)$4$4!" (7LM*KKQQS$//; M$2$S$S$]$]$)$4$4!"
 $E+?@%emm5JK*OOUUW$}}22>).)<)< !XA(6([([(g(g(k(k(m %& %RRSUV$W	!X
  %}}44@).)>)> !XA(6([([(i(i(m(m(o %& %RRSUV$W	!X
  %//; M$2$W$W$a$a$)$4$4!"
 (#E{m+UV i6p  +,S-A-ACSTCIMM$$))$/ 261I1I1O1OPT1U.Av-.dF,<V,DbI!LRR%%	  ! 
 	V^,222 
-((22CCII
 	
 	M Z(;(;=QR'F%FO%FO  !			
 		
r4   c                    ddl m} i }d}|r| j                  j                  j	                         }t        |j                  j                  |      }| j                  |j                         | j                  j                  j                  |       | j                  j                  j                  |      \  }|t        <   t        | j                  j                  |      r< | j                  j                  j                  j                   | j"                  fi | y | j                  j%                  d| j"                   |      j&                  di | y)a2  Drops the table from the Snowflake database.

        Note that subsequent operations such as :meth:`DataFrame.select`, :meth:`DataFrame.collect` on this ``Table`` instance and the derived DataFrame will raise errors because the underlying
        table in the Snowflake database no longer exists.
        r   r   Nzdrop table r   r3   )r   r   r   r   r   r   r   table_drop_tabler   r   r   r   r   rR   r   entity_registryr   ry   r   '_internal_collect_with_tag_no_telemetry)rJ   r@   r   r   r   r   r   s          r5   r   zTable.drop_table  s    	M==++002D#DII$>$>ECcff%MM$$))$/ 261I1I1O1OPT1U.Av-.dmm))+?@:DMM//::
6DMMdoo./   65@ 9?@r4   )NFNT)rA   rq   )NN)T)&r-   r.   r/   r0   r   rW   r   rV   protoBindr   r1   r	   datetimer%   rK   r   r   r   r   floatr   r
   r   r   r!   r"   r*   rO   r7   rP   r(   r>   rY   r;   r   r   __classcell__)r   s   @r5   rq   rq     s     CG*/*.C4 ?C#' $=ABF $C4C4 >?C4 $(	C4
 EJJ'C4 C4 #7>#:;C4 C=C4 C4 E#x'8'8"89:C4 !s,='=!>?C4 C4 
C4 C4J

  !%V
 #)-VuoV C=V
 smV "#V V 
V Vp  '+&*	
 6:
#./
 F#
 #	
 #4S>2
 
 
 

  
  '+&*	
 6:
#./
 F#
 #	
 #4S>2
 
 
 
'
  
  '+&*	l? 6:l?#./l? F#l? #	l? #4S>2l? l? l? 
|::	;l? l?\  '+&*	
 6:	F#	 #	
 #4S>2	 	 	 
	  	  '+&*	
 6:	F#	 #	
 #4S>2	 	 	 
'	  	  '+&*\?
 6:\?F#\? #\?
 #4S>2\? \? \? 
|::	;\? \?|  6:

 
 % 13G GHI	
 #4S>2
 
 
 

  
  6:

 
 % 13G GHI	
 #4S>2
 
 
 
'
  
  6:k
k
 k
 % 13G GHI	k
 #4S>2k
 k
 k
 
{99	:k
 k
Z @D @D @ @r4   rq   )Ksysr  loggingr   typingr   r   r   r   r   r	   r
   snowflake.snowparkr   4snowflake.snowpark._internal.proto.generated.ast_pb2r   	_internalr  	generatedast_pb26snowflake.snowpark._internal.analyzer.binary_plan_noder   9snowflake.snowpark._internal.analyzer.snowflake_plan_noder   <snowflake.snowpark._internal.analyzer.table_merge_expressionr   r   r   r   r   r   5snowflake.snowpark._internal.analyzer.unary_plan_noder   &snowflake.snowpark._internal.ast.utilsr   r   r   r   r   r   r   *snowflake.snowpark._internal.error_messager   &snowflake.snowpark._internal.telemetryr   r   'snowflake.snowpark._internal.type_utilsr   "snowflake.snowpark._internal.utilsr   r    snowflake.snowpark.columnr!   snowflake.snowpark.dataframer"   r#   snowflake.snowpark.rowr$   snowflake.snowpark.typesr%   version_infor(   collections.abcr-   r   r*   r7   r;   r>   rY   rg   ri   rV   ro   rq   r3   r4   r5   <module>r8     s<      M M M  D D D S T  I   W T C - A & 6
 v(
H
: : * ^ ^BK K\)T#Y )< ))T#Y )< )B
s)B#B.2B=ABB u
@I u
@r4   