Skip to main content

uqa_execution/query/statement/
consumer.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bind output sinks to an opaque read generation before physical row delivery.
8use crate::query::consumer as physical;
9pub use physical::QueryConsumerControl;
10use std::{cell::Cell, rc::Rc};
11use uqa_core::Value;
12use uqa_sql::{type_resolution::coerce_common_context_value, SQLError};
13
14/// A row sink chooses its own services for the selected generation; query execution supplies no writable context.
15pub trait QueryConsumerFactory<'consumer, S: Clone + 'static> {
16    fn bind(
17        self: Rc<Self>,
18        generation: Option<&S>,
19    ) -> Result<Rc<dyn physical::QueryRowConsumer + 'consumer>, SQLError>;
20    fn uses_directional_scan(&self) -> bool {
21        false
22    }
23    fn streams_set_inputs(&self) -> bool {
24        true
25    }
26}
27
28pub(crate) struct SetOperationConsumerFactory<'consumer, S: Clone + 'static> {
29    downstream: Rc<dyn QueryConsumerFactory<'consumer, S> + 'consumer>,
30    state: Rc<SetOperationState>,
31}
32struct SetOperationState {
33    columns: Vec<String>,
34    schema: crate::RowSchema,
35    offset: Cell<u64>,
36    remaining: Cell<Option<u64>>,
37    begun: Cell<bool>,
38    stopped: Cell<bool>,
39}
40impl<'consumer, S: Clone + 'static> SetOperationConsumerFactory<'consumer, S> {
41    pub(crate) fn new(
42        downstream: Rc<dyn QueryConsumerFactory<'consumer, S> + 'consumer>,
43        schema: crate::RowSchema,
44        offset: u64,
45        limit: Option<u64>,
46    ) -> Self {
47        Self {
48            downstream,
49            state: Rc::new(SetOperationState {
50                columns: schema.columns().to_vec(),
51                schema,
52                offset: Cell::new(offset),
53                remaining: Cell::new(limit),
54                begun: Cell::new(false),
55                stopped: Cell::new(limit == Some(0)),
56            }),
57        }
58    }
59    pub(crate) fn stopped(&self) -> bool {
60        self.state.stopped.get()
61    }
62}
63impl<'consumer, S: Clone + 'static> QueryConsumerFactory<'consumer, S>
64    for SetOperationConsumerFactory<'consumer, S>
65{
66    fn bind(
67        self: Rc<Self>,
68        generation: Option<&S>,
69    ) -> Result<Rc<dyn physical::QueryRowConsumer + 'consumer>, SQLError> {
70        Ok(Rc::new(SetOperationRowConsumer {
71            downstream: Rc::clone(&self.downstream).bind(generation)?,
72            state: Rc::clone(&self.state),
73        }))
74    }
75}
76struct SetOperationRowConsumer<'consumer> {
77    downstream: Rc<dyn physical::QueryRowConsumer + 'consumer>,
78    state: Rc<SetOperationState>,
79}
80impl SetOperationRowConsumer<'_> {
81    fn stopped(&self) -> bool {
82        self.state.stopped.get()
83    }
84}
85impl physical::QueryRowConsumer for SetOperationRowConsumer<'_> {
86    fn begin(&self, columns: &[String], _schema: &crate::RowSchema) -> Result<(), SQLError> {
87        if columns.len() != self.state.columns.len() {
88            return Err(SQLError::TypeMismatch(format!(
89                "set-operation input width {} does not match output width {}",
90                columns.len(),
91                self.state.columns.len()
92            )));
93        }
94        if self.state.begun.replace(true) {
95            Ok(())
96        } else {
97            self.downstream
98                .begin(&self.state.columns, &self.state.schema)
99        }
100    }
101
102    fn consume(&self, row: crate::OwnedPhysicalRow) -> Result<QueryConsumerControl, SQLError> {
103        if self.stopped() {
104            return Ok(QueryConsumerControl::Stop);
105        }
106        if self.state.offset.get() > 0 {
107            self.state.offset.set(self.state.offset.get() - 1);
108            return Ok(QueryConsumerControl::Continue);
109        }
110        if self.state.remaining.get() == Some(0) {
111            self.state.stopped.set(true);
112            return Ok(QueryConsumerControl::Stop);
113        }
114        let projections = {
115            let view = row.view();
116            self.state
117                .schema
118                .column_types()
119                .iter()
120                .enumerate()
121                .map(|(position, target_type)| {
122                    let source_type = row.schema.column_type(position);
123                    if target_type
124                        .as_ref()
125                        .is_some_and(|target_type| source_type != Some(target_type))
126                    {
127                        let value = view.value_at(position).cloned().unwrap_or(Value::Null);
128                        return coerce_common_context_value(
129                            value,
130                            source_type,
131                            target_type.as_ref(),
132                        )
133                        .map(crate::RowProjectionValue::Owned);
134                    }
135                    Ok(row.schema.physical_slot(position).map_or(
136                        crate::RowProjectionValue::Owned(Value::Null),
137                        crate::RowProjectionValue::InputSlot,
138                    ))
139                })
140                .collect::<Result<Vec<_>, SQLError>>()?
141        };
142        let control = self.downstream.consume(crate::OwnedPhysicalRow::new(
143            self.state.schema.clone(),
144            row.row
145                .project_with_values(projections)
146                .without_lock_origins(),
147        ))?;
148        match control {
149            QueryConsumerControl::Continue => {}
150            QueryConsumerControl::Stop => {
151                self.state.stopped.set(true);
152                return Ok(control);
153            }
154            QueryConsumerControl::Rewind => {
155                return Err(SQLError::Internal(
156                    "set-operation consumer received a directional rewind".into(),
157                ));
158            }
159        }
160        if let Some(remaining) = self.state.remaining.get() {
161            let remaining = remaining - 1;
162            self.state.remaining.set(Some(remaining));
163            if remaining == 0 {
164                self.state.stopped.set(true);
165                return Ok(QueryConsumerControl::Stop);
166            }
167        }
168        Ok(QueryConsumerControl::Continue)
169    }
170}
171
172#[derive(Clone)]
173pub enum QueryOutputMode<'consumer, S: Clone + 'static> {
174    Rows,
175    SharedSpill,
176    ExistsKeySet,
177    RowConsumer(Rc<dyn QueryConsumerFactory<'consumer, S> + 'consumer>),
178}
179impl<'consumer, S: Clone + 'static> QueryOutputMode<'consumer, S> {
180    pub fn physical_consumer(consumer: Rc<dyn physical::QueryRowConsumer + 'consumer>) -> Self {
181        Self::RowConsumer(Rc::new(PhysicalConsumer(consumer)))
182    }
183}
184struct PhysicalConsumer<'consumer>(Rc<dyn physical::QueryRowConsumer + 'consumer>);
185impl<'consumer, S: Clone + 'static> QueryConsumerFactory<'consumer, S>
186    for PhysicalConsumer<'consumer>
187{
188    fn bind(
189        self: Rc<Self>,
190        _generation: Option<&S>,
191    ) -> Result<Rc<dyn physical::QueryRowConsumer + 'consumer>, SQLError> {
192        Ok(Rc::clone(&self.0))
193    }
194    fn uses_directional_scan(&self) -> bool {
195        self.0.uses_directional_scan()
196    }
197    fn streams_set_inputs(&self) -> bool {
198        self.0.streams_set_inputs()
199    }
200}