
    XIg3                         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 ddlmZ ddlmZ dd	lmZ dd
lmZ erddlmZ ddgZdddededefdZdedef   dedef   fdZ G d d      Z G d d      Zy)   )ContributionsAcceptedError    )CallableTYPE_CHECKINGoverloadDictUnionList   )Column)SparkSession)	DataFrame)_to_column_expr)ColumnOrName)NumericType)LiteralTypeGroupedDataGroupingselfnamecolsreturnc                 0   dj                  t        |            }| j                  rt        | j                        nd}| j                  j	                         } t        | j                  j                  d      ||||      }t        || j                        S )N, apply)function_namefunction_aggr
group_exprprojected_columns)
joinlist	_groupingstrget_columnsgetattr_dfrelationr   session)r   r   r   expressionsgroup_byprojectionsjdfs          `/var/www/html/answerous/venv/lib/python3.12/site-packages/duckdb/experimental/spark/sql/group.py_api_internalr/   !   sx    ((4:&K&*nns4>>""H..,,.K
-'$((##W
-!%	C S$,,''    f.c                 t     dddt         dt        f fd} j                  |_         j                  |_        |S )Nr   r   r   r   c                 6    j                   }t        | |g| S N)__name__r/   )r   r   r   r1   s      r.   _apizdf_varargs_api.<locals>._api.   s    zzT4/$//r0   )r$   r   r5   __doc__)r1   r6   s   ` r.   df_varargs_apir8   -   s:    0= 0 0 0 JJDM99DLKr0   c                   &    e Zd ZddZdefdZd Zy)r   c                     d| _         |D cg c]  }t        |       c}| _        d|v r|d   }ddg}||v sJ || _         y y c c}w )Nr   specialcuberollup)_typer   _cols)r   r   kwargsxr;   accepted_specials         r.   __init__zGrouping.__init__8   s]    
267Qoa(7
Y'G &1.... DJ	  8s   Ar   c                 t    dj                  | j                  D cg c]  }t        |       c}      }|S c c}w )Nr   )r!   r?   r$   )r   rA   columnss      r.   r%   zGrouping.get_columnsA   s-    ((DJJ7qCF78 8s   5c                 h    | j                         }| j                  r| j                  dz   |z   dz   S |S )N())r%   r>   )r   rE   s     r.   __str__zGrouping.__str__E   s5    ""$::::#g-33r0   N)r   r   )r5   
__module____qualname__rC   r$   r%   rI    r0   r.   r   r   7   s    !S r0   c                      e Zd ZdZdedefdZdefdZdefdZ	e
dedefd	       Zdedefd
Ze
dedefd       Ze
dedefd       Ze
dedefd       Zededefd       Zedeeef   defd       Zdeeeeef   f   defdZy)r   zo
    A set of methods for aggregations on a :class:`DataFrame`,
    created by :func:`DataFrame.groupBy`.

    groupingdfc                 B    || _         || _        |j                  | _        y r4   )r#   r'   r)   )r   rN   rO   s      r.   rC   zGroupedData.__init__S   s    !%'ZZr0   r   c                 ,    t        | j                        S r4   )r$   r'   r   s    r.   __repr__zGroupedData.__repr__X   s    488}r0   c                 :    t        | d      j                  dd      S )a~  Counts the number of records for each group.

        Examples
        --------
        >>> df = spark.createDataFrame(
        ...      [(2, "Alice"), (3, "Alice"), (5, "Bob"), (10, "Bob")], ["age", "name"])
        >>> df.show()
        +---+-----+
        |age| name|
        +---+-----+
        |  2|Alice|
        |  3|Alice|
        |  5|  Bob|
        | 10|  Bob|
        +---+-----+

        Group-by name, and count each group.

        >>> df.groupBy(df.name).count().sort("name").show()
        +-----+-----+
        | name|count|
        +-----+-----+
        |Alice|    2|
        |  Bob|    2|
        +-----+-----+
        countzcount_star())r/   withColumnRenamedrR   s    r.   rU   zGroupedData.count[   s    6 T7+==ngVVr0   r   c                      y)zComputes average values for each numeric columns for each group.

        :func:`mean` is an alias for :func:`avg`.

        Parameters
        ----------
        cols : str
            column names. Non-numeric columns are ignored.
        NrL   r   r   s     r.   meanzGroupedData.meanx       r0   c                     t        |      }t        |      dk(  rT| j                  j                  }|j                  D cg c])  }t        |j                  t              s|j                  + }}t        | dg| S c c}w )a  Computes average values for each numeric columns for each group.

        :func:`mean` is an alias for :func:`avg`.

        Parameters
        ----------
        cols : str
            column names. Non-numeric columns are ignored.

        Examples
        --------
        >>> df = spark.createDataFrame([
        ...     (2, "Alice", 80), (3, "Alice", 100),
        ...     (5, "Bob", 120), (10, "Bob", 140)], ["age", "name", "height"])
        >>> df.show()
        +---+-----+------+
        |age| name|height|
        +---+-----+------+
        |  2|Alice|    80|
        |  3|Alice|   100|
        |  5|  Bob|   120|
        | 10|  Bob|   140|
        +---+-----+------+

        Group-by name, and calculate the mean of the age in each group.

        >>> df.groupBy("name").avg('age').sort("name").show()
        +-----+--------+
        | name|avg(age)|
        +-----+--------+
        |Alice|     2.5|
        |  Bob|     7.5|
        +-----+--------+

        Calculate the mean of the age and height in all data.

        >>> df.groupBy().avg('age', 'height').show()
        +--------+-----------+
        |avg(age)|avg(height)|
        +--------+-----------+
        |     5.0|      110.0|
        +--------+-----------+
        r   avg)
