
    }i=                       U d dl mZ d dlmZ d dlmZmZ d dlZd dlmZ d dl	m
Z
mZmZmZmZ d dlmZ er4d 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 d dlm Z m!Z! eZ"de#d<   	 e
j$        %                                Z&	 ese&dk    rd dlm'Z( nd dl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j0        Z1	 ej2        Z3	 dpd*Z4d+d,dqd0Z5drd5Z6 G d6 d7          Z7dsd>Z8dtdAZ9 edBC          dudE            Z:ej;        j<        Z<i e<j=        e(j>        e<j?        e(j@        e<jA        e(jB        e<jC        e(jD        e<jE        e(jF        e<jG        e(jH        e<jI        e(jJ        e<jK        e(jL        e<jM        e(jN        e<jO        e(jP        e<jQ        e(jR        e<jS        e(jT        e<jU        e(jV        e<jW        e(jX        e<jY        e(jZ        e<j[        e(j\        e<j]        e(j^        Z_dFe#dG<   e(j`        e(ja        e(jb        e(jc        dHZddIe#dJ<   e<je        ZfdvdMZgdwdPZhdxdRZidydTZjdzdYZk	 	 	 	 d{ddd[d\d|ddZld}djZmd~dmZnddnZog doZpdS )    )annotations)	lru_cache)TYPE_CHECKINGAnyN)
Expression)ImplementationVersionextend_boolisinstance_or_issubclass
zip_strict)ColumnNotFoundError)MappingSequence)DuckDBPyRelation)	TypeAlias)CompliantLazyFrameAny)DuckDBLazyFrame)
DuckDBExpr)DType)	IntoDTypeTimeUnitr   
Incomplete)      )sqltypes)typing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                   	 ddl m} n1# t          $ r$}dt           j         }t	          |          |d}~ww xY 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)duckdbr8   ModuleNotFoundError__version__NotImplementedError
isinstancer   )r3   r5   r8   excmsgargss         J/home/jrussi/.local/lib/python3.11/site-packages/narwhals/_duckdb/utils.pylambda_exprrB   G   s    0+++++++ 0 0 0aVM_aa!#&&C/0 #6:66BF99FDD$'''   	 
727 )	separatorexprsrE   strc                V    | rt          dt          |           g|R  n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)rE   rF   s     rA   
concat_strrM   W   s=     6?W1[#i..151111AhDWQVDWDWDWW    dfr   r   list[tuple[str, Expression]]c               \   g }|D ]} ||           }|                     |           }|j        |                    |          }t          |          t          |          k    r%d| dt          |           d}t          |          |                    t          ||                     |S )Nz!Internal error: got output names z, but only got z results)_evaluate_output_names_alias_output_nameslenAssertionErrorextendzip)rO   rF   native_resultsr5   native_series_listoutput_namesr?   s          rA   evaluate_exprs_and_aliasesr[   g   s     46N E E!T"XX22266#/33LAAL|$6 7 777tlttSVWiSjSjtttC %%%c,0BCCDDDDrN   c                  B    e Zd ZU dZdZded<   dd	Ze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   r6   Nonec                    || _         d S N)_rel)selfr_   s     rA   __init__zDeferredTimeZone.__init__   s    			rN   rG   c                P    | j         t          | j                  | _         | j         S )z;Fetch relation time zone (if it wasn't calculated already).)r^   fetch_rel_time_zonerc   )rd   s    rA   	time_zonezDeferredTimeZone.time_zone   s(     !)%8%C%CD"%%rN   )r_   r   r6   r`   )r6   rG   )	__name__
__module____qualname____doc__r^   __annotations__re   propertyrh    rN   rA   r]   r]   w   sh          " %)((((    & & & X& & &rN   r]   duckdb_dtypeduckdb_dtypes.DuckDBPyTypeversionr	   deferred_time_zoner   c                   | j         }j        |dk    r)                    t          | j                            S |dk    r*| j        }                    fd|D                       S |dk    r| j        \  }}|d         g}|d         j         dk    r=|d         j        \  }}|                    d|d                    |d         j         dk    =t          |d                   }                    |t          |                    S |dk    rJt          j        u r                                S | j        d         d         }	                    |	          S |d	k    r                    j        
          S |dk    r&| j        \  \  }
}\  }
}                    ||          S t!          |          S )Nliststructc           
     t    g | ]4}                     |d          t          |d                             5S )r   r   )namedtype)Fieldnative_to_narwhals_dtype).0childrs   dtypesrr   s     rA   
