YjFB8UddlmZddlZddlZddlZddlZddlmZddlZ ddl m Z ddl Z ejr ddlmZddlZej"eej&eedej*ffZded<ddZdd Zdd Zdd Zdd Zdd ZddZddZddZ ddZ!y)) annotationsN)Decimalregister_io_source)Iterator_ExpressionTreeztyping_extensions.TypeAliascvtj|jjd}t |S)aConvert a Polars predicate expression to a DuckDB-compatible SQL expression. Parameters: predicate (pl.Expr): A Polars expression (e.g., col("foo") > 5) Returns: SQLExpression: A DuckDB SQL expression string equivalent. None: If conversion fails. Example: >>> _predicate_to_expression(pl.col("foo") > 5) SQLExpression("(foo > 5)") jsonformat)r loadsmeta serialize_tree_to_sql_expression) predicatetrees d/mnt/ssd/data/Dropbox/adrian/tools/powerbricks/venv/lib/python3.12/site-packages/duckdb/polars_io.py_predicate_to_expressionrs/ ::inn..f.= >D "4 ((c^ tjt|S#t$rYywxYw)zConvert an already-parsed Polars expression tree to a DuckDB expression. Returns None if the tree contains a node we cannot translate to SQL. N)duckdb SQLExpression_pl_tree_to_sql Exceptionrs rrr)s/ ##OD$9:: s  ,,ct|tsy|jd}t|txr5t|jdtxr|dj dS)zReturn True if a serialized node is a dynamic predicate (see the note above). Detected by shape: a ``Display`` node whose ``fmt_str`` starts with ``dynamic_pred``. FDisplayfmt_str dynamic_pred) isinstancedictgetstr startswith)nodedisplays r_is_dynamic_predicate_noder'Bs^ dD !hhy!G7D! : w{{9-s 3 : I  ) ). 9rct|ryt|tr td|j DSt|t rtd|DSy)zTReturn True if the serialized expression tree contains a dynamic predicate anywhere.Tc32K|]}t|ywN _tree_contains_dynamic_predicate.0childs r z3_tree_contains_dynamic_predicate..VsVu3E:Vc32K|]}t|ywr*r+r-s rr0z3_tree_contains_dynamic_predicate..XsMu3E:Mr1F)r'r r!anyvalueslist)r%s rr,r,QsL!$'$V VVV$MMMM rcNt|ryt|trnd|vrj|d}t|trU|jddk(rAt |d\}}t |d\}}|xs|}|||fS|||fSdi|||di|fSt |r d}t ||d fS) uRemove dynamic-predicate conjuncts from a serialized predicate tree. See the note above for what a dynamic predicate is and why we drop it. Returns ``(stripped_tree, removed)``. ``stripped_tree`` is ``None`` when the predicate was purely dynamic. Raises ``NotImplementedError`` if a dynamic predicate appears anywhere other than a top-level ``And`` conjunct — a shape polars does not produce today, where the hint can neither be safely dropped nor applied. )NT BinaryExpropAndleftright)r:r;zICannot handle a polars dynamic predicate outside a top-level AND conjunctF)r'r r!r"_strip_dynamic_predicatesr,NotImplementedError)rbin_exprr: left_removedr; right_removedremovedmsgs rr<r<\s"$'$,$"6 % h %(,,t*<*E!:8F;K!L D,#>> _pl_operation_to_sql("Eq") '=' z>==%ANDOR)LtLtEqGtGtEqEqModulusr9Or)KeyErrorr=)r8s r_pl_operation_to_sqlr[sO &      &!"%%&s %c2|jdd}d|dS)zEscape SQL identifiers by doubling any double quotes and wrapping in double quotes. Example: >>> _escape_sql_identifier('column"name') '"column""name"' "z"")replace) identifierescapeds r_escape_sql_identifierras$  d+G wiq>rc|j\}|dk(r||}t|tsJd|dt||d|d|d}}}t|tsJd|dt|t|tsJd|d t|t|tsJd |dt|d t |d t |d t |d S|dk(r6||}t|tsJd|d t|t|S|dvr6||}t|tsJd|dt|t |S|dk(r9||}t|ttfsJdt|t |S|dk(r>||} t| tttfsJdt| t | S|dk(r||} t| tsJd|dt| | d} t| tsJd|dt| | d} t| tsJd|dt| | d} t| tsJd|dt| d| vr9| d}t | d}|dk(rd |dS|dk(rd |dSd |}t|d!| }t||d"k(r||}t|tsJd|dt||jd#}|d$k(r3|jd%i}t|trd&|vr"d'}t||d(k7rd)|}t||d%}t|tsJd|dt|t |S|d*k(r||}t|tsJd|dt|d+|vrd,|vrt |d+}|d,}n$tt|j}|}t|tsJd|d-t|t|tsJd|d.t||jd/s|d0k(r|d0}t|tsJd|d1t|d2t!|cxkrd3ksnJd|d1t!|d4t t#|dt#d5|d6zz S|jd7s|d8k(rp|d8}t|tsJd|d9t|t$j$j'|dd:z t$j(j*;}d<|d=S|d>vrt ||S|d?k(r~|d?}t|tsJd|d@t||dAz}|dAzdBz}t$j$j,t%j.||Czj1}d<|dDS|dEk(re|dE}t|ttfsJd|dFt|t%j2dGdHdHt%j.|Iz}d<|dJS|dKk(rT|dK} t| tsJd|dLt| t5| }!dMj7dN|!D}"d<|"dOS|dPk(s|dQk(r@|jdQ|jdPdR}#t t9j:|#SdS|dT|}t|dU|dV||}t|)WaRecursively convert a Polars expression tree (as JSON) to a SQL string. Parameters: tree (dict): JSON-deserialized expression tree from Polars Returns: str: SQL expression string Example: Input tree: { "BinaryExpr": { "left": { "Column": "foo" }, "op": "Gt", "right": { "Literal": { "Int": 5 } } } } Output: "(foo > 5)" r7zA z should be a dict but got r:r8r;z LHS of a z The op of a z should be a str but got z RHS of a ( )ColumnzThe col name of a )LiteralDynIntz4The value of an Int should be an int or str but got Floatz;The value of a Float should be a float, int or str but got Functioninputz. should have a list of dicts as input but got rfunctionz. should have a function dict as input but got BooleanIsNullz IS NULL) IsNotNullz IS NOT NULL)z Boolean function not supported: zUnsupported function type: CastoptionsStrictexprrgz;Strict cast on non-literal expression cannot be pushed down NonStrictz9Only NonStrict/Strict casts can be safely unwrapped, got Scalardtypevaluez" should have a str dtype but got z" should have a dict value but got z {'Decimal'rz. should be a two or three member list but got z member list z {'Datetime'Datetimez% should be a one member list but got i@B)tz'z '::TIMESTAMP) Int8Int16Int32Int64Int128UInt8UInt16UInt32UInt64UInt128Float32Float64rnTimez should be an int but got iʚ;i)seconds microsecondsz'::TIMEDatez should be a number but got i)daysz'::DATEBinaryz should be a list but got c3(K|] }d|d yw)z\x02xN)r.bs rr0z"_pl_tree_to_sql..UsAAc7mAsz'::BLOBString StringOwnedNzUnsupported scalar type z , with value z Node type: z is not implemented. )keysr r!typer#rr[raintfloatr5r=r"nextiterr$lenrdatetime fromtimestamptimezoneutcmin timedeltatimedatebytesjoinrConstantExpression)$r node_type bin_expr_treelhsr8rhscol_nameval_tree int_literal float_literal func_treeinputs input_tree func_dictfuncarg_sqlrB cast_treerr cast_expr scalar_treerwrx decimal_valuemicros dt_timestamp nanosecondsrrdt_timedays_since_epochr bin_value binary_datar` string_vals$ rrrs())+KYL Y -.o"YK?YZ^_lZmYn0oo.$V,mD.A=QXCYR#t$b )r*B)C1_UXEYDZZ[\\H ?(C(s,>ykIbcghpcqbr*ss(%h//&& ?(D)eR {:TUYZbUcTd+ee)x((E9o +Sz2 B4 CTBU V 2;GY -%c):; I$}J]I^ _ ;=!!JO )T*gb ;UVZ[dVeUf,gg*7#&$'u2i[8fgklrgsft)uu'AY *d+  I$zJZI[ \ +j) )T*  I$y/IZ [ *  !Y'D%fQi0Gx7)9--{"7)=114TF;C%c* *+I;7!#&&FO )T*gb ;UVZ[dVeUf,gg*-- * h " fb1Ii.)92LS)#..  #Mg[YC%c* *f% )T*gb ;UVZ[dVeUf,gg*y))H9o +t,k9+=WX\]hXiWj.kk, k !g&< G,-E(Ek..012EE%%fI;6XY]^cYdXe'ff%%&g"YK7YZ^_dZeYf(gg&   L )Ui-?!),MmT2 UGI$}J]I^_ 2M*/a/ UGI#mJ\I]]ij /w}Q/072rAR;R3SST T   M *ez.A:&Ffd+ lr%8]^bci^j]k-l l+#,,::6!9y;PU]UfUfUjUj:kL|&l3 3   uU|$ $ F?-Kk3/ j2eW.source_generatoris@ !!  #88C 6 EFD+33D9N  +11&9N  ::inn66f6EFD%>t%D "I{$!8!C!)NY)>y)I^g&  %+22>BN6@6H.002nNlNlmwNx !8!8$? 2L!-mmL1889KLLmmL11  2sD;D>T)schemais_pure) rzlist[str] | Nonerzpl.Expr | Noner int | NonerrreturnzIterator[pl.DataFrame]r)rrrs` r duckdb_sourcerfsI%2&%2!%2%2 %2 %2N .vt LLr)rpl.Exprrduckdb.Expression | None)rrrr)r% typing.Anyrbool)rrrz#tuple[_ExpressionTree | None, bool])rrrr)r8r#rr#)r_r#rr#)rrrr#)rzduckdb.DuckDBPyRelationrzpl.schema.Schemarz pl.LazyFrame)" __future__rrrGr typingdecimalrpolarsrDpolars.io.pluginsrr TYPE_CHECKINGcollections.abcrtyping_extensionsDictr#UnionrAnyr__annotations__rrr'r,r<rKr[rarrrrrrs" 0  (/5{{3 SRUWhjpjtjtMt@u;u/v,v)& 2 <U &,C#L*Mr