Skip to main content

uqa_execution/statement/
cursor.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Single-query scheduling that seals a bounded result before committing its snapshot.
8
9use super::{
10    batch::context::{BatchExecutionContext, CachedStatement},
11    plan_executor::UnifiedPlanExecutor,
12    transactions::{
13        abort_explicit_statement_error, rollback_after_statement_error, rollback_implicit_statement,
14    },
15};
16use crate::query::{cursor::SQLCursor, locking::query_has_row_locks};
17use std::sync::Arc;
18use uqa_sql::semantics::effects::{query_may_mutate_engine, query_requires_statement_transaction};
19use uqa_sql::{plan::UnifiedPlan, SQLError, SQLParam};
20
21pub fn execute<S: Clone + Send + Sync + 'static>(
22    context: &BatchExecutionContext<'_, S>,
23    sql: &str,
24    params: &[SQLParam],
25) -> Result<SQLCursor, SQLError> {
26    let _statement_deadline = crate::statement::batch::context::statement_deadline(context);
27    if let Err(error) = context.runtime.cancellation.check() {
28        return Err(abort_explicit_statement_error(
29            context.transactions,
30            error.into(),
31        ));
32    }
33    let _statement_thread =
34        super::context::statement_thread_scope(context.statements, context.runtime.cancellation);
35    let cached = context.cache.cached_sql_statement(sql);
36    if !context.persistent_backend && context.transactions.transaction_depth() == 0 {
37        if let Some((plan, parser)) = cached.as_ref().and_then(|cached| {
38            cached
39                .optimized_plan
40                .as_ref()
41                .map(|plan| (plan, &cached.parser))
42        }) {
43            if !context.statements.notification_subscriptions_required()
44                || matches!(plan.as_ref(), UnifiedPlan::Query(_))
45            {
46                for notice in parser.notices.iter() {
47                    context.runtime.notices.push(notice.clone());
48                }
49                let executor = UnifiedPlanExecutor::new(
50                    context.statements.statement_execution_context(),
51                    params,
52                );
53                return execute_spilled(&executor, plan.as_ref());
54            }
55        }
56    }
57    execute_uncached_or_snapshot_scoped(context, sql, params, cached)
58}
59
60#[inline(never)]
61#[expect(
62    clippy::too_many_lines,
63    reason = "preserves cursor bounds and position"
64)]
65fn execute_uncached_or_snapshot_scoped<S: Clone + Send + Sync + 'static>(
66    context: &BatchExecutionContext<'_, S>,
67    sql: &str,
68    params: &[SQLParam],
69    cached: Option<CachedStatement>,
70) -> Result<SQLCursor, SQLError> {
71    let (statement, initial_plan, cached_optimized, parser) = if let Some(cached) = cached {
72        for notice in cached.parser.notices.iter() {
73            context.runtime.notices.push(notice.clone());
74        }
75        (
76            cached.statement.as_ref().clone(),
77            cached.logical_plan,
78            cached.optimized_plan,
79            cached.parser,
80        )
81    } else {
82        let (parsed, parser) =
83            uqa_sql::parser::with_settings(context.statements.parser_settings(), || {
84                uqa_sql::parse_statements(sql)
85            });
86        for notice in parser.notices.iter() {
87            context.runtime.notices.push(notice.clone());
88        }
89        let parsed =
90            parsed.map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
91        if context.statements.notification_subscriptions_required() {
92            for statement in &parsed {
93                context.runtime.cancellation.check().map_err(|error| {
94                    abort_explicit_statement_error(context.transactions, error.into())
95                })?;
96                if statement.is_notification_listener_command() {
97                    return Err(abort_explicit_statement_error(
98                        context.transactions,
99                        SQLError::NotificationRequiresSubscription,
100                    ));
101                }
102            }
103        }
104        let mut statements = parsed
105            .iter()
106            .map(uqa_sql::ParsedStatement::compile)
107            .collect::<Result<Vec<_>, _>>()
108            .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
109        if statements.len() != 1 {
110            return Err(abort_explicit_statement_error(
111                context.transactions,
112                single_query_error(statements.len()),
113            ));
114        }
115        let statement = statements.remove(0);
116        let plan = Arc::new(UnifiedPlan::lower_with(
117            statement.clone(),
118            context.aggregates,
119        ));
120        context.cache.cache_sql_statement(
121            sql.to_string(),
122            Arc::new(statement.clone()),
123            Arc::clone(&plan),
124            parser.clone(),
125        );
126        (statement, plan, None, parser)
127    };
128    if context.statements.notification_subscriptions_required()
129        && matches!(
130            statement,
131            uqa_sql::Statement::Listen { .. } | uqa_sql::Statement::Unlisten { .. }
132        )
133    {
134        return Err(abort_explicit_statement_error(
135            context.transactions,
136            SQLError::NotificationRequiresSubscription,
137        ));
138    }
139    let query = query_from_plan(initial_plan.as_ref())
140        .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
141    let has_row_locks = query_has_row_locks(query);
142    let _row_lock_statement = has_row_locks.then(|| context.row_locks.begin_row_lock_statement());
143
144    if context.transactions.transaction_depth() != 0 {
145        context.transactions.ensure_transaction_usable()?;
146        if has_row_locks {
147            context
148                .row_locks
149                .statement_row_lock_cache()
150                .map_err(|error| context.transactions.abort_after_error(error))?;
151        }
152        context
153            .transactions
154            .prepare_explicit_statement_snapshot(true)
155            .map_err(|error| context.transactions.abort_after_error(error))?;
156        let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
157        let current_query = query_from_plan(&plan)
158            .map_err(|error| context.transactions.abort_after_error(error))?;
159        context.cache.cache_sql_statement(
160            sql.to_string(),
161            Arc::new(statement.clone()),
162            Arc::new(plan.clone()),
163            parser.clone(),
164        );
165        if query_may_mutate_engine(&context.effects.query_effect_context(), current_query)
166            .map_err(|error| context.transactions.abort_after_error(error))?
167            && !has_row_locks
168            && context
169                .transactions
170                .prepare_explicit_transaction_writer()
171                .map_err(|error| context.transactions.abort_after_error(error))?
172        {
173            plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
174            query_from_plan(&plan)
175                .map_err(|error| context.transactions.abort_after_error(error))?;
176            context.cache.cache_sql_statement(
177                sql.to_string(),
178                Arc::new(statement.clone()),
179                Arc::new(plan.clone()),
180                parser.clone(),
181            );
182        }
183        let optimized = context
184            .planning
185            .plan_for_execution(plan, params)
186            .map_err(|error| context.transactions.abort_after_error(error))?;
187        let executor =
188            UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
189        return execute_spilled(&executor, &optimized)
190            .map_err(|error| context.transactions.abort_after_error(error));
191    }
192
193    let is_read_query = !query_may_mutate_engine(&context.effects.query_effect_context(), query)?;
194    let requires_statement_transaction = !is_read_query
195        || query_requires_statement_transaction(&context.effects.query_effect_context(), query)?;
196    let needs_transaction =
197        context.persistent_backend || requires_statement_transaction || has_row_locks;
198    if !needs_transaction {
199        let optimized = if let Some(plan) = cached_optimized {
200            plan
201        } else {
202            let (plan, reusable) = context
203                .planning
204                .plan_for_statement_cache(initial_plan.as_ref().clone(), params)?;
205            let plan = Arc::new(plan);
206            if reusable {
207                context
208                    .cache
209                    .cache_optimized_sql_plan(sql, Arc::clone(&plan));
210            }
211            plan
212        };
213        let executor =
214            UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
215        return execute_spilled(&executor, optimized.as_ref());
216    }
217
218    if has_row_locks {
219        context.row_locks.statement_row_lock_cache()?;
220    }
221    context
222        .transactions
223        .begin_implicit_statement_transaction(is_read_query)?;
224    if let Err(error) = context
225        .transactions
226        .prepare_explicit_statement_snapshot(true)
227    {
228        return rollback_after_statement_error(context.transactions, error);
229    }
230    let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
231    context.cache.cache_sql_statement(
232        sql.to_string(),
233        Arc::new(statement.clone()),
234        Arc::new(plan.clone()),
235        parser.clone(),
236    );
237    let must_restart_as_writer = if is_read_query && context.persistent_backend && !has_row_locks {
238        match query_from_plan(&plan).and_then(|query| {
239            query_may_mutate_engine(&context.effects.query_effect_context(), query)
240        }) {
241            Ok(mutates) => mutates,
242            Err(error) => return rollback_after_statement_error(context.transactions, error),
243        }
244    } else {
245        false
246    };
247    if must_restart_as_writer {
248        rollback_implicit_statement(
249            context.transactions,
250            "restart cursor read transaction as writer",
251        )?;
252        context
253            .transactions
254            .begin_implicit_statement_transaction(false)?;
255        if let Err(error) = context
256            .transactions
257            .prepare_explicit_statement_snapshot(true)
258        {
259            return rollback_after_statement_error(context.transactions, error);
260        }
261        plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
262        if let Err(error) = query_from_plan(&plan) {
263            return rollback_after_statement_error(context.transactions, error);
264        }
265        context.cache.cache_sql_statement(
266            sql.to_string(),
267            Arc::new(statement.clone()),
268            Arc::new(plan.clone()),
269            parser.clone(),
270        );
271    }
272    let mutating_query = match query_from_plan(&plan)
273        .and_then(|query| query_may_mutate_engine(&context.effects.query_effect_context(), query))
274    {
275        Ok(mutates) => mutates,
276        Err(error) => return rollback_after_statement_error(context.transactions, error),
277    };
278    if mutating_query && context.persistent_backend && !has_row_locks {
279        match context.transactions.prepare_explicit_transaction_writer() {
280            Ok(true) => {
281                plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
282                if let Err(error) = query_from_plan(&plan) {
283                    return rollback_after_statement_error(context.transactions, error);
284                }
285                context.cache.cache_sql_statement(
286                    sql.to_string(),
287                    Arc::new(statement.clone()),
288                    Arc::new(plan.clone()),
289                    parser.clone(),
290                );
291            }
292            Ok(false) => {}
293            Err(error) => return rollback_after_statement_error(context.transactions, error),
294        }
295    }
296    let optimized = match context.planning.plan_for_execution(plan, params) {
297        Ok(plan) => plan,
298        Err(error) => return rollback_after_statement_error(context.transactions, error),
299    };
300    let executor =
301        UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
302    let cursor = match execute_spilled(&executor, &optimized) {
303        Ok(cursor) => cursor,
304        Err(error) => return rollback_after_statement_error(context.transactions, error),
305    };
306    context
307        .transactions
308        .run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit)?;
309    Ok(cursor)
310}
311
312fn execute_spilled<S: Clone + Send + Sync + 'static>(
313    executor: &UnifiedPlanExecutor<'_, '_, S>,
314    plan: &UnifiedPlan,
315) -> Result<SQLCursor, SQLError> {
316    executor.execute_query_to_spill(plan)?.into_cursor()
317}
318
319fn query_from_plan(plan: &UnifiedPlan) -> Result<&uqa_sql::plan::QueryPlan, SQLError> {
320    let UnifiedPlan::Query(query) = plan else {
321        return Err(single_query_error(1));
322    };
323    Ok(query)
324}
325
326fn single_query_error(statement_count: usize) -> SQLError {
327    SQLError::Unsupported(format!(
328        "SQL cursor accepts exactly one query statement, received {statement_count}"
329    ))
330}