o
    $&]i:                     @  s  U d dl mZ d dlmZ d dlmZ d dlZd dlmZ zd dlm	Z
 W n ey4   d dlmZ
 Y nw d dlmZmZmZmZ d dlmZ erwd dl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!m"Z" ddddddddddd
Z#dddZ$dddZ%ej&Z'	 ej(Z)	 ej*Z+	 ej,Z-	 dyd$d%Z.d&d'dzd+d,Z/d{d1d2Z0G d3d4 d4Z1d|d;d<Z2d}d?d@Z3edAdBd~dDdEZ4ej5j6Z6i e6j7e
j8e6j9e
j:e6j;e
j<e6j=e
j>e6j?e
j@e6jAe
jBe6jCe
jDe6jEe
jFe6jGe
jHe6jIe
jJe6jKe
jLe6jMe
jNe6jOe
jPe6jQe
jRe6jSe
jTe6jUe
jVe6jWe
jXZYdFeZdG< e
j[e
j\e
j]e
j^dHZ_dIeZdJ< e6j`e6jafZbddMdNZcddQdRZdddTdUZeddWdXZfdd]d^Zg	_	_		dddd`daddidjZhddpdqZiddtduZjddvdwZkg dxZldS )    )annotations)	lru_cache)TYPE_CHECKINGN)
Expression)Versionextend_boolisinstance_or_issubclass
zip_strict)ColumnNotFoundError)MappingSequence)DuckDBPyRelation)CompliantLazyFrameAny)DuckDBLazyFrame)
DuckDBExpr)DType)	IntoDTypeTimeUnityearquartermonthdayhourminutesecondmillisecondmicrosecond
nanosecond)
yqmodhmsmsusnsdescasc)TFz
nulls lastznulls firstparams)str | Expression | tuple[Expression, ...]exprr   returnc             
   C  s^   zddl m} W n ty } zdt j }t||d}~ww t| tr(| fn| }|||S )z}Wraps [`duckdb.LambdaExpression`].

    [`duckdb.LambdaExpression`]: https://duckdb.org/docs/stable/sql/functions/lambda
    r   )LambdaExpressionz<DuckDB>=1.2.0 is required for this operation. Found: DuckDB N)duckdbr.   ModuleNotFoundError__version__NotImplementedError
isinstancer   )r*   r,   r.   excmsgargs r7   T/var/www/html/IGF-ODF-V3/venv/lib/python3.10/site-packages/narwhals/_duckdb/utils.pylambda_expr:   s   

r9    )	separatorexprsr;   strc                 G  s*   | rt dt| g|R  S t dg|R  S )a  Concatenate many strings, NULL inputs are skipped.

    Wraps [concat] and [concat_ws] `FunctionExpression`(s).

    Arguments:
        exprs: Native columns.
        separator: String that will be used to separate the values of each column.


    [concat]: https://duckdb.org/docs/stable/sql/functions/char.html#concatstring-
    [concat_ws]: https://duckdb.org/docs/stable/sql/functions/char.html#concat_wsseparator-string-
    	concat_wsconcat)Flit)r;   r<   r7   r7   r8   
concat_strJ   s   *rB   dfr   r   list[tuple[str, Expression]]c                G  sv   g }|D ]4}|| }| | }|jd ur||}t|t|kr0d| dt| d}t||t|| q|S )Nz!Internal error: got output names z, but only got z results)_evaluate_output_names_alias_output_nameslenAssertionErrorextendzip)rC   r<   native_resultsr,   native_series_listoutput_namesr5   r7   r7   r8   evaluate_exprs_and_aliasesZ   s   


rN   c                   @  s6   e Zd ZU dZdZded< dd	d
ZedddZdS )DeferredTimeZonea  Object which gets passed between `native_to_narwhals_dtype` calls.

    DuckDB stores the time zone in the connection, rather than in the dtypes, so
    this ensures that when calculating the schema of a dataframe with multiple
    timezone-aware columns, that the connection's time zone is only fetched once.

    Note: we cannot make the time zone a cached `DuckDBLazyFrame` property because
    the time zone can be modified after `DuckDBLazyFrame` creation:

    ```python
    df = nw.from_native(rel)
    print(df.collect_schema())
    rel.query("set timezone = 'Asia/Kolkata'")
    print(df.collect_schema())  # should change to reflect new time zone
    ```
    Nz
str | None_cached_time_zonerelr   r-   Nonec                 C  s
   || _ d S N)_rel)selfrQ   r7   r7   r8   __init__~   s   
zDeferredTimeZone.__init__r=   c                 C  s   | j du rt| j| _ | j S )z;Fetch relation time zone (if it wasn't calculated already).N)rP   fetch_rel_time_zonerT   )rU   r7   r7   r8   	time_zone   s   
zDeferredTimeZone.time_zone)rQ   r   r-   rR   )r-   r=   )	__name__
__module____qualname____doc__rP   __annotations__rV   propertyrX   r7   r7   r7   r8   rO   j   s   
 
