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    execute_with_context(context, sql, params, false)
27}
28
29pub fn execute_nested<S: Clone + Send + Sync + 'static>(
30    context: &BatchExecutionContext<'_, S>,
31    sql: &str,
32    params: &[SQLParam],
33) -> Result<SQLCursor, SQLError> {
34    execute_with_context(context, sql, params, true)
35}
36
37fn execute_with_context<S: Clone + Send + Sync + 'static>(
38    context: &BatchExecutionContext<'_, S>,
39    sql: &str,
40    params: &[SQLParam],
41    nested_statement: bool,
42) -> Result<SQLCursor, SQLError> {
43    let _statement_deadline = (!nested_statement)
44        .then(|| crate::statement::batch::context::statement_deadline(context))
45        .flatten();
46    if let Err(error) = context.runtime.cancellation.check() {
47        return Err(abort_explicit_statement_error(
48            context.transactions,
49            error.into(),
50        ));
51    }
52    context.transactions.refresh_idle_statement_view()?;
53    let _statement_thread =
54        super::context::statement_thread_scope(context.statements, context.runtime.cancellation);
55    let cached = context.cache.cached_sql_statement(sql);
56    if !nested_statement
57        && !context.persistent_backend
58        && context.transactions.transaction_depth() == 0
59    {
60        if let Some((plan, parser)) = cached.as_ref().and_then(|cached| {
61            cached
62                .optimized_plan_for(params)
63                .map(|plan| (plan, &cached.parser))
64        }) {
65            if !context.statements.notification_subscriptions_required()
66                || matches!(plan.as_ref(), UnifiedPlan::Query(_))
67            {
68                for notice in parser.notices.iter() {
69                    context.runtime.notices.push(notice.clone());
70                }
71                let executor = UnifiedPlanExecutor::with_nested_statement(
72                    context.statements.statement_execution_context(),
73                    params,
74                    nested_statement,
75                );
76                return execute_spilled(&executor, plan.as_ref());
77            }
78        }
79    }
80    execute_uncached_or_snapshot_scoped(context, sql, params, cached, nested_statement)
81}
82
83#[inline(never)]
84#[expect(
85    clippy::too_many_lines,
86    reason = "preserves cursor bounds and position"
87)]
88fn execute_uncached_or_snapshot_scoped<S: Clone + Send + Sync + 'static>(
89    context: &BatchExecutionContext<'_, S>,
90    sql: &str,
91    params: &[SQLParam],
92    cached: Option<CachedStatement>,
93    nested_statement: bool,
94) -> Result<SQLCursor, SQLError> {
95    let planning_owner = context
96        .planning
97        .planning_control()
98        .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
99    let control = planning_owner.control();
100    let (statement, initial_plan, cached_optimized, parser) = if let Some(cached) = cached {
101        for notice in cached.parser.notices.iter() {
102            context.runtime.notices.push(notice.clone());
103        }
104        let optimized = if nested_statement {
105            None
106        } else {
107            cached.optimized_plan_for(params).cloned()
108        };
109        let plan = match cached.logical_plan {
110            Some(plan) => plan,
111            None => super::batch::analysis::lower(&cached.statement, context.aggregates, &control)
112                .map_err(|error| abort_explicit_statement_error(context.transactions, error))?,
113        };
114        (cached.statement, plan, optimized, cached.parser)
115    } else {
116        let (parsed, parser) =
117            uqa_sql::parser::with_settings(context.statements.parser_settings(), || {
118                uqa_sql::parse_statements(sql)
119            });
120        for notice in parser.notices.iter() {
121            context.runtime.notices.push(notice.clone());
122        }
123        let parsed =
124            parsed.map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
125        if context.statements.notification_subscriptions_required() {
126            for statement in &parsed {
127                context.runtime.cancellation.check().map_err(|error| {
128                    abort_explicit_statement_error(context.transactions, error.into())
129                })?;
130                if statement.is_notification_listener_command() {
131                    return Err(abort_explicit_statement_error(
132                        context.transactions,
133                        SQLError::NotificationRequiresSubscription,
134                    ));
135                }
136            }
137        }
138        let mut statements = parsed
139            .iter()
140            .map(uqa_sql::ParsedStatement::compile)
141            .collect::<Result<Vec<_>, _>>()
142            .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
143        if statements.len() != 1 {
144            return Err(abort_explicit_statement_error(
145                context.transactions,
146                single_query_error(statements.len()),
147            ));
148        }
149        let statement = Arc::new(statements.remove(0));
150        let plan = super::batch::analysis::lower(&statement, context.aggregates, &control)
151            .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
152        context
153            .cache
154            .cache_sql_statement(sql, statement.clone(), None, parser.clone(), &control)
155            .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
156        (statement, plan, None, parser)
157    };
158    if context.statements.notification_subscriptions_required()
159        && matches!(
160            statement.as_ref(),
161            uqa_sql::Statement::Listen { .. } | uqa_sql::Statement::Unlisten { .. }
162        )
163    {
164        return Err(abort_explicit_statement_error(
165            context.transactions,
166            SQLError::NotificationRequiresSubscription,
167        ));
168    }
169    let query = query_from_plan(initial_plan.as_ref())
170        .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
171    let has_row_locks = query_has_row_locks(query);
172    let _row_lock_statement = has_row_locks.then(|| context.row_locks.begin_row_lock_statement());
173
174    if context.transactions.transaction_depth() != 0 {
175        drop(initial_plan);
176        return super::batch::context::with_active_transaction(context.transactions, || {
177            if has_row_locks {
178                context.row_locks.statement_row_lock_cache()?;
179            }
180            context
181                .transactions
182                .prepare_explicit_statement_snapshot(true)?;
183            let mut plan = super::batch::analysis::lower(&statement, context.aggregates, &control)?;
184            let current_query = query_from_plan(&plan)?;
185            context.cache.cache_sql_statement(
186                sql,
187                statement.clone(),
188                Some(plan.clone()),
189                parser.clone(),
190                &control,
191            )?;
192            if query_may_mutate_engine(&context.effects.query_effect_context(), current_query)?
193                && !has_row_locks
194                && context.transactions.prepare_explicit_transaction_writer()?
195            {
196                drop(plan);
197                plan = super::batch::analysis::lower(&statement, context.aggregates, &control)?;
198                query_from_plan(&plan)?;
199                context.cache.cache_sql_statement(
200                    sql,
201                    statement.clone(),
202                    Some(plan.clone()),
203                    parser.clone(),
204                    &control,
205                )?;
206            }
207            let optimized = super::batch::analysis::plan(
208                context,
209                sql,
210                plan,
211                params,
212                !nested_statement,
213                false,
214                &control,
215            )?;
216            let executor = UnifiedPlanExecutor::with_nested_statement(
217                context.statements.statement_execution_context(),
218                params,
219                nested_statement,
220            );
221            execute_spilled(&executor, &optimized)
222        });
223    }
224
225    let is_read_query = !query_may_mutate_engine(&context.effects.query_effect_context(), query)?;
226    let requires_statement_transaction = !is_read_query
227        || query_requires_statement_transaction(&context.effects.query_effect_context(), query)?;
228    let needs_transaction =
229        context.persistent_backend || requires_statement_transaction || has_row_locks;
230    if !needs_transaction {
231        let optimized = if let Some(plan) = cached_optimized {
232            plan
233        } else {
234            context.cache.retire_sql_logical_plan(sql, &control)?;
235            let plan = initial_plan.copy_for_rewrite(&control)?;
236            drop(initial_plan);
237            let (plan, reusable) = context
238                .planning
239                .plan_owned_for_statement_cache(plan, params, &control)?;
240
241            if reusable && !nested_statement {
242                context
243                    .cache
244                    .cache_optimized_sql_plan(sql, plan.clone(), &control)?;
245            }
246            plan
247        };
248        let executor = UnifiedPlanExecutor::with_nested_statement(
249            context.statements.statement_execution_context(),
250            params,
251            nested_statement,
252        );
253        return execute_spilled(&executor, optimized.as_ref());
254    }
255
256    drop(initial_plan);
257    if has_row_locks {
258        context.row_locks.statement_row_lock_cache()?;
259    }
260    context
261        .transactions
262        .begin_implicit_statement_transaction(is_read_query)?;
263    if let Err(error) = context
264        .transactions
265        .prepare_explicit_statement_snapshot(true)
266    {
267        return rollback_after_statement_error(context.transactions, error);
268    }
269    let mut plan = super::batch::analysis::lower(&statement, context.aggregates, &control)
270        .or_else(|error| rollback_after_statement_error(context.transactions, error))?;
271    context
272        .cache
273        .cache_sql_statement(
274            sql,
275            statement.clone(),
276            Some(plan.clone()),
277            parser.clone(),
278            &control,
279        )
280        .or_else(|error| rollback_after_statement_error(context.transactions, error))?;
281    let must_restart_as_writer = if is_read_query && context.persistent_backend && !has_row_locks {
282        match query_from_plan(&plan).and_then(|query| {
283            query_may_mutate_engine(&context.effects.query_effect_context(), query)
284        }) {
285            Ok(mutates) => mutates,
286            Err(error) => return rollback_after_statement_error(context.transactions, error),
287        }
288    } else {
289        false
290    };
291    if must_restart_as_writer {
292        rollback_implicit_statement(
293            context.transactions,
294            "restart cursor read transaction as writer",
295        )?;
296        context
297            .transactions
298            .begin_implicit_statement_transaction(false)?;
299        if let Err(error) = context
300            .transactions
301            .prepare_explicit_statement_snapshot(true)
302        {
303            return rollback_after_statement_error(context.transactions, error);
304        }
305        drop(plan);
306        plan = super::batch::analysis::lower(&statement, context.aggregates, &control)
307            .or_else(|error| rollback_after_statement_error(context.transactions, error))?;
308        if let Err(error) = query_from_plan(&plan) {
309            return rollback_after_statement_error(context.transactions, error);
310        }
311        context
312            .cache
313            .cache_sql_statement(
314                sql,
315                statement.clone(),
316                Some(plan.clone()),
317                parser.clone(),
318                &control,
319            )
320            .or_else(|error| rollback_after_statement_error(context.transactions, error))?;
321    }
322    let mutating_query = match query_from_plan(&plan)
323        .and_then(|query| query_may_mutate_engine(&context.effects.query_effect_context(), query))
324    {
325        Ok(mutates) => mutates,
326        Err(error) => return rollback_after_statement_error(context.transactions, error),
327    };
328    if mutating_query && context.persistent_backend && !has_row_locks {
329        match context.transactions.prepare_explicit_transaction_writer() {
330            Ok(true) => {
331                drop(plan);
332                plan = super::batch::analysis::lower(&statement, context.aggregates, &control)
333                    .or_else(|error| rollback_after_statement_error(context.transactions, error))?;
334                if let Err(error) = query_from_plan(&plan) {
335                    return rollback_after_statement_error(context.transactions, error);
336                }
337                context
338                    .cache
339                    .cache_sql_statement(
340                        sql,
341                        statement.clone(),
342                        Some(plan.clone()),
343                        parser.clone(),
344                        &control,
345                    )
346                    .or_else(|error| rollback_after_statement_error(context.transactions, error))?;
347            }
348            Ok(false) => {}
349            Err(error) => return rollback_after_statement_error(context.transactions, error),
350        }
351    }
352    let optimized = match super::batch::analysis::plan(
353        context,
354        sql,
355        plan,
356        params,
357        !nested_statement,
358        false,
359        &control,
360    ) {
361        Ok(plan) => plan,
362        Err(error) => return rollback_after_statement_error(context.transactions, error),
363    };
364    let executor = UnifiedPlanExecutor::with_nested_statement(
365        context.statements.statement_execution_context(),
366        params,
367        nested_statement,
368    );
369    let cursor = match execute_spilled(&executor, &optimized) {
370        Ok(cursor) => cursor,
371        Err(error) => return rollback_after_statement_error(context.transactions, error),
372    };
373    context
374        .transactions
375        .run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit)?;
376    Ok(cursor)
377}
378
379fn execute_spilled<S: Clone + Send + Sync + 'static>(
380    executor: &UnifiedPlanExecutor<'_, '_, S>,
381    plan: &UnifiedPlan,
382) -> Result<SQLCursor, SQLError> {
383    executor.execute_query_to_spill(plan)?.into_cursor()
384}
385
386fn query_from_plan(plan: &UnifiedPlan) -> Result<&uqa_sql::plan::QueryPlan, SQLError> {
387    let UnifiedPlan::Query(query) = plan else {
388        return Err(single_query_error(1));
389    };
390    Ok(query)
391}
392
393fn single_query_error(statement_count: usize) -> SQLError {
394    SQLError::Unsupported(format!(
395        "SQL cursor accepts exactly one query statement, received {statement_count}"
396    ))
397}