
    ˀh?                       d dl mZ d dlZd dlmZmZmZ d dlmZ d dl	m
Z
 d dlmZmZ d dlmZ d dlmZ d d	lmZ e
r- ej(                  e      5  d d
lmZmZ ddd       d dl	mZmZmZ  ej(                  e      5  d dlmZ ddd        G d d      Z G d d      Z G d d      Z	 	 	 	 ddZ 	 	 	 	 ddZ!	 	 	 	 d dZ"	 	 	 	 d!dZ# G d de      Z$	 	 	 	 d"dZ% G d de      Z& G d de      Z'y# 1 sw Y   xY w# 1 sw Y   }xY w)#    )annotationsN)IterableMappingSequence)Path)TYPE_CHECKING)	DataFramecol)PartitioningScheme)issue_unstable_warning)Expr)PyDataFramePyExpr)IOAnyCallable)PyPartitioningc                  @    e Zd ZU dZd
dZded<   ded<   ded<   ddZy	)KeyedPartitiona0  
    A key-value pair for a partition.

    .. warning::
        This functionality is currently considered **unstable**. It may be
        changed at any point without it being considered a breaking change.

    See Also
    --------
    PartitionByKey
    PartitionParted
    KeyedPartitionContext
    namestr	str_value	raw_valuer   c                .    || _         || _        || _        y Nr   r   r   )selfr   r   r   s       o/var/www/html/wine-match-dev/backend/winematch-backend/venv/lib/python3.12/site-packages/polars/io/partition.py__init__zKeyedPartition.__init__&   s    	""    c                8    | j                    d| j                   S )zGet the `key=value`.=)r   r   )r   s    r   	hive_namezKeyedPartition.hive_name/   s    ))Adnn-..r    N)r   r   r   r   r   r   returnNone)r$   r   )__name__
__module____qualname____doc__r   __annotations__r#    r    r   r   r      s"    #
 INN/r    r   c                  z    e Zd ZU dZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZded<   ded<   ded<   ded<   d	ed<   d	ed
<   ddZy)KeyedPartitionContexta*  
    Callback context for a partition creation using keys.

    .. warning::
        This functionality is currently considered **unstable**. It may be
        changed at any point without it being considered a breaking change.

    See Also
    --------
    PartitionByKey
    PartitionParted
    file_idxintpart_idxin_part_idxkeyslist[KeyedPartition]	file_pathr   	full_pathc                X    || _         || _        || _        || _        || _        || _        y r   r.   r0   r1   r2   r4   r5   )r   r.   r0   r1   r2   r4   r5   s          r   r   zKeyedPartitionContext.__init__B   s/     ! &	""r    c                    t        | j                        dkD  sJ t        | j                  d   j                               }| j                  dd D ]  }|t        |j                               z  }  |S )z$The keys mapped to hive directories.r      N)lenr2   r   r#   )r   pkeys      r   	hive_dirszKeyedPartitionContext.hive_dirs[   sf    499~!!!1'')*99QR= 	'Ccmmo&&A	'r    N)r.   r/   r0   r/   r1   r/   r2   r3   r4   r   r5   r   r$   r%   )r$   r   )r&   r'   r(   r)   r   r*   r=   r+   r    r   r-   r-   4   sz    ## # 	#
 ## # # 
#  MM
Or    r-   c                  8    e Zd ZU dZd	dZded<   ded<   ded<   y)
BasePartitionContexta  
    Callback context for a partition creation.

    .. warning::
        This functionality is currently considered **unstable**. It may be
        changed at any point without it being considered a breaking change.

    See Also
    --------
    PartitionMaxSize
    r.   r/   r4   r   r5   c                .    || _         || _        || _        y r   r.   r4   r5   )r   r.   r4   r5   s       r   r   zBasePartitionContext.__init__q   s     ""r    N)r.   r/   r4   r   r5   r   r$   r%   )r&   r'   r(   r)   r   r*   r+   r    r   r?   r?   d   s     
#
 MOr    r?   c                      y  fdS )Nc           	          t        | j                  t        | j                        t        | j                                    S )NrA   )r?   r.   r   r4   r5   )ctxfile_path_cbs    r   <lambda>z)_cast_base_file_path_cb.<locals>.<lambda>   s3    |\\3==)3==)	
 r    r+   rE   s   `r   _cast_base_file_path_cbrH   }   s      r    c                      y  fdS )Nc                H    t        | j                  | j                  | j                  | j                  D cg c].  }t        |j                  |j                  |j                        0 c}t        | j                        t        | j                                    S c c}w )Nr   r7   )r-   r.   r0   r1   r2   r   r   r   r   r   r4   r5   )rD   kvrE   s     r   rF   z*_cast_keyed_file_path_cb.<locals>.<lambda>   s~    |\\\\
 ((	  BLLBLL 3==)3==)	
 
s   3Br+   rG   s   `r   _cast_keyed_file_path_cbrL      s      r    c                   dd}| y t        | t              rt        |       j                  gS t        | t              r| j                  gS t        | t
              r| D cg c]
  } ||       c}S d| }t        |      c c}w )Nc                    t        | t              rt        |       j                  S t        | t              r| j                  S d| }t        |      )N&cannot do a per partition sort by for )