rO   duckdb_dtypeduckdb_dtypes.DuckDBPyTypeversionr   deferred_time_zoner   c           
        s  | j }j|dkrt| j S |dkr)| j} fdd|D S |dkre| j\}}|d g}|d j dkrT|d j\}}|d|d  |d j dks>t|d  }j|t	|dS |d	krt
ju rr S | jd d }	j|	d
S |dkrj jdS t|S )Nliststructc                   s*   g | ]}j |d  t|d  dqS )r      )namedtype)Fieldnative_to_narwhals_dtype).0childrb   dtypesra   r7   r8   
<listcomp>   s    z,native_to_narwhals_dtype.<locals>.<listcomp>arrayre   r   )innershapeenum)
categoriesztimestamp with time zone)rX   )idrm   Listri   rk   childrenStructinsertArraytupler   V1EnumDatetimerX   $_non_nested_native_to_narwhals_dtype)
r_   ra   rb   duckdb_dtype_idrv   rk   sizerq   rp   rs   r7   rl   r8   ri      s<   




ri   rQ   duckdb.DuckDBPyRelationc                 C  s$   |  dd }|d usJ |d S )Nzduckdb_settings()z;select value from duckdb_settings() where name = 'TimeZone'r   )queryfetchone)rQ   resultr7   r7   r8   rW      s   rW      )maxsizer   c                 C  s   |j }i d| d| d| d| d| d| d| d| d	|	 d
|
 d| d| d| d| d|dd|dd| |d| | | | | d| | S )Nhugeintbigintintegersmallinttinyintuhugeintubigintuinteger	usmallintutinyintdoublefloatvarchardatetimestamp_sr$   timestamp_msr%   	timestampr'   )timestamp_nsbooleanintervaldecimaltimeblob)rm   Int128Int64Int32Int16Int8UInt128UInt64UInt32UInt16UInt8Float64Float32StringDater}   BooleanDurationDecimalTimeBinarygetUnknown)r   ra   rm   r7   r7   r8   r~      sZ   	


r~   z0Mapping[type[DType], duckdb_dtypes.DuckDBPyType]NW_TO_DUCKDB_DTYPES)r$   r%   r&   r'   z-Mapping[TimeUnit, duckdb_dtypes.DuckDBPyType]TIME_UNIT_TO_TIMESTAMPrg   r   c                   s  j }|  }t| }r|S t| |jr6tju r!d}t|t	| |jr0t
d| jS d}t|t| |jrm| j}| j}|sHt| S |dkrVd| d}t|| j }	krjd|	 d| d	}t|t
jS t| |jr| j }dkrd
| d}t
jS t| |jrt| j }
t|
S t| |jr fdd| jD }t|S t	| |jr| }t	||jr|j}t	||jst| }ddd | jD }t
| | S t |t!rd|j" d}t|d|  }t#|)Nz9Converting to Enum is not supported in narwhals.stable.v1ENUMz9Can not cast / initialize Enum without categories presentr&   zUOnly microsecond precision is supported for timezone-aware `Datetime` in DuckDB, got z
 precisionzOnly the connection time zone z is supported, got: .z6Only microsecond-precision Duration is supported, got c                   s   i | ]}|j t|j qS r7   )rf   narwhals_to_native_dtyperg   )rj   fieldrb   ra   r7   r8   
<dictcomp>!  s    z,narwhals_to_native_dtype.<locals>.<dictcomp>r:   c                 s  s    | ]	}d | dV  qdS )[]Nr7   )rj   itemr7   r7   r8   	<genexpr>+      z+narwhals_to_native_dtype.<locals>.<genexpr>zConverting to z# dtype is not supported for DuckDB.zUnknown dtype: )$rm   	base_typer   r   r   r|   r   r{   r2   r3   duckdb_dtypesDuckDBPyTypers   
ValueErrorr}   	time_unitrX   r   TIMESTAMP_TZr   INTERVALru   r   rp   r/   	list_typerw   fieldsstruct_typery   joinrq   
issubclassUNSUPPORTED_DTYPESrY   rH   )rg   ra   rb   rm   r   duckdb_typer5   tutzrel_tzrp   r   nw_innerduckdb_innerduckdb_shape_fmtr7   r   r8   r      sb   