r"   lenr'   schemafields
isinstancedataTyper   r   r/   )r   r   rE   r^   rA   s        r.   r\   zGroupedData.avg   sh    X t*w<1XX__F28--!gQ:ajjZeCf!&&!gG!gT53733 "hs   A;A;c                      y)a2  Computes the max value for each numeric columns for each group.

        Examples
        --------
        >>> df = spark.createDataFrame([
        ...     (2, "Alice", 80), (3, "Alice", 100),
        ...     (5, "Bob", 120), (10, "Bob", 140)], ["age", "name", "height"])
        >>> df.show()
        +---+-----+------+
        |age| name|height|
        +---+-----+------+
        |  2|Alice|    80|
        |  3|Alice|   100|
        |  5|  Bob|   120|
        | 10|  Bob|   140|
        +---+-----+------+

        Group-by name, and calculate the max of the age in each group.

        >>> df.groupBy("name").max("age").sort("name").show()
        +-----+--------+
        | name|max(age)|
        +-----+--------+
        |Alice|       3|
        |  Bob|      10|
        +-----+--------+

        Calculate the max of the age and height in all data.

        >>> df.groupBy().max("age", "height").show()
        +--------+-----------+
        |max(age)|max(height)|
        +--------+-----------+
        |      10|        140|
        +--------+-----------+
        NrL   rX   s     r.   maxzGroupedData.max   rZ   r0   c                      y)a  Computes the min value for each numeric column for each group.

        Parameters
        ----------
        cols : str
            column names. Non-numeric columns are ignored.

        Examples
        --------
        >>> df = spark.createDataFrame([
        ...     (2, "Alice", 80), (3, "Alice", 100),
        ...     (5, "Bob", 120), (10, "Bob", 140)], ["age", "name", "height"])
        >>> df.show()
        +---+-----+------+
        |age| name|height|
        +---+-----+------+
        |  2|Alice|    80|
        |  3|Alice|   100|
        |  5|  Bob|   120|
        | 10|  Bob|   140|
        +---+-----+------+

        Group-by name, and calculate the min of the age in each group.

        >>> df.groupBy("name").min("age").sort("name").show()
        +-----+--------+
        | name|min(age)|
        +-----+--------+
        |Alice|       2|
        |  Bob|       5|
        +-----+--------+

        Calculate the min of the age and height in all data.

        >>> df.groupBy().min("age", "height").show()
        +--------+-----------+
        |min(age)|min(height)|
        +--------+-----------+
        |       2|         80|
        +--------+-----------+
        NrL   rX   s     r.   minzGroupedData.min   rZ   r0   c                      y)a  Computes the sum for each numeric columns for each group.

        Parameters
        ----------
        cols : str
            column names. Non-numeric columns are ignored.

        Examples
        --------
        >>> df = spark.createDataFrame([
        ...     (2, "Alice", 80), (3, "Alice", 100),
        ...     (5, "Bob", 120), (10, "Bob", 140)], ["age", "name", "height"])
        >>> df.show()
        +---+-----+------+
        |age| name|height|
        +---+-----+------+
        |  2|Alice|    80|
        |  3|Alice|   100|
        |  5|  Bob|   120|
        | 10|  Bob|   140|
        +---+-----+------+

        Group-by name, and calculate the sum of the age in each group.

        >>> df.groupBy("name").sum("age").sort("name").show()
        +-----+--------+
        | name|sum(age)|
        +-----+--------+
        |Alice|       5|
        |  Bob|      15|
        +-----+--------+

        Calculate the sum of the age and height in all data.

        >>> df.groupBy().sum("age", "height").show()
        +--------+-----------+
        |sum(age)|sum(height)|
        +--------+-----------+
        |      20|        440|
        +--------+-----------+
        NrL   rX   s     r.   sumzGroupedData.sum
  rZ   r0   exprsc                      y r4   rL   )r   rh   s     r.   aggzGroupedData.agg6      r0   _GroupedData__exprsc                      y r4   rL   )r   rl   s     r.   rj   zGroupedData.agg:  rk   r0   c                    |sJ d       t        |      dk(  rt        |d   t              rt        t	        d |D              sJ d       t        | j                  j                        }|j                  |D cg c]  }|j                   c}       t        | j                        } | j                  j                  j                  |d|i}t        || j                        S c c}w )a  Compute aggregates and returns the result as a :class:`DataFrame`.

        The available aggregate functions can be:

        1. built-in aggregation functions, such as `avg`, `max`, `min`, `sum`, `count`

        2. group aggregate pandas UDFs, created with :func:`pyspark.sql.functions.pandas_udf`

           .. note:: There is no partial aggregation with group aggregate UDFs, i.e.,
               a full shuffle is required. Also, all the data of a group will be loaded into
               memory, so the user should be aware of the potential OOM risk if data is skewed
               and certain groups are too large to fit in memory.

           .. seealso:: :func:`pyspark.sql.functions.pandas_udf`

        If ``exprs`` is a single :class:`dict` mapping from string to string, then the key
        is the column to perform aggregation on, and the value is the aggregate function.

        Alternatively, ``exprs`` can also be a list of aggregate :class:`Column` expressions.

        .. versionadded:: 1.3.0

        .. versionchanged:: 3.4.0
            Supports Spark Connect.

        Parameters
        ----------
        exprs : dict
            a dict mapping from column name (string) to aggregate functions (string),
            or a list of :class:`Column`.

        Notes
        -----
        Built-in aggregation functions and group aggregate pandas UDFs cannot be mixed
        in a single call to this function.

        Examples
        --------
        >>> from pyspark.sql import functions as F
        >>> from pyspark.sql.functions import pandas_udf, PandasUDFType
        >>> df = spark.createDataFrame(
        ...      [(2, "Alice"), (3, "Alice"), (5, "Bob"), (10, "Bob")], ["age", "name"])
        >>> df.show()
        +---+-----+
        |age| name|
        +---+-----+
        |  2|Alice|
        |  3|Alice|
        |  5|  Bob|
        | 10|  Bob|
        +---+-----+

        Group-by name, and count each group.

        >>> df.groupBy(df.name)
        GroupedData[grouping...: [name...], value: [age: bigint, name: string], type: GroupBy]

        >>> df.groupBy(df.name).agg({"*": "count"}).sort("name").show()
        +-----+--------+
        | name|count(1)|
        +-----+--------+
        |Alice|       2|
        |  Bob|       2|
        +-----+--------+

        Group-by name, and calculate the minimum age.

        >>> df.groupBy(df.name).agg(F.min(df.age)).sort("name").show()
        +-----+--------+
        | name|min(age)|
        +-----+--------+
        |Alice|       2|
        |  Bob|       5|
        +-----+--------+

        Same as above but uses pandas UDF.

        >>> @pandas_udf('int', PandasUDFType.GROUPED_AGG)  # doctest: +SKIP
        ... def min_udf(v):
        ...     return v.min()
        ...
        >>> df.groupBy(df.name).agg(min_udf(df.age)).sort("name").show()  # doctest: +SKIP
        +-----+------------+
        | name|min_udf(age)|
        +-----+------------+
        |Alice|           2|
        |  Bob|           5|
        +-----+------------+
        zexprs should not be emptyr   r   c              3   <   K   | ]  }t        |t                y wr4   )r`   r   ).0cs     r.   	<genexpr>z"GroupedData.agg.<locals>.<genexpr>  s     <z!V,<s   zall exprs should be Columngroups)r]   r`   dictr   allr"   r#   r?   extendexprr$   r'   r(   selectr   r)   )r   rh   r*   rA   r+   rels         r.   rj   zGroupedData.agg>  s    t 111uu:?z%(D9,, <e<<Z>ZZ<t~~334K61674>>*H*$((##**KIICdll++  7s   8C#N)r5   rJ   rK   r7   r   r   rC   r$   rS   rU   r8   rY   r\   rc   re   rg   r   r   rj   r   r	   rL   r0   r.   r   r   L   sG   0 0y 0
# Wy W: 	# 	) 	 	14 14 14f $ $ $ $L ) ) ) )V ) ) ) )V & Y   4S> i  d,%S#X 67 d,I d,r0   N)	exceptionr   typingr   r   r   r   r	   r
   columnr   r)   r   	dataframer   	functionsr   _typingr   typesr   r   __all__r$   r/   r8   r   r   rL   r0   r.   <module>r      s   $ 3 G G  !   & ! $*
%
( 
(S 
( 
( 
(hsI~. 8CN3K  *V, V,r0   