
    hh;                    x   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 	 d dlm	Z
 n# e$ r	 d dlmZ
 Y nw xY wd dlmZmZmZmZ d dlmZ er.d 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-	 djd$Z.d%d&dkd*Z/dld/Z0 G d0 d1          Z1dmd8Z2dnd;Z3 ed<=          dod?            Z4ej5        j6        Z6i e6j7        e
j8        e6j9        e
j:        e6j;        e
j<        e6j=        e
j>        e6j?        e
j@        e6jA        e
jB        e6jC        e
jD        e6jE        e
jF        e6jG        e
jH        e6jI        e
jJ        e6jK        e
jL        e6jM        e
jN        e6jO        e
jP        e6jQ        e
jR        e6jS        e
jT        e6jU        e
jV        e6jW        e
jX        ZYd@eZdA<   e
j[        e
j\        e
j]        e
j^        dBZ_dCeZdD<   e6j`        e6ja        fZbdpdGZcdqdJZddrdLZedsdNZfdtdSZg	 	 	 	 dudddUdVdvd^ZhdwddZidxdgZjdydhZkg diZldS )z    )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                   	 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)duckdbr0   ModuleNotFoundError__version__NotImplementedError
isinstancer   )r+   r-   r0   excmsgargss         M/var/www/histauto/venv/lib/python3.11/site-packages/narwhals/_duckdb/utils.pylambda_exprr:   :   s    0+++++++ 0 0 0aVM_aa!#&&C/0 #6:66BF99FDD$'''   	 
727 )	separatorexprsr=   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)r=   r>   s     r9   
concat_strrE   J   s=     6?W1[#i..151111AhDWQVDWDWDWW    dfr   r   list[tuple[str, Expression]]c               p   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)_call_evaluate_output_names_alias_output_nameslenAssertionErrorextendzip)rG   r>   native_resultsr-   native_series_listoutput_namesr7   s          r9   evaluate_exprsrT   Z   s     46N E E!ZZ^^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rF   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   r.   Nonec                    || _         d S N)_rel)selfrX   s     r9   __init__zDeferredTimeZone.__init__~   s    			rF   r?   c                P    | j         t          | j                  | _         | j         S )z;Fetch relation time zone (if it wasn't calculated already).)rW   fetch_rel_time_zoner\   )r]   s    r9   	time_zonezDeferredTimeZone.time_zone   s(     !)%8%C%CD"%%rF   )rX   r   r.   rY   )r.   r?   )	__name__
__module____qualname____doc__rW   __annotations__r^   propertyra    rF   r9   rV   rV   j   sh          " %)((((    & & & X& & &rF   rV   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    rKt          j        u r
                                S | j        d         d         }	
                    |		          S |d
k    r
                    j                  S t          |          S )Nliststructc           
     t    g | ]4}                     |d          t          |d                             5S )r      )namedtype)Fieldnative_to_narwhals_dtype).0childrl   dtypesrk   s     r9   
<listcomp>z,native_to_narwhals_dtype.<locals>.<listcomp>   sY       
 	 q258WFXYY     rF   arrayrq   r   )innershapeenum)
categoriesztimestamp with time zone)ra   )idrx   Listru   rw   childrenStructinsertArraytupler   V1EnumDatetimera   $_non_nested_native_to_narwhals_dtype)ri   rk   rl   duckdb_dtype_idr   rw   sizer|   r{   r~   rx   s    ``       @r9   ru   ru      s   
 #oO^F &  {{$\%7BTUU
 
 	
 (""(}}     
 &  
 
 	
 '!!"+t G9AhkW$$(+KE4LLDG$$$ AhkW$$ )q7<NOO||%uU|||<<<&  gj  ;;== !*1-a0
{{j{111444);)EFFF/IIIrF   rX   duckdb.DuckDBPyRelationc                j    |                      dd                                          }|J |d         S )Nzduckdb_settings()z;select value from duckdb_settings() where name = 'TimeZone'r   )queryfetchone)rX   results     r9   r`   r`      s?    YYZ hjj  !9rF      )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&   	timestampr(   )timestamp_nsbooleanintervaldecimaltimeblob)rx   Int128Int64Int32Int16Int8UInt128UInt64UInt32UInt16UInt8Float64Float32StringDater   BooleanDurationDecimalTimeBinarygetUnknown)r   rk   rx   s      r9   r   r      s   ^F6==??&,,.. 	6<<>> 	FLLNN	
 	6;;== 	FNN$$ 	6==?? 	FMMOO 	V]]__ 	FLLNN 	&.."" 	!! 	6==?? 	 	vs++  	--!" 	V__&&#$ -->>##OO%%>>##/  0 
c/6>>++,,1-rF   z0Mapping[type[DType], duckdb_dtypes.DuckDBPyType]NW_TO_DUCKDB_DTYPES)r%   r&   r'   r(   z-Mapping[TimeUnit, duckdb_dtypes.DuckDBPyType]TIME_UNIT_TO_TIMESTAMPrs   r   c                p   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 tA          |tB                    rd|j"         d}t          |          d|  }tG          |          )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 rh   )rr   narwhals_to_native_dtypers   )rv   fieldrl   rk   s     r9   
<dictcomp>z,narwhals_to_native_dtype.<locals>.<dictcomp>!  s=     
 
 
 J0gGYZZ
 
 
rF   r<   c              3  "   K   | ]
}d | dV  dS )[]Nrh   )rv   items     r9   	<genexpr>z+narwhals_to_native_dtype.<locals>.<genexpr>+  s*      "G"G4;t;;;"G"G"G"G"G"GrF   zConverting to z# dtype is not supported for DuckDB.zUnknown dtype: )$rx   	base_typer   r   r	   r   r   r   r4   r5   duckdb_dtypesDuckDBPyTyper~   
ValueErrorr   	time_unitra   r   TIMESTAMP_TZr   INTERVALr   r   r{   r1   	list_typer   fieldsstruct_typer   joinr|   
issubclassUNSUPPORTED_DTYPESrb   rN   )rs   rk   rl   rx   r   duckdb_typer7   tutzrel_tzr{   r   nw_innerduckdb_innerduckdb_shape_fmts    ``            r9   r   r      s
    ^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)/00 'Vy1VVV!#&&&
#E
#
#C


rF   into_expressionstr | Expressionc                N    t          | t                    rt          |           n| S r[   )r5   r?   col)r   s    r9   parse_into_expressionr   4  s$    #-os#C#CX3XrF   partition_byc                 R    | sdS d                     d | D                       }d| S )Nr<   , c                .    g | ]}t          |           S rh   )r   )rv   xs     r9   ry   z-generate_partition_by_sql.<locals>.<listcomp>;  s$    LLL!0335LLLrF   zpartition by r   )r   by_sqls     r9   generate_partition_by_sqlr   8  s=     rYYLL|LLLMMF#6###rF   namesc                 @    d                     d | D                       S )Nr   c              3  N   K   | ] }t          t          |                    V  !d S r[   )r?   r   )rv   rr   s     r9   r   z$join_column_names.<locals>.<genexpr>@  s.      66ST^^666666rF   r   )r   s    r9   join_column_namesr   ?  s#    9966666666rF   order_by
descendingSequence[bool]
nulls_lastc                p    |sdS d                     d t          || |          D                       }d| S )Nr<   ,c              3  x   K   | ]5\  }}}t          |           d t          |          d t          |          V  6dS ) N)r   DESCENDING_TO_ORDERNULLS_LAST_TO_NULLS_POS)rv   r   _descending_nulls_lasts       r9   r   z(generate_order_by_sql.<locals>.<genexpr>H  sg        'A{K !##oo&9+&FooI`alImoo     rF   z	order by )r   r
   )r   r   r   r   s       r9   generate_order_by_sqlr   C  s\      rXX  +5h
