uqa-sql 0.6.3

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Role incarnations and authorization subjects over an explicit role catalog.

use super::RoleDefinition;
use crate::SQLError;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, sync::Arc};
pub use uqa_core::catalog_role::RoleIdentity;
use uqa_core::memory::ProductionControl;

/// A selected role keeps its incarnation even if another role later reuses its name or OID.
#[derive(Debug, Serialize, Deserialize)]
pub struct RoleBinding {
    pub name: String,
    pub oid: u32,
    pub object_id: [u8; 16],
    #[serde(skip)]
    memory: Option<uqa_core::memory::MemoryReservation>,
}

impl Clone for RoleBinding {
    fn clone(&self) -> Self {
        Self::new(self.name.clone(), self.oid, self.object_id)
    }
}
impl PartialEq for RoleBinding {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.oid == other.oid && self.object_id == other.object_id
    }
}
impl Eq for RoleBinding {}

/// Explicit SQL names are resolved against the current catalog; captured authority retains its incarnation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RoleReference {
    Named(String),
    Bound(Arc<RoleBinding>),
}

impl From<String> for RoleReference {
    fn from(name: String) -> Self {
        Self::Named(name)
    }
}

impl From<&str> for RoleReference {
    fn from(name: &str) -> Self {
        Self::Named(name.into())
    }
}

impl RoleReference {
    pub fn from_identity_with_control(
        identity: RoleIdentity,
        roles: &BTreeMap<String, RoleDefinition>,
        control: &ProductionControl<'_>,
    ) -> Result<Self, SQLError> {
        let role = identity
            .role_definition_with_control(roles, control)?
            .ok_or_else(|| {
                SQLError::Internal(
                    "role identity references a missing or replaced incarnation".into(),
                )
            })?;
        Self::from_definition_with_control(role, control)
    }

    pub(crate) fn from_definition_with_control(
        role: &RoleDefinition,
        control: &ProductionControl<'_>,
    ) -> Result<Self, SQLError> {
        control.check()?;
        let oid = RoleBinding::validated_oid(role)?;
        let header = control.reserve(std::mem::size_of::<RoleBinding>())?;
        let (name, memory) = control.copy_text(&role.name)?.into_parts();
        control.check()?;
        Ok(Self::Bound(Arc::new(RoleBinding {
            name,
            oid,
            object_id: role.object_id,
            memory: control.combine(header, memory),
        })))
    }

    pub fn clone_with_control(
        &self,
        control: &ProductionControl<'_>,
    ) -> Result<uqa_core::memory::Produced<Self>, SQLError> {
        control.check()?;
        let (reference, memory) = match self {
            Self::Named(name) => {
                let (name, memory) = control.copy_text(name)?.into_parts();
                (Self::Named(name), memory)
            }
            Self::Bound(role) => (Self::Bound(role.clone()), control.empty_reservation()),
        };
        Ok(control.finish(reference, memory)?)
    }

    pub fn from_identity(
        identity: RoleIdentity,
        roles: &BTreeMap<String, RoleDefinition>,
    ) -> Result<Self, SQLError> {
        let name = identity.role_name(roles).ok_or_else(|| {
            SQLError::Internal("role identity references a missing or replaced incarnation".into())
        })?;
        Ok(Self::Bound(Arc::new(RoleBinding::from_definition(
            &roles[name],
        )?)))
    }

    pub fn require_name<'a>(
        &'a self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Result<&'a str, SQLError> {
        match self {
            Self::Named(name) => {
                super::require_role_exists(roles, name)?;
                Ok(name)
            }
            Self::Bound(role) => role.require_name(roles),
        }
    }

    pub fn catalog_name(
        &self,
        roles: &BTreeMap<String, RoleDefinition>,
    ) -> Result<String, SQLError> {
        match self {
            Self::Named(name) => Ok(name.clone()),
            Self::Bound(role) => role.require_name(roles).map(str::to_owned),
        }
    }

    pub fn bind(&self, roles: &BTreeMap<String, RoleDefinition>) -> Result<RoleBinding, SQLError> {
        let name = self.require_name(roles)?;
        RoleBinding::from_definition(&roles[name])
    }
}

impl RoleSubject for RoleReference {
    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
        match self {
            Self::Named(name) => name.role_name(roles),
            Self::Bound(role) => role.role_name(roles),
        }
    }

    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition> {
        match self {
            Self::Named(name) => name.role_definition(roles),
            Self::Bound(role) => role.role_definition(roles),
        }
    }

    fn role_definition_with_control<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
        control: &ProductionControl<'_>,
    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
        match self {
            Self::Named(name) => name.role_definition_with_control(roles, control),
            Self::Bound(role) => role.role_definition_with_control(roles, control),
        }
    }
}

impl RoleBinding {
    pub fn new(name: String, oid: u32, object_id: [u8; 16]) -> Self {
        Self {
            name,
            oid,
            object_id,
            memory: None,
        }
    }

    pub fn reserved_bytes(&self) -> usize {
        self.memory
            .as_ref()
            .map_or(0, uqa_core::memory::MemoryReservation::bytes)
    }