<listcomp>z,native_to_narwhals_dtype.<locals>.<listcomp>   sY       
 	 q258WFXYY     rN   arrayr   r   )innershapeenumztimestamp with time zone)rh   decimal)idr~   Listr{   r}   childrenStructinsertArraytupler	   V1EnumDatetimerh   Decimal$_non_nested_native_to_narwhals_dtype)rp   rr   rs   duckdb_dtype_idr   r}   sizer   r   
categories_	precisionscaler~   s    ``          @rA   r{   r{      s   
 (?O^F &  {{$\%7BTUU
 
 	
 (""8D8M}}     
 &  
 
 	
 '!! #+ta	AhkW$$(+KE4LLDG$$$ AhkW$$ )q7<NOO||%uU|||<<<&  gj  ;;== !-!6q!9!!<
{{:&&&444);)EFFF)## &2%:"I
E~~i////IIIrN   r_   duckdb.DuckDBPyRelationc                j    |                      dd                                          }|J |d         S )Nzduckdb_settings()z;select value from duckdb_settings() where name = 'TimeZone'r   )queryfetchone)r_   results     rA   rg   rg      s?    YYZ hjj  !9rN      )maxsizer   c                   |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.   	timestampr0   )timestamp_nsbooleanintervaltimeblob)r~   Int128Int64Int32Int16Int8UInt128UInt64UInt32UInt16UInt8Float64Float32StringDater   BooleanDurationTimeBinarygetUnknown)r   rr   r~   s      rA   r   r      s   ^F6==??&,,.. 	6<<>> 	FLLNN	
 	6;;== 	FNN$$ 	6==?? 	FMMOO 	V]]__ 	FLLNN 	&.."" 	!! 	6==?? 	 	vs++  	--!" 	V__&&#$ -->>##OO%%-  . 
c/6>>++,,/-rN   z0Mapping[type[DType], duckdb_dtypes.DuckDBPyType]NW_TO_DUCKDB_DTYPES)r-   r.   r/   r0   z-Mapping[TimeUnit, duckdb_dtypes.DuckDBPyType]TIME_UNIT_TO_TIMESTAMPry   r   c                   j         }|                                 }t                              |          x}r|S t	          | |j                  rat          j        u rd}t          |          t          | |j                  rt          j        d| j                  S d}t          |          t	          | |j                  ri| j        }| j        }|st"          |         S |dk    rd| d}t          |          |j        x}	k    rd|	 d| d	}t          |          t          j        S t	          | |j                  r| j        x}dk    rd
| d}t          j        S t	          | |j                  r*t-          | j                  }
t1          j        |
          S t	          | |j                  r(fd| j        D             }t1          j        |          S t          | |j                  r| }t          ||j                  r|j        }t          ||j                  t-          |          }d                    d | j        D                       }t          j        | |           S t          | |j                   r%t          j        d| j!         d| j"         d          S tG          |tH                    rd|j%         d}t          |          d|  }tM          |          )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                H    i | ]}|j         t          |j                  S ro   )rx   narwhals_to_native_dtypery   )r|   fieldrs   rr   s     rA   
<dictcomp>z,narwhals_to_native_dtype.<locals>.<dictcomp>5  s=     
 
 
 J0gGYZZ
 
 