isinstancer   r
   _pyexprr   	TypeError)vmsgs     r   prepare_onez3_prepare_per_partition_sort_by.<locals>.prepare_one   sD    aq6>>!4 99:1%@CC. r    rO   )rS   
str | Exprr$   r   )rP   r   r
   rQ   r   r   rR   )erU   rS   rT   s       r   _prepare_per_partition_sort_byrX      s|    ! 	y	As	A	At			{	Ax	 ()*1A**6qe<n +s   Bc                      y d fd}|S )Nc                <     t        j                  |              y r   )r	   
_from_pydf)pydffs    r   cbz$_prepare_finish_callback.<locals>.cb   s    	)

t
$%r    )r\   r   r$   r%   r+   )r]   r^   s   ` r   _prepare_finish_callbackr_      s     	y& Ir    c                  D     e Zd ZdZdddd	 	 	 	 	 	 	 	 	 	 	 d fdZ xZS )PartitionMaxSizeao  
    Partitioning scheme to write files with a maximum size.

    This partitioning scheme generates files that have a given maximum size. If
    the size reaches the maximum size, it is closed and a new file is opened.

    .. warning::
        This functionality is currently considered **unstable**. It may be
        changed at any point without it being considered a breaking change.

    Parameters
    ----------
    base_path
        The base path for the output files.
    file_path
        A callback to register or modify the output path for each partition
        relative to the `base_path`. The callback provides a
        :class:`polars.io.partition.BasePartitionContext` that contains information
        about the partition.

        If no callback is given, it defaults to `{ctx.file_idx}.{EXT}`.
    max_size : int
        The maximum size in rows of each of the generated files.
    per_partition_sort_by
        Columns or expressions to sort over within each partition.

        Note that this might increase the memory consumption needed for each partition.
    finish_callback
        A callback that gets called when the query finishes successfully.

        For parquet files, the callback is given a dataframe with metrics about all
        files written files.

    Examples
    --------
    Split a parquet file by over smaller CSV files with 100 000 rows each:

    >>> pl.scan_parquet("/path/to/file.parquet").sink_csv(
    ...     PartitionMax("./out", max_size=100_000),
    ... )  # doctest: +SKIP

    See Also
    --------
    PartitionByKey
    PartitionParted
    polars.io.partition.BasePartitionContext
    N)r4   per_partition_sort_byfinish_callbackc                   t        d       t        | 	  t        j                  |t        |      |t        |      t        |                   y )N0partitioning strategies are considered unstable.)	base_pathrE   max_sizerb   rc   )r   superr   r   new_max_sizerH   rX   r_   )r   rf   r4   rg   rb   rc   	__class__s         r   r   zPartitionMaxSize.__init__   sL     	QR''#4Y?!&D)' !9 I
	
r    )rf   
str | Pathr4   ICallable[[BasePartitionContext], Path | str | IO[bytes] | IO[str]] | Nonerg   r/   rb   (str | Expr | Iterable[str | Expr] | Nonerc   "Callable[[DataFrame], None] | Noner$   r%   r&   r'   r(   r)   r   __classcell__rj   s   @r   ra   ra      sY    .j JN>B

	
 
  H
 <
 

 
r    ra   c                   dd}t        | t              rt        |       j                  g}|S t        | t              r| j                  g}|S t        | t
              r!| D cg c]  } ||      j                   }}|S t        | t              r=| j                         D cg c]   \  }}|j                  |      j                  " }}}|S d}t        |      c c}w c c}}w )Nc                <    t        | t              rt        |       S | S r   )rP   r   r
   )is    r   to_exprz_lower_by.<locals>.to_expr  s    aq6MHr    zinvalid `by` type)rt   rV   r$   r   )
rP   r   r
   rQ   r   r   r   itemsaliasrR   )byru   
lowered_byrW   nrT   s         r   	_lower_byr{     s     "c"goo&
  
B	jj\
  
B	!245Qgaj((5
5  
B	 57XXZ@TQaggaj((@
@
  "n 6@s    C %Cc                  J     e Zd ZdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ xZS )PartitionByKeya
  
    Partitioning scheme to write files split by the values of keys.

    This partitioning scheme generates an arbitrary amount of files splitting
    the data depending on what the value is of key expressions.

    The amount of files that can be written is not limited. However, when
    writing beyond a certain amount of files, the data for the remaining
    partitions is buffered before writing to the file.

    .. warning::
        This functionality is currently considered **unstable**. It may be
        changed at any point without it being considered a breaking change.

    Parameters
    ----------
    base_path
        The base path for the output files.

        Use the `mkdir` option on the `sink_*` methods to ensure directories in
        the path are created.
    file_path
        A callback to register or modify the output path for each partition
        relative to the `base_path`. The callback provides a
        :class:`polars.io.partition.KeyedPartitionContext` that contains information
        about the partition.

        If no callback is given, it defaults to
        `{ctx.keys.hive_dirs()}/{ctx.in_part_idx}.{EXT}`.
    by
        The expressions to partition by.
    include_key : bool
        Whether to include the key columns in the output files.
    per_partition_sort_by
        Columns or expressions to sort over within each partition.

        Note that this might increase the memory consumption needed for each partition.
    finish_callback
        A callback that gets called when the query finishes successfully.

        For parquet files, the callback is given a dataframe with metrics about all
        files written files.

    Examples
    --------
    Split into a hive-partitioning style partition:

    >>> (
    ...     pl.DataFrame({"a": [1, 2, 3], "b": [5, 7, 9], "c": ["A", "B", "C"]})
    ...     .lazy()
    ...     .sink_parquet(
    ...         PartitionByKey(
    ...             "./out",
    ...             by=[pl.col.a, pl.col.b],
    ...             include_key=False,
    ...         ),
    ...         mkdir=True,
    ...     )
    ... )  # doctest: +SKIP

    Split a parquet file by a column `year` into CSV files:

    >>> pl.scan_parquet("/path/to/file.parquet").sink_csv(
    ...     PartitionByKey(
    ...         "./out/",
    ...         file_path=lambda ctx: f"year={ctx.keys[0].str_value}.csv",
    ...         by="year",
    ...     ),
    ... )  # doctest: +SKIP

    See Also
    --------
    PartitionMaxSize
    PartitionParted
    polars.io.partition.KeyedPartitionContext
    NTr4   include_keyrb   rc   c                   t        d       t        |      }t        |   t	        j
                  |t        |      ||t        |      t        |                   y Nre   )rf   rE   rx   r   rb   rc   	r   r{   rh   r   r   
new_by_keyrL   rX   r_   	r   rf   r4   rx   r   rb   rc   ry   rj   s	           r   r   zPartitionByKey.__init__y  X     	QRr]
%%#5i@'&D)' !9 I		
r    rf   rk   r4   JCallable[[KeyedPartitionContext], Path | str | IO[bytes] | IO[str]] | Nonerx   6str | Expr | Sequence[str | Expr] | Mapping[str, Expr]r   boolrb   rm   rc   rn   r$   r%   ro   rq   s   @r   r}   r}   +  sh    Kd  JN>B

	
 C
 
  H
 <
 

 
r    r}   c                  J     e Zd ZdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ xZS )PartitionPartedab  
    Partitioning scheme to split parted dataframes.

    This is a specialized version of :class:`PartitionByKey`. Where as
    :class:`PartitionByKey` accepts data in any order, this scheme expects the input
    data to be pre-grouped or pre-sorted. This scheme suffers a lot less overhead than
    :class:`PartitionByKey`, but may not be always applicable.

    Each new value of the key expressions starts a new partition, therefore repeating
    the same value multiple times may overwrite previous partitions.

    .. warning::
        This functionality is currently considered **unstable**. It may be
        changed at any point without it being considered a breaking change.

    Parameters
    ----------
    base_path
        The base path for the output files.

        Use the `mkdir` option on the `sink_*` methods to ensure directories in
        the path are created.
    file_path
        A callback to register or modify the output path for each partition
        relative to the `base_path`.The callback provides a
        :class:`polars.io.partition.KeyedPartitionContext` that contains information
        about the partition.

        If no callback is given, it defaults to
        `{ctx.keys.hive_dirs()}/{ctx.in_part_idx}.{EXT}`.
    by
        The expressions to partition by.
    include_key : bool
        Whether to include the key columns in the output files.
    per_partition_sort_by
        Columns or expressions to sort over within each partition.

        Note that this might increase the memory consumption needed for each partition.
    finish_callback
        A callback that gets called when the query finishes successfully.

        For parquet files, the callback is given a dataframe with metrics about all
        files written files.

    Examples
    --------
    Split a parquet file by a column `year` into CSV files:

    >>> pl.scan_parquet("/path/to/file.parquet").sink_csv(
    ...     PartitionParted("./out", by="year"),
    ...     mkdir=True,
    ... )  # doctest: +SKIP

    See Also
    --------
    PartitionMaxSize
    PartitionByKey
    polars.io.partition.KeyedPartitionContext
    NTr~   c                   t        d       t        |      }t        |   t	        j
                  |t        |      ||t        |      t        |                   y r   r   r   s	           r   r   zPartitionParted.__init__  r   r    r   ro   rq   s   @r   r   r     sg    :B  JN>B

	
 C
 
  H
 <
 

 
r    r   )rE   rl   r$   rl   )rE   r   r$   r   )rW   rm   r$   zlist[PyExpr] | None)r]   rn   r$   z$Callable[[PyDataFrame], None] | None)rx   r   r$   zlist[PyExpr])(
__future__r   
contextlibcollections.abcr   r   r   pathlibr   typingr   polarsr	   r
   polars._typingr   polars._utils.unstabler   polars.exprr   suppressImportErrorpolars.polarsr   r   r   r   r   r   r   r-   r?   rH   rL   rX   r_   ra   r{   r}   r   r+   r    r   <module>r      s@   "  7 7    ! - 9 			[	) 656 )(Z% -,-/ /:- -` 2 O P./2
)
)
F
) F
R>2g
' g
TV
( V
O6 6
- -s   	C3<C?3C<?D