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_for(params)
40                .map(|plan| (plan, &cached.parser))
41        }) {
42            if !context.statements.notification_subscriptions_required()
43                || matches!(plan.as_ref(), UnifiedPlan::Query(_))
44            {
45                for notice in parser.notices.iter() {
46                    context.runtime.notices.push(notice.clone());
47                }
48                let executor = UnifiedPlanExecutor::new(
49                    context.statements.statement_execution_context(),
50                    params,
51                );
52                return execute_spilled(&executor, plan.as_ref());
53            }
54        }
55    }
56    execute_uncached_or_snapshot_scoped(context, sql, params, cached)
57}
58
59#[inline(never)]
60#[expect(
61    clippy::too_many_lines,
62    reason = "preserves cursor bounds and position"
63)]
64fn execute_uncached_or_snapshot_scoped<S: Clone + Send + Sync + 'static>(
65    context: &BatchExecutionContext<'_, S>,
66    sql: &str,
67    params: &[SQLParam],
68    cached: Option<CachedStatement>,
69) -> Result<SQLCursor, SQLError> {
70    let (statement, initial_plan, cached_optimized, parser) = if let Some(cached) = cached {
71        for notice in cached.parser.notices.iter() {
72            context.runtime.notices.push(notice.clone());
73        }
74        let optimized = cached.optimized_plan_for(params).cloned();
75        (
76            cached.statement.as_ref().clone(),
77            cached.logical_plan,
78            optimized,
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        return super::batch::context::with_active_transaction(context.transactions, || {
146            if has_row_locks {
147                context.row_locks.statement_row_lock_cache()?;
148            }
149            context
150                .transactions
151                .prepare_explicit_statement_snapshot(true)?;
152            let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
153            let current_query = query_from_plan(&plan)?;
154            context.cache.cache_sql_statement(
155                sql.to_string(),
156                Arc::new(statement.clone()),
157                Arc::new(plan.clone()),
158                parser.clone(),
159            );
160            if query_may_mutate_engine(&context.effects.query_effect_context(), current_query)?
161                && !has_row_locks
162                && context.transactions.prepare_explicit_transaction_writer()?
163            {
164                plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
165                query_from_plan(&plan)?;
166                context.cache.cache_sql_statement(
167                    sql.to_string(),
168                    Arc::new(statement.clone()),
169                    Arc::new(plan.clone()),
170                    parser.clone(),
171                );
172            }
173            let optimized = context.planning.plan_for_execution(plan, params)?;
174            let executor =
175                UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
176            execute_spilled(&executor, &optimized)
177        });
178    }
179
180    let is_read_query = !query_may_mutate_engine(&context.effects.query_effect_context(), query)?;
181    let requires_statement_transaction = !is_read_query
182        || query_requires_statement_transaction(&context.effects.query_effect_context(), query)?;
183    let needs_transaction =
184        context.persistent_backend || requires_statement_transaction || has_row_locks;
185    if !needs_transaction {
186        let optimized = if let Some(plan) = cached_optimized {
187            plan
188        } else {
189            let (plan, reusable) = context
190                .planning
191                .plan_for_statement_cache(initial_plan.as_ref().clone(), params)?;
192            let plan = Arc::new(plan);
193            if reusable {
194                context
195                    .cache
196                    .cache_optimized_sql_plan(sql, Arc::clone(&plan));
197            }
198            plan
199        };
200        let executor =
201            UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
202        return execute_spilled(&executor, optimized.as_ref());
203    }
204
205    if has_row_locks {
206        context.row_locks.statement_row_lock_cache()?;
207    }
208    context
209        .transactions
210        .begin_implicit_statement_transaction(is_read_query)?;
211    if let Err(error) = context
212        .transactions
213        .prepare_explicit_statement_snapshot(true)
214    {
215        return rollback_after_statement_error(context.transactions, error);
216    }
217    let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
218    context.cache.cache_sql_statement(
219        sql.to_string(),
220        Arc::new(statement.clone()),
221        Arc::new(plan.clone()),
222        parser.clone(),
223    );
224    let must_restart_as_writer = if is_read_query && context.persistent_backend && !has_row_locks {
225        match query_from_plan(&plan).and_then(|query| {
226            query_may_mutate_engine(&context.effects.query_effect_context(), query)
227        }) {
228            Ok(mutates) => mutates,
229            Err(error) => return rollback_after_statement_error(context.transactions, error),
230        }
231    } else {
232        false
233    };
234    if must_restart_as_writer {
235        rollback_implicit_statement(
236            context.transactions,
237            "restart cursor read transaction as writer",
238        )?;
239        context
240            .transactions
241            .begin_implicit_statement_transaction(false)?;
242        if let Err(error) = context
243            .transactions
244            .prepare_explicit_statement_snapshot(true)
245        {
246            return rollback_after_statement_error(context.transactions, error);
247        }
248        plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
249        if let Err(error) = query_from_plan(&plan) {
250            return rollback_after_statement_error(context.transactions, error);
251        }
252        context.cache.cache_sql_statement(
253            sql.to_string(),
254            Arc::new(statement.clone()),
255            Arc::new(plan.clone()),
256            parser.clone(),
257        );
258    }
259    let mutating_query = match query_from_plan(&plan)
260        .and_then(|query| query_may_mutate_engine(&context.effects.query_effect_context(), query))
261    {
262        Ok(mutates) => mutates,
263        Err(error) => return rollback_after_statement_error(context.transactions, error),
264    };
265    if mutating_query && context.persistent_backend && !has_row_locks {
266        match context.transactions.prepare_explicit_transaction_writer() {
267            Ok(true) => {
268                plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
269                if let Err(error) = query_from_plan(&plan) {
270                    return rollback_after_statement_error(context.transactions, error);
271                }
272                context.cache.cache_sql_statement(
273                    sql.to_string(),
274                    Arc::new(statement.clone()),
275                    Arc::new(plan.clone()),
276                    parser.clone(),
277                );
278            }
279            Ok(false) => {}
280            Err(error) => return rollback_after_statement_error(context.transactions, error),
281        }
282    }
283    let optimized = match context.planning.plan_for_execution(plan, params) {
284        Ok(plan) => plan,
285        Err(error) => return rollback_after_statement_error(context.transactions, error),
286    };
287    let executor =
288        UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
289    let cursor = match execute_spilled(&executor, &optimized) {
290        Ok(cursor) => cursor,
291        Err(error) => return rollback_after_statement_error(context.transactions, error),
292    };
293    context
294        .transactions
295        .run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit)?;
296    Ok(cursor)
297}
298
299fn execute_spilled<S: Clone + Send + Sync + 'static>(
300    executor: &UnifiedPlanExecutor<'_, '_, S>,
301    plan: &UnifiedPlan,
302) -> Result<SQLCursor, SQLError> {
303    executor.execute_query_to_spill(plan)?.into_cursor()
304}
305
306fn query_from_plan(plan: &UnifiedPlan) -> Result<&uqa_sql::plan::QueryPlan, SQLError> {
307    let UnifiedPlan::Query(query) = plan else {
308        return Err(single_query_error(1));
309    };
310    Ok(query)
311}
312
313fn single_query_error(statement_count: usize) -> SQLError {
314    SQLError::Unsupported(format!(
315        "SQL cursor accepts exactly one query statement, received {statement_count}"
316    ))
317}