1use crate::row_locks::{
10 binding::{
11 bind_relation, lock_descendants, RelationBinding, RelationLockCatalog, RelationLockSession,
12 },
13 RelationLockMode,
14};
15use uqa_sql::catalog::roles::RoleReference;
16use uqa_sql::{
17 ast::{LockTableStmt, LockTableTarget, TableLockMode},
18 catalog::{
19 resolution::RelationResolution, roles::guards::RoleCatalogGuards,
20 security::BoundTableSecurity, stored_view::StoredView, SystemRelation,
21 },
22 semantics::table_locks::{ensure_lock_privilege, view_lock_targets},
23 SQLError, SQLResult,
24};
25
26pub struct TableLockMetadata {
27 pub object_id: [u8; 16],
28 pub security: BoundTableSecurity,
29}
30
31pub trait TableLockCatalog:
32 RelationLockCatalog + uqa_sql::catalog::security::system_relations::SystemRelationSecurityCatalog
33{
34 fn resolve(&self, name: &str, bound: bool) -> Result<RelationResolution, SQLError>;
35 fn table(
36 &self,
37 name: &str,
38 roles: &std::collections::BTreeMap<String, uqa_sql::catalog::roles::RoleDefinition>,
39 ) -> Result<Option<TableLockMetadata>, SQLError>;
40 fn view(&self, name: &str) -> Result<Option<StoredView>, SQLError>;
41 fn descendants(&self, name: &str) -> Result<Vec<String>, SQLError>;
42}
43
44pub trait TableLockSession: RelationLockSession {
45 fn in_transaction_block(&self) -> bool;
46 fn current_role(&self) -> RoleReference;
47}
48
49#[derive(Clone, Copy)]
50pub struct TableLockContext<'a> {
51 pub catalog: &'a dyn TableLockCatalog,
52 pub roles: &'a dyn RoleCatalogGuards,
53 pub session: &'a dyn TableLockSession,
54}
55
56struct BoundRelation {
57 name: String,
58 kind: &'static str,
59 metadata: TableLockMetadata,
60 source: RelationSource,
61}
62
63enum RelationSource {
64 Table,
65 View(Box<StoredView>),
66 System(SystemRelation),
67}
68
69impl TableLockContext<'_> {
70 fn resolve(
71 &self,
72 name: &str,
73 bound: bool,
74 view_source: bool,
75 ) -> Result<Option<BoundRelation>, SQLError> {
76 let (canonical, kind) = match self.catalog.resolve(name, bound)? {
77 RelationResolution::Found(canonical, kind) => (canonical, kind),
78 RelationResolution::MissingSchema(schema) => {
79 return Err(SQLError::Routine {
80 sqlstate: "3F000".into(),
81 message: format!("schema \"{schema}\" does not exist"),
82 })
83 }
84 RelationResolution::MissingRelation => return Err(SQLError::UnknownTable(name.into())),
85 };
86 if let Some(relation) = SystemRelation::from_qualified_name(&canonical) {
87 return Ok(Some(BoundRelation {
88 name: canonical,
89 kind,
90 metadata: TableLockMetadata {
91 object_id: relation.object_id(),
92 security: self.catalog.system_relation_security(relation),
93 },
94 source: RelationSource::System(relation),
95 }));
96 }
97 match kind {
98 "table" => self
99 .catalog
100 .table(&canonical, &self.roles.role_definitions())?
101 .map(|metadata| BoundRelation {
102 name: canonical,
103 kind,
104 metadata,
105 source: RelationSource::Table,
106 }),
107 "view" => self
108 .catalog
109 .view(&canonical)?
110 .map(|view| {
111 Ok::<_, SQLError>(BoundRelation {
112 name: canonical,
113 kind,
114 metadata: TableLockMetadata {
115 object_id: view.object_id,
116 security: view.security(),
117 },
118 source: RelationSource::View(Box::new(view)),
119 })
120 })
121 .transpose()?,
122 _ if view_source => return Ok(None),
123 _ => {
124 let (_, local) = uqa_core::RelationIdentity::parse_reference(&canonical)
125 .map_err(SQLError::Internal)?;
126 return Err(SQLError::Diagnostic {
127 sqlstate: "42809".into(),
128 message: format!("cannot lock relation \"{local}\""),
129 detail: uqa_sql::catalog::analysis::relkind_not_supported_detail(kind),
130 hint: None,
131 });
132 }
133 }
134 .map(Some)
135 .ok_or_else(|| SQLError::UnknownTable(name.into()))
136 }
137
138 fn lock_named(
139 &self,
140 name: &str,
141 bound: bool,
142 subject: &RoleReference,
143 statement: &LockTableStmt,
144 view_source: bool,
145 ) -> Result<Option<BoundRelation>, SQLError> {
146 bind_relation(
147 self.session,
148 statement.mode.into(),
149 statement.nowait,
150 || {
151 self.resolve(name, bound, view_source).map(|relation| {
152 relation.map(|value| RelationBinding {
153 name: value.name.clone(),
154 object_id: Some(value.metadata.object_id),
155 value,
156 })
157 })
158 },
159 |relation| {
160 let target = &relation.value;
161 ensure_lock_privilege(
162 self.roles,
163 &target.metadata.security,
164 subject,
165 statement.mode,
166 &relation.name,
167 target.kind,
168 )
169 },
170 )
171 .map(|relation| relation.map(|relation| relation.value))
172 }
173
174 fn lock_descendants(&self, name: &str, statement: &LockTableStmt) -> Result<(), SQLError> {
175 lock_descendants(
176 self.catalog,
177 self.session,
178 self.catalog
179 .descendants(name)?
180 .into_iter()
181 .filter(|child| child != name),
182 statement.mode.into(),
183 statement.nowait,
184 )
185 }
186
187 fn lock_references(
188 &self,
189 relation: BoundRelation,
190 descendants: bool,
191 statement: &LockTableStmt,
192 ancestors: &mut Vec<[u8; 16]>,
193 ) -> Result<(), SQLError> {
194 if ancestors.contains(&relation.metadata.object_id) {
195 return Ok(());
196 }
197 let (targets, subject) = match relation.source {
198 RelationSource::Table => {
199 return if descendants {
200 self.lock_descendants(&relation.name, statement)
201 } else {
202 Ok(())
203 };
204 }
205 RelationSource::View(view) => (
206 view_lock_targets(&view.query)?,
207 if view.security_invoker() {
208 self.session.current_role()
209 } else {
210 relation
211 .metadata
212 .security
213 .owner_reference(&self.roles.role_definitions())?
214 },
215 ),
216 RelationSource::System(system) => (
217 system
218 .view_sources()
219 .iter()
220 .map(|source| LockTableTarget {
221 name: source.qualified_name(),
222 include_descendants: false,
223 })
224 .collect(),
225 relation
226 .metadata
227 .security
228 .owner_reference(&self.roles.role_definitions())?,
229 ),
230 };
231 ancestors.push(relation.metadata.object_id);
232 for target in targets {
233 if self
234 .resolve(&target.name, true, true)?
235 .is_some_and(|source| ancestors.contains(&source.metadata.object_id))
236 {
237 continue;
238 }
239 if let Some(source) = self.lock_named(&target.name, true, &subject, statement, true)? {
240 self.lock_references(source, target.include_descendants, statement, ancestors)?;
241 }
242 }
243 ancestors.pop();
244 Ok(())
245 }
246}
247
248pub fn execute(
249 context: TableLockContext<'_>,
250 statement: &LockTableStmt,
251 nested: bool,
252) -> Result<SQLResult, SQLError> {
253 if !nested && !context.session.in_transaction_block() {
254 return Err(SQLError::Routine {
255 sqlstate: "25P01".into(),
256 message: "LOCK TABLE can only be used in transaction blocks".into(),
257 });
258 }
259 let subject = context.session.current_role();
260 for target in &statement.targets {
261 if let Some(relation) =
262 context.lock_named(&target.name, false, &subject, statement, false)?
263 {
264 context.lock_references(
265 relation,
266 target.include_descendants,
267 statement,
268 &mut Vec::new(),
269 )?;
270 }
271 }
272 Ok(SQLResult::empty())
273}
274
275impl From<TableLockMode> for RelationLockMode {
276 fn from(mode: TableLockMode) -> Self {
277 match mode {
278 TableLockMode::AccessShare => Self::AccessShare,
279 TableLockMode::RowShare => Self::RowShare,
280 TableLockMode::RowExclusive => Self::RowExclusive,
281 TableLockMode::ShareUpdateExclusive => Self::ShareUpdateExclusive,
282 TableLockMode::Share => Self::Share,
283 TableLockMode::ShareRowExclusive => Self::ShareRowExclusive,
284 TableLockMode::Exclusive => Self::Exclusive,
285 TableLockMode::AccessExclusive => Self::AccessExclusive,
286 }
287 }
288}
289
290#[cfg(test)]
291mod tests;