    pub fn identity(&self) -> RoleIdentity {
        RoleIdentity {
            oid: i64::from(self.oid),
            object_id: self.object_id,
        }
    }

    pub fn from_definition(role: &RoleDefinition) -> Result<Self, SQLError> {
        let oid = Self::validated_oid(role)?;
        Ok(Self::new(role.name.clone(), oid, role.object_id))
    }

    fn validated_oid(role: &RoleDefinition) -> Result<u32, SQLError> {
        if role.oid <= 0 {
            return Err(SQLError::Internal("invalid role OID".into()));
        }
        if role.object_id == [0; 16] {
            return Err(SQLError::Internal("role has no object identity".into()));
        }
        u32::try_from(role.oid).map_err(|_| SQLError::Internal("invalid role OID".into()))
    }

    /// Retain the original incarnation through name changes before publishing a stored role reference.
    pub fn revalidate(&self, roles: &BTreeMap<String, RoleDefinition>) -> Result<(), SQLError> {
        if self.role_definition(roles).is_some() {
            Ok(())
        } else {
            Err(SQLError::Routine {
                sqlstate: "42704".into(),
                message: format!("role {} was concurrently dropped", self.oid),
            })
        }
    }

    fn matches_definition(&self, role: &RoleDefinition) -> bool {
        role.oid == i64::from(self.oid) && role.object_id == self.object_id
    }

    pub fn require_name<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Result<&'a str, SQLError> {
        self.role_definition(roles)
            .map(|role| role.name.as_str())
            .ok_or_else(|| SQLError::Routine {
                sqlstate: "42704".into(),
                message: format!("invalid role OID: {}", self.oid),
            })
    }
}

/// A named SQL argument and an already selected session role have different lookup semantics. An absent bound role contributes no inherited privileges; PUBLIC ACLs remain applicable.
pub trait RoleSubject {
    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str>;

    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition>;

    /// Native captured identities poll while searching a renamed incarnation. External subjects retain their existing lookup semantics.
    fn role_definition_with_control<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
        control: &ProductionControl<'_>,
    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
        control.check()?;
        let role = self.role_definition(roles);
        control.check()?;
        Ok(role)
    }
}

impl<T: RoleSubject + ?Sized> RoleSubject for Arc<T> {
    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
        self.as_ref().role_name(roles)
    }
    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition> {
        self.as_ref().role_definition(roles)
    }

    fn role_definition_with_control<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
        control: &ProductionControl<'_>,
    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
        self.as_ref().role_definition_with_control(roles, control)
    }
}

impl<T: RoleSubject + ?Sized> RoleSubject for &T {
    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
        (*self).role_name(roles)
    }

    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition> {
        (*self).role_definition(roles)
    }

    fn role_definition_with_control<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
        control: &ProductionControl<'_>,
    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
        (*self).role_definition_with_control(roles, control)
    }
}

impl RoleSubject for str {
    fn role_name<'a>(&'a self, _roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
        Some(self)
    }

    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition> {
        roles.get(self)
    }
}

impl RoleSubject for String {
    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
        self.as_str().role_name(roles)
    }

    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition> {
        self.as_str().role_definition(roles)
    }
}

impl RoleSubject for uqa_core::catalog_acl::AclGrantee {
    fn role_name<'a>(&'a self, _roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
        self.role_name()
    }

    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition> {
        self.role_name().and_then(|name| roles.get(name))
    }
}

impl RoleSubject for RoleBinding {
    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
        self.role_definition(roles).map(|role| role.name.as_str())
    }

    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition> {
        roles
            .get(&self.name)
            .filter(|role| self.matches_definition(role))
            .or_else(|| roles.values().find(|role| self.matches_definition(role)))
    }

    fn role_definition_with_control<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
        control: &ProductionControl<'_>,
    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
        control.check()?;
        if let Some(role) = roles
            .get(&self.name)
            .filter(|role| self.matches_definition(role))
        {
            return Ok(Some(role));
        }
        for role in roles.values() {
            control.check()?;
            if self.matches_definition(role) {
                return Ok(Some(role));
            }
        }
        Ok(None)
    }
}

impl RoleSubject for RoleIdentity {
    fn role_name<'a>(&'a self, roles: &'a BTreeMap<String, RoleDefinition>) -> Option<&'a str> {
        self.role_definition(roles).map(|role| role.name.as_str())
    }

    fn role_definition<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
    ) -> Option<&'a RoleDefinition> {
        if !self.is_valid() {
            return None;
        }
        roles.values().find(|role| role.identity() == *self)
    }

    fn role_definition_with_control<'a>(
        &self,
        roles: &'a BTreeMap<String, RoleDefinition>,
        control: &ProductionControl<'_>,
    ) -> Result<Option<&'a RoleDefinition>, SQLError> {
        control.check()?;
        if !self.is_valid() {
            return Ok(None);
        }
        for role in roles.values() {
            control.check()?;
            if role.identity() == *self {
                return Ok(Some(role));
            }
        }
        Ok(None)
    }
}

#[cfg(test)]
mod tests;