J+W+W    F  vrF   rh   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 followingr<   )z ignore nulls)z over (r   )r   r   rM   r   r?   removesuffixsql_expression)r-   r   r   r  r  r   r   r   pbflagsobrowsfuncs                r9   window_expressionr  O  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;;;<<<rF   	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 r[   )r?   )rv   r7   r  s     r9   r   z)catch_duckdb_exception.<locals>.<genexpr>r  sB       = = 	s9~~= = = = = =rF   )znot found in FROM clausez5this column cannot be referenced before it is defined)available_columns)r5   r1   BinderExceptionanyr   from_available_column_namescolumns)r  r  s   ` r9   catch_duckdb_exceptionr  o  s|     )V344 	
 = = = =
= = = : : 	
 #>#m
 
 
 	
 rF   rr   r8   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
  rC   )rr   r8   s     r9   functionr     s]    xAw~~:Q:::;;;T>D>>>rF   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 )r1   r"  ImportErrorr3   r4   )r-   r"  r6   r7   s       r9   r
  r
    sm    0((((((( 0 0 0aVM_aa!#&&C/0 =r;   )
UNITS_DICTrV   rC   r  r   rE   r   rT   r`   r   r   r   r   r:   rD   r   ru   r   r
  whenr  )r+   r,   r-   r   r.   r   )r>   r   r=   r?   r.   r   )rG   r   r>   r   r.   rH   )ri   rj   rk   r   rl   rV   r.   r   )rX   r   r.   r?   )r   r?   rk   r   r.   r   )rs   r   rk   r   rl   rV   r.   rj   )r   r   r.   r   )r   r   r.   r?   )r   r?   r.   r?   )r   r   r   r   r   r   r.   r?   )rh   rh   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  )rr   r?   r8   r   r.   r   )r-   r?   r.   r   )m
__future__r   	functoolsr   typingr   r1   r   duckdb.sqltypessqltypesr   r2   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   ConstantExpressionrD   CaseExpressionr%  FunctionExpressionrC   r:   rE   rT   rV   ru   r`   r   MAINrx   r   DOUBLEr   FLOATr   BLOBr   VARCHARr   BOOLEANr   DATEr   TIMEr   TINYINTr   SMALLINTr   INTEGERr   BIGINTr   HUGEINTr   UTINYINTr   	USMALLINTr   UINTEGERr   UBIGINTr   UHUGEINTr   rf   TIMESTAMP_STIMESTAMP_MS	TIMESTAMPTIMESTAMP_NSr   r   Categoricalr   r   r   r   r   r   r  r  r   r
  __all__rh   rF   r9   <module>rP     sX   " " " " " " "                         *+++++++ * * *))))))))* W V V V V V V V V V V V 3 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 
	
				


 
 $E22 !-mDD  * , (
 ,( ( ( (  57 X X X X X X     & & & & & & & &>.J .J .J .Jb    2- - - -: 
	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      nf&89 4 4 4 4nY Y Y Y$ $ $ $7 7 7 7	  	  	  	  02+-!= )-(,= = = = = =@   "        s   & 44