Skip to main content

uqa_sql/semantics/effects/
read_only.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL commands forbidden by read-only transactions and snapshot-setting rules.
8
9use super::{command_payload_may_write_database, query_may_write_database, QueryEffectContext};
10use crate::{
11    ast::RelationPersistence,
12    plan::{CommandPlan, UnifiedPlan},
13    result::completion::command_tag_name,
14    SQLError,
15};
16
17pub fn read_only_error(command: &str) -> SQLError {
18    SQLError::Routine {
19        sqlstate: "25006".into(),
20        message: format!("cannot execute {command} in a read-only transaction"),
21    }
22}
23
24fn table_is_temporary(
25    context: &QueryEffectContext<'_>,
26    table: &str,
27) -> Result<Option<bool>, SQLError> {
28    context
29        .catalog
30        .table_persistence(table)
31        .map(|persistence| persistence.map(|value| value == RelationPersistence::Temporary))
32        .map_err(|error| SQLError::Internal(format!("resolve read-only target `{table}`: {error}")))
33}
34
35fn dml_command(
36    context: &QueryEffectContext<'_>,
37    table: &str,
38    command: &CommandPlan,
39) -> Result<Option<&'static str>, SQLError> {
40    match table_is_temporary(context, table)? {
41        Some(false) => Ok(Some(command_tag_name(command))),
42        Some(true) if command_payload_may_write_database(context, command)? => {
43            Ok(Some(command_tag_name(command)))
44        }
45        Some(true) | None => Ok(None),
46    }
47}
48
49/// The tag of a command a read-only transaction rejects, or `None` when the command may run: `ClassifyUtilityCommandAsReadOnly` rejects every utility command that changes persistent state, and `ExecCheckXactReadOnly` rejects a query that writes to a permanent relation.
50pub fn forbidden_command(
51    context: &QueryEffectContext<'_>,
52    plan: &UnifiedPlan,
53) -> Result<Option<&'static str>, SQLError> {
54    let UnifiedPlan::Command(command) = plan else {
55        let UnifiedPlan::Query(query) = plan else {
56            unreachable!();
57        };
58        return query_may_write_database(context, query).map(|mutates| mutates.then_some("SELECT"));
59    };
60    let command = command.as_ref();
61    match command {
62        CommandPlan::Insert(insert) => dml_command(context, &insert.table, command),
63        CommandPlan::Update(update) => dml_command(context, &update.table, command),
64        CommandPlan::Delete(delete) => dml_command(context, &delete.table, command),
65        CommandPlan::Merge(merge) => dml_command(context, &merge.target, command),
66        CommandPlan::DeclareCursor { query, .. } => {
67            query_may_write_database(context, query).map(|mutates| mutates.then_some("SELECT"))
68        }
69        CommandPlan::Execute { name, .. } => context
70            .catalog
71            .lookup_prepared(name)
72            .map_or(Ok(None), |prepared| forbidden_command(context, &prepared)),
73        // VACUUM's transaction-block prohibition has precedence over read-only validation and is enforced by its executor.
74        CommandPlan::Empty
75        | CommandPlan::Analyze { .. }
76        | CommandPlan::LockTable(_)
77        | CommandPlan::Vacuum(_)
78        | CommandPlan::SetVariable { .. }
79        | CommandPlan::Notify { .. }
80        | CommandPlan::Listen { .. }
81        | CommandPlan::Unlisten { .. }
82        | CommandPlan::ResetVariable { .. }
83        | CommandPlan::ResetAllVariables
84        | CommandPlan::SetConstraints { .. }
85        | CommandPlan::ShowVariable { .. }
86        | CommandPlan::Discard { .. }
87        | CommandPlan::Load { .. }
88        | CommandPlan::Transaction(_)
89        | CommandPlan::FetchCursor(_)
90        | CommandPlan::CloseCursor { .. }
91        | CommandPlan::Prepare { .. }
92        | CommandPlan::Deallocate { .. }
93        | CommandPlan::Explain { .. }
94        | CommandPlan::DoBlock { .. }
95        | CommandPlan::Call { .. } => Ok(None),
96        CommandPlan::CreateTable(_)
97        | CommandPlan::CreateTableIfNotExists(_)
98        | CommandPlan::CreateTableAs { .. }
99        | CommandPlan::CreateIndex(_)
100        | CommandPlan::RenameIndex(_)
101        | CommandPlan::Drop(_)
102        | CommandPlan::AlterTable(_)
103        | CommandPlan::AlterForeignTable(_)
104        | CommandPlan::AlterView(_)
105        | CommandPlan::CreateView { .. }
106        | CommandPlan::CreateMaterializedView { .. }
107        | CommandPlan::RefreshMaterializedView { .. }
108        | CommandPlan::CreateSchema { .. }
109        | CommandPlan::AlterSchemaOwner { .. }
110        | CommandPlan::RenameSchema { .. }
111        | CommandPlan::Truncate { .. }
112        | CommandPlan::CreateSequence(_)
113        | CommandPlan::AlterSequence(_)
114        | CommandPlan::CreateDomain(_)
115        | CommandPlan::AlterDomain(_)
116        | CommandPlan::CommentType(_)
117        | CommandPlan::CreateShellType(_)
118        | CommandPlan::CreateEnum(_)
119        | CommandPlan::CreateCompositeType(_)
120        | CommandPlan::AlterEnum(_)
121        | CommandPlan::AlterTypeObject(_)
122        | CommandPlan::GrantType(_)
123        | CommandPlan::CreateForeignWrapper(_)
124        | CommandPlan::CreateForeignServer(_)
125        | CommandPlan::CreateForeignTable(_)
126        | CommandPlan::CreateForeignTableDefinition(_)
127        | CommandPlan::CreateFunction(_)
128        | CommandPlan::DropFunction(_)
129        | CommandPlan::AlterRoutine(_)
130        | CommandPlan::AlterRoutineOwner(_)
131        | CommandPlan::RenameRoutine(_)
132        | CommandPlan::GrantRoutine(_)
133        | CommandPlan::GrantTable(_)
134        | CommandPlan::GrantSequence(_)
135        | CommandPlan::GrantDatabase(_)
136        | CommandPlan::GrantSchema(_)
137        | CommandPlan::GrantRole(_)
138        | CommandPlan::CreateRole(_)
139        | CommandPlan::AlterRole(_)
140        | CommandPlan::RenameRole(_)
141        | CommandPlan::DropRole(_)
142        | CommandPlan::CreateTrigger(_)
143        | CommandPlan::DropTrigger(_)
144        | CommandPlan::CreateRule(_)
145        | CommandPlan::DropRule(_) => Ok(Some(command_tag_name(command))),
146    }
147}
148
149pub fn plan_sets_transaction_snapshot(plan: &UnifiedPlan) -> bool {
150    !matches!(
151        plan,
152        UnifiedPlan::Command(command)
153            if matches!(
154                command.as_ref(),
155                CommandPlan::Empty
156                    | CommandPlan::SetVariable { .. }
157                    | CommandPlan::Notify { .. }
158                    | CommandPlan::Listen { .. }
159                    | CommandPlan::Unlisten { .. }
160                    | CommandPlan::ResetVariable { .. }
161                    | CommandPlan::ResetAllVariables
162                    | CommandPlan::SetConstraints { .. }
163                    | CommandPlan::ShowVariable { .. }
164                    | CommandPlan::Transaction(_)
165                    | CommandPlan::LockTable(_)
166                    | CommandPlan::FetchCursor(_)
167                    | CommandPlan::CloseCursor { .. }
168                    | CommandPlan::Deallocate { .. }
169                    | CommandPlan::Load { .. }
170                    | CommandPlan::Discard { .. }
171            )
172    )
173}