3939//! a refusal that is raised only if gradient actually reaches it.
4040
4141use std:: borrow:: Cow ;
42- use std:: collections:: { BTreeSet , HashMap } ;
42+ use std:: collections:: { BTreeSet , HashMap , HashSet } ;
4343use std:: ops:: ControlFlow ;
4444use std:: rc:: Rc ;
4545
@@ -48,6 +48,8 @@ use prost::Message;
4848use substrait:: proto:: aggregate_rel:: Grouping ;
4949use substrait:: proto:: expression:: mask_expression:: { StructItem , StructSelect } ;
5050use substrait:: proto:: expression:: { MaskExpression , RexType , WindowFunction } ;
51+ use substrait:: proto:: extensions:: simple_extension_declaration:: { ExtensionFunction , MappingType } ;
52+ use substrait:: proto:: extensions:: SimpleExtensionDeclaration ;
5153use substrait:: proto:: function_argument:: ArgType ;
5254use substrait:: proto:: join_rel:: JoinType ;
5355use substrait:: proto:: plan_rel:: RelType as PlanRelType ;
@@ -625,6 +627,9 @@ fn two(widths: &[Option<usize>]) -> Result<Option<(usize, usize)>> {
625627/// where Substrait reads every column, so each field after it would land
626628/// on the wrong column. Such a read gets a mask of the table's first
627629/// column, which nothing reads.
630+ /// - **DuckDB's unary minus.** DuckDB's producer writes `-x` as `subtract`
631+ /// with one argument, where Substrait's is `negate`. Such a call is
632+ /// pointed at a declaration of `negate`.
628633pub ( crate ) fn in_read_form ( plan : & Plan ) -> Cow < ' _ , Plan > {
629634 let duckdb = plan
630635 . version
@@ -635,7 +640,19 @@ pub(crate) fn in_read_form(plan: &Plan) -> Cow<'_, Plan> {
635640 RelType :: Read ( r) => duckdb && reads_no_columns ( r) ,
636641 _ => false ,
637642 } ;
638- if !PlanRels . then ( Deep ) . then ( RelKind ) . any ( plan, changes) {
643+ let subtracts: HashSet < u32 > = if duckdb {
644+ function_anchors ( plan, "subtract" ) . collect ( )
645+ } else {
646+ HashSet :: new ( )
647+ } ;
648+ let negation = |e : & Expression | match & e. rex_type {
649+ Some ( RexType :: ScalarFunction ( f) ) => {
650+ f. arguments . len ( ) == 1 && subtracts. contains ( & f. function_reference )
651+ }
652+ _ => false ,
653+ } ;
654+ let exprs = || PlanRels . then ( Deep ) . then ( RelKind ) . then ( Exprs ) . then ( Cosmos ) ;
655+ if !PlanRels . then ( Deep ) . then ( RelKind ) . any ( plan, changes) && !exprs ( ) . any ( plan, negation) {
639656 return Cow :: Borrowed ( plan) ;
640657 }
641658 let mut plan = plan. clone ( ) ;
@@ -659,9 +676,57 @@ pub(crate) fn in_read_form(plan: &Plan) -> Cow<'_, Plan> {
659676 }
660677 _ => { }
661678 } ) ;
679+ // After the windows are projections, whose expressions `Exprs` reaches.
680+ if exprs ( ) . any ( & plan, negation) {
681+ let negate = declare_function ( & mut plan, "negate" ) ;
682+ exprs ( ) . modify ( & mut plan, |e| {
683+ if negation ( e) {
684+ if let Some ( RexType :: ScalarFunction ( f) ) = & mut e. rex_type {
685+ f. function_reference = negate;
686+ }
687+ }
688+ } ) ;
689+ }
662690 Cow :: Owned ( plan)
663691}
664692
693+ /// The anchors of `plan`'s declarations of the function `name`, whatever
694+ /// their signatures.
695+ fn function_anchors < ' a > ( plan : & ' a Plan , name : & ' a str ) -> impl Iterator < Item = u32 > + ' a {
696+ plan. extensions
697+ . iter ( )
698+ . filter_map ( move |d| match & d. mapping_type {
699+ Some ( MappingType :: ExtensionFunction ( f) )
700+ if crate :: functions:: normalize ( & f. name ) == name =>
701+ {
702+ Some ( f. function_anchor )
703+ }
704+ _ => None ,
705+ } )
706+ }
707+
708+ /// A new declaration of the function `name` in `plan`, at the anchor after
709+ /// its last function's, with no extension URN, as DuckDB declares its own.
710+ fn declare_function ( plan : & mut Plan , name : & str ) -> u32 {
711+ let anchor = plan
712+ . extensions
713+ . iter ( )
714+ . filter_map ( |d| match & d. mapping_type {
715+ Some ( MappingType :: ExtensionFunction ( f) ) => Some ( f. function_anchor + 1 ) ,
716+ _ => None ,
717+ } )
718+ . max ( )
719+ . unwrap_or ( 0 ) ;
720+ plan. extensions . push ( SimpleExtensionDeclaration {
721+ mapping_type : Some ( MappingType :: ExtensionFunction ( ExtensionFunction {
722+ function_anchor : anchor,
723+ name : name. into ( ) ,
724+ ..Default :: default ( )
725+ } ) ) ,
726+ } ) ;
727+ anchor
728+ }
729+
665730/// Does DuckDB's producer mean `r` to read none of its table's columns: a
666731/// read with no mask, of a table that has some.
667732fn reads_no_columns ( r : & ReadRel ) -> bool {
@@ -2465,6 +2530,49 @@ mod tests {
24652530 assert_eq ! ( masks, [ Some ( first) , Some ( mask) ] ) ;
24662531 }
24672532
2533+ #[ test]
2534+ fn duckdb_s_one_argument_subtract_is_read_as_negate ( ) {
2535+ // DuckDB's `SELECT -v, v - v FROM t`: its unary minus is declared
2536+ // as a bare `subtract`, at its own anchor.
2537+ let declare = |anchor, name : & str | SimpleExtensionDeclaration {
2538+ mapping_type : Some ( MappingType :: ExtensionFunction ( ExtensionFunction {
2539+ function_anchor : anchor,
2540+ name : name. into ( ) ,
2541+ ..Default :: default ( )
2542+ } ) ) ,
2543+ } ;
2544+ let exprs = vec ! [
2545+ crate :: expr:: call( 1 , vec![ field( 0 ) ] ) ,
2546+ crate :: expr:: call( 3 , vec![ field( 0 ) , field( 0 ) ] ) ,
2547+ ] ;
2548+ let read = emit:: read_step ( "t" , vec ! [ "v" . into( ) ] ) ;
2549+ let functions = Functions :: from_plan ( & Plan :: default ( ) ) . unwrap ( ) ;
2550+ let ext = crate :: functions:: Extensions :: new ( & functions) ;
2551+ let mut plan = emit:: plan (
2552+ emit:: project_emit ( read, exprs, Some ( vec ! [ 1 , 2 ] ) ) ,
2553+ vec ! [ "n" . into( ) , "d" . into( ) ] ,
2554+ & ext,
2555+ ) ;
2556+ plan. extensions = vec ! [ declare( 1 , "subtract" ) , declare( 3 , "subtract:fp64_fp64" ) ] ;
2557+ assert ! ( matches!( in_read_form( & plan) , Cow :: Borrowed ( _) ) ) ;
2558+ plan. version = Some ( substrait:: version:: version_with_producer ( "DuckDB" ) ) ;
2559+ let read = in_read_form ( & plan) ;
2560+ let functions = Functions :: from_plan ( & read) . unwrap ( ) ;
2561+ let ( root, _) = root_of ( & read) . unwrap ( ) ;
2562+ let Some ( RelType :: Project ( p) ) = & root. rel_type else {
2563+ panic ! ( "{root:?}" )
2564+ } ;
2565+ let names: Vec < _ > = p
2566+ . expressions
2567+ . iter ( )
2568+ . map ( |e| match & e. rex_type {
2569+ Some ( RexType :: ScalarFunction ( f) ) => functions. name ( f. function_reference ) . unwrap ( ) ,
2570+ other => panic ! ( "{other:?}" ) ,
2571+ } )
2572+ . collect ( ) ;
2573+ assert_eq ! ( names, [ "negate" , "subtract" ] ) ;
2574+ }
2575+
24682576 #[ test]
24692577 fn a_namespace_separates_its_clock_from_its_counter ( ) {
24702578 // Without a separator, clock 0xabc1 with counter 2 and clock 0xabc
0 commit comments