r   into_expressionstr | Expressionc                 C  s   t | tr	t| S | S rS   )r3   r=   col)r   r7   r7   r8   parse_into_expression4  s   r   partition_byc                  G  s&   | sdS d dd | D }d| S )Nr:   , c                 S  s   g | ]}t | qS r7   )r   )rj   xr7   r7   r8   rn   ;  s    z-generate_partition_by_sql.<locals>.<listcomp>zpartition by r   )r   by_sqlr7   r7   r8   generate_partition_by_sql8  s   
r   namesc                  G  s   d dd | D S )Nr   c                 s  s    | ]	}t t|V  qd S rS   )r=   r   )rj   rf   r7   r7   r8   r   @  r   z$join_column_names.<locals>.<genexpr>r   )r   r7   r7   r8   join_column_names?  s   r   order_by
descendingSequence[bool]
nulls_lastc                 G  s.   |sdS d dd t|| |D }d| S )Nr:   ,c                 s  s6    | ]\}}}t | d t|  d t|  V  qdS ) N)r   DESCENDING_TO_ORDERNULLS_LAST_TO_NULLS_POS)rj   r   _descending_nulls_lastr7   r7   r8   r   H  s
    
z(generate_order_by_sql.<locals>.<genexpr>z	order by )r   r	   )r   r   r   r   r7   r7   r8   generate_order_by_sqlC  s   


r   r7   F)r   r   ignore_nullsSequence[str | Expression]
rows_start
int | Nonerows_endSequence[bool] | Noner   boolc             	   C  s   t | }tdt|}	|p|	}|p|	}t|||d}
|d ur.|d ur.d|  d| d}n|d ur9d| d}n|d urEd|  d}nd}|rSt| d	 d
nt| }t| d| d|
 d| d	S )NF)r   r   zrows between z preceding and z
 followingz%rows between unbounded preceding and z" preceding and unbounded followingr:   )z ignore nulls)z over (r   )r   r   rG   r   r=   removesuffixsql_expression)r,   r   r   r   r   r   r   r   pbflagsobrowsfuncr7   r7   r8   window_expressionO  s     r   	exception	Exceptionframer   ColumnNotFoundError | Exceptionc                  s4   t  tjrt fdddD rtj|jdS  S )Nc                 3  s    | ]	}|t  v V  qd S rS   )r=   )rj   r5   r   r7   r8   r   r  s
    

z)catch_duckdb_exception.<locals>.<genexpr>)znot found in FROM clausez5this column cannot be referenced before it is defined)available_columns)r3   r/   BinderExceptionanyr
   from_available_column_namescolumns)r   r   r7   r   r8   catch_duckdb_exceptiono  s   r  rf   r6   c                 G  s@   | dkr
|d   S | dkrtd|d  dS t| g|R  S )Nisnullr   count_distinctzcount(distinct r   )r  r   r@   )rf   r6   r7   r7   r8   function  s
   r  c              
   C  sF   zddl m} W || S  ty" } zdt j }t||d }~ww )Nr   )SQLExpressionz<DuckDB>=1.3.0 is required for this operation. Found: DuckDB )r/   r	  ImportErrorr1   r2   )r,   r	  r4   r5   r7   r7   r8   r     s   
r   )
UNITS_DICTrO   r@   r  r   rB   r   rW   r  r   r   r   r9   rA   r   ri   r   r   whenr   )r*   r+   r,   r   r-   r   )r<   r   r;   r=   r-   r   )rC   r   r<   r   r-   rD   )r_   r`   ra   r   rb   rO   r-   r   )rQ   r   r-   r=   )r   r=   ra   r   r-   r   )rg   r   ra   r   rb   rO   r-   r`   )r   r   r-   r   )r   r   r-   r=   )r   r=   r-   r=   )r   r   r   r   r   r   r-   r=   )r7   r7   NN)r,   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r-   r   )r   r   r   r   r-   r   )rf   r=   r6   r   r-   r   )r,   r=   r-   r   )m
__future__r   	functoolsr   typingr   r/   r   duckdb.sqltypessqltypesr   r0   duckdb.typingnarwhals._utilsr   r   r   r	   narwhals.exceptionsr
   collections.abcr   r   r   narwhals._compliant.typingr   narwhals._duckdb.dataframer   narwhals._duckdb.exprr   narwhals.dtypesr   narwhals.typingr   r   r  r   r   ColumnExpressionr   ConstantExpressionrA   CaseExpressionr  FunctionExpressionr@   r9   rB   rN   rO   ri   rW   r~   MAINrm   r   DOUBLEr   FLOATr   BLOBr   VARCHARr   BOOLEANr   DATEr   TIMEr   TINYINTr   SMALLINTr   INTEGERr   BIGINTr   HUGEINTr   UTINYINTr   	USMALLINTr   UINTEGERr   UBIGINTr   UHUGEINTr   r]   TIMESTAMP_STIMESTAMP_MS	TIMESTAMPTIMESTAMP_NSr   r   Categoricalr   r   r   r   r   r   r   r  r  r   __all__r7   r7   r7   r8   <module>   s    





1	


7



 

	