rN   rD   c              3  "   K   | ]
}d | dV  dS )[]Nro   )r|   items     rA   	<genexpr>z+narwhals_to_native_dtype.<locals>.<genexpr>?  s*      "G"G4;t;;;"G"G"G"G"G"GrN   zDECIMAL(, )zConverting to z# dtype is not supported for DuckDB.zUnknown dtype: )'r~   	base_typer   r   r   r   r	   r   r<   r=   duckdb_dtypesDuckDBPyTyper   
ValueErrorr   	time_unitrh   r   TIMESTAMP_TZr   INTERVALr   r   r   r9   	list_typer   fieldsstruct_typer   joinr   r   r   r   
issubclassUNSUPPORTED_DTYPESri   rU   )ry   rr   rs   r~   r   duckdb_typer?   tutzrel_tzr   r   nw_innerduckdb_innerduckdb_shape_fmts    ``            rA   r   r     sH    ^F!!I)--i888{ v{33 gj  MC%c***eV[)) 	K -.IU5E.I.IJJJIoov77 *__ 	.)"--::xjlxxxCS//!.88&99T6TTrTTTCS//!))v77 &/!Bd**Y2YYYC%%v{33 '(g?QRR&&&v}55 *
 
 
 
 

 
 
 !&)))%&& O#6<00 	&~H 6<00 	&/'CUVV77"G"G5;"G"G"GGG)\*M;K*M*MNNN%(( X)*VU_*V*V*V*V*VWWW)/00 'Vy1VVV!#&&&
#E
#
#C


rN   into_expressionstr | Expressionc                N    t          | t                    rt          |           n| S rb   )r=   rG   col)r   s    rA   parse_into_expressionr   J  s$    #-os#C#CX3XrN   partition_byc                 R    | sdS d                     d | D                       }d| S )NrD   r   c                .    g | ]}t          |           S ro   )r   )r|   xs     rA   r   z-generate_partition_by_sql.<locals>.<listcomp>Q  s$    LLL!0335LLLrN   zpartition by r   )r   by_sqls     rA   generate_partition_by_sqlr   N  s=     rYYLL|LLLMMF#6###rN   namesc                 @    d                     d | D                       S )Nr   c              3  N   K   | ] }t          t          |                    V  !d S rb   )rG   r   )r|   rx   s     rA   r   z$join_column_names.<locals>.<genexpr>V  s.      66ST^^666666rN   r   )r   s    rA   join_column_namesr   U  s#    9966666666rN   order_by
descendingSequence[bool]
nulls_lastc                p    |sdS d                     d t          || |          D                       }d| S )NrD   ,c              3  x   K   | ]5\  }}}t          |           d t          |          d t          |          V  6dS ) N)r   DESCENDING_TO_ORDERNULLS_LAST_TO_NULLS_POS)r|   r   _descending_nulls_lasts       rA   r   z(generate_order_by_sql.<locals>.<genexpr>^  sg        'A{K !##oo&9+&FooI`alImoo     rN   z	order by )r   r   )r   r   r   r   s       rA   generate_order_by_sqlr	  Y  s\      rXX  +5h
J+W+W    F  vrN   ro   F)r   r   ignore_nullsSequence[str | Expression]
rows_start
int | Nonerows_endSequence[bool] | Noner
  boolc          
     b   t          | }t          dt          |                    }	|p|	}|p|	}t          |||d}
||d|  d| d}n|d| d}n|d|  d}nd}|r%t	          |                               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 followingrD   r   z ignore nulls)z over (r  )r   r
   rT   r	  rG   removesuffixsql_expression)r5   r   r   r  r  r   r   r
  pbflagsobrowsfuncs                rA   window_expressionr  e  s    
