Skip to main content

uqa_engine/capabilities/
insert_consumers.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Retain the session generation selected for an INSERT SELECT sink.
8use crate::{session::StatementReadSnapshot, Engine};
9use std::rc::Rc;
10use uqa_execution::{
11    mutation::insert::source::{
12        binding::InsertSelectBinding, InsertSelectConsumer, InsertSourceContext,
13    },
14    query::consumer::{QueryConsumerControl, QueryRowConsumer},
15    OwnedPhysicalRow, RowSchema,
16};
17use uqa_sql::SQLError;
18
19enum SourceSession<'a> {
20    Live(&'a Engine),
21    Snapshot(Box<Engine>),
22}
23impl SourceSession<'_> {
24    fn engine(&self) -> &Engine {
25        match self {
26            Self::Live(engine) => engine,
27            Self::Snapshot(engine) => engine,
28        }
29    }
30    fn source_context(&self) -> InsertSourceContext<'_, StatementReadSnapshot> {
31        let engine = self.engine();
32        InsertSourceContext {
33            rows: engine.mutation_preparation_context(),
34            identities: engine.insert_identity_context(),
35            runtime: engine.query_runtime_view(),
36        }
37    }
38}
39struct BoundInsertConsumer<'a> {
40    session: SourceSession<'a>,
41    destination: Option<uqa_execution::mutation::returning::ReturningDestination<'a>>,
42    consumer: Rc<InsertSelectConsumer<StatementReadSnapshot>>,
43}
44impl QueryRowConsumer for BoundInsertConsumer<'_> {
45    fn begin(&self, columns: &[String], schema: &RowSchema) -> Result<(), SQLError> {
46        self.consumer
47            .begin(self.session.source_context(), columns, schema)
48    }
49    fn consume(&self, row: OwnedPhysicalRow) -> Result<QueryConsumerControl, SQLError> {
50        self.consumer
51            .consume(self.session.source_context(), row, self.destination)
52    }
53}
54impl InsertSelectBinding<StatementReadSnapshot> for Engine {
55    fn bind<'a>(
56        &'a self,
57        snapshot: Option<&StatementReadSnapshot>,
58        consumer: Rc<InsertSelectConsumer<StatementReadSnapshot>>,
59        destination: Option<uqa_execution::mutation::returning::ReturningDestination<'a>>,
60    ) -> Result<Rc<dyn QueryRowConsumer + 'a>, SQLError> {
61        let session = match snapshot {
62            Some(snapshot) => {
63                SourceSession::Snapshot(Box::new(self.statement_read_snapshot_engine(snapshot)))
64            }
65            None => SourceSession::Live(self),
66        };
67        Ok(Rc::new(BoundInsertConsumer {
68            session,
69            destination,
70            consumer,
71        }))
72    }
73}