#L	1Bs8}}--E$uJ$uJ	ZJ	W	W	WB("6O
{OO8OOO		KxKKK		N
{NNN=IXc$ii$$S))9999sSWyyDT;;";;r;;D;;;<<<rN   	exception	Exceptionframer   ColumnNotFoundError | Exceptionc                    t           t          j                  r5t           fddD                       rt	          j        |j                  S  S )Nc              3  :   K   | ]}|t                    v V  d S rb   )rG   )r|   r?   r  s     rA   r   z)catch_duckdb_exception.<locals>.<genexpr>  sB       = = 	s9~~= = = = = =rN   )znot found in FROM clausez5this column cannot be referenced before it is defined)available_columns)r=   r9   BinderExceptionanyr   from_available_column_namescolumns)r  r  s   ` rA   catch_duckdb_exceptionr%    s|     )V344 	
 = = = =
= = = : : 	
 #>#m
 
 
 	
 rN   rx   r@   c                    | 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  rK   )rx   r@   s     rA   functionr)    s]    xAw~~:Q:::;;;T>D>>>rN   c                    	 ddl m} n1# t          $ r$}dt           j         }t	          |          |d }~ww xY w ||           S )Nr   )SQLExpressionz<DuckDB>=1.3.0 is required for this operation. Found: DuckDB )r9   r+  ImportErrorr;   r<   )r5   r+  r>   r?   s       rA   r  r    sm    0((((((( 0 0 0aVM_aa!#&&C/0 =rC   )
UNITS_DICTr]   rK   r%  r   rM   r   rg   r)  r	  r   r   rB   rL   r   r{   r   r  whenr  )r3   r4   r5   r   r6   r   )rF   r   rE   rG   r6   r   )rO   r   rF   r   r6   rP   )rp   rq   rr   r	   rs   r]   r6   r   )r_   r   r6   rG   )r   rG   rr   r	   r6   r   )ry   r   rr   r	   rs   r]   r6   rq   )r   r   r6   r   )r   r   r6   rG   )r   rG   r6   rG   )r   r   r   r   r   r   r6   rG   )ro   ro   NN)r5   r   r   r  r   r  r  r  r  r  r   r  r   r  r
  r  r6   r   )r  r  r  r   r6   r  )rx   rG   r@   r   r6   r   )r5   rG   r6   r   )q
__future__r   	functoolsr   r   r   r   r9   r   narwhals._utilsr   r	   r
   r   r   narwhals.exceptionsr   collections.abcr   r   r   typing_extensionsr   narwhals._compliant.typingr   narwhals._duckdb.dataframer   narwhals._duckdb.exprr   narwhals.dtypesr   narwhals.typingr   r   r   rm   DUCKDB_backend_versionBACKEND_VERSIONr   r   r-  r  r  ColumnExpressionr   ConstantExpressionrL   CaseExpressionr.  FunctionExpressionrK   rB   rM   r[   r]   r{   rg   r   MAINr~   r   DOUBLEr   FLOATr   BLOBr   VARCHARr   BOOLEANr   DATEr   TIMEr   TINYINTr   SMALLINTr   INTEGERr   BIGINTr   HUGEINTr   UTINYINTr   	USMALLINTr   UINTEGERr   UBIGINTr   UHUGEINTr   TIMESTAMP_STIMESTAMP_MS	TIMESTAMPTIMESTAMP_NSr   Categoricalr   r   r   r   r   r	  r  r%  r)  r  __all__ro   rN   rA   <module>rY     s   " " " " " " "       % % % % % % % %                     4 3 3 3 3 3 
411111111''''''++++++@@@@@@::::::000000%%%%%%33333333
    > !'88:: * /Ov--0000000...... 
	
				


 
 $E22 !-mDD  * , (
 ,( ( ( (  57 X X X X X X     & & & & & & & &>6J 6J 6J 6Jr    2- - - -8 
	I
NM(I
NM'I M=%I M=(	I
 NM)I K#I K#I K&I L-(I L-'I L-&I M=(I L-(I M=*I M=)I  M=(!I" NM*#I     ( 
	"

$

!

$	I I      ' 6 6 6 6rY Y Y Y$ $ $ $7 7 7 7	  	  	  	  02+-!= )-(,= = = = = =@   "        rN   