uqa-sql 0.2.1

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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Relation persistence, view options, and sequence lifecycle nodes.

use serde::{Deserialize, Serialize};

/// `PostgreSQL`'s `pg_class.relpersistence` contract.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum RelationPersistence {
    #[default]
    Permanent,
    Unlogged,
    Temporary,
}

impl RelationPersistence {
    #[must_use]
    pub const fn catalog_code(self) -> &'static str {
        match self {
            Self::Permanent => "p",
            Self::Unlogged => "u",
            Self::Temporary => "t",
        }
    }
}

/// `ON COMMIT` behavior retained with a temporary table definition.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum OnCommitAction {
    #[default]
    PreserveRows,
    DeleteRows,
    Drop,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlterViewKind {
    View,
    MaterializedView,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlterViewAction {
    Set(Vec<(String, String)>),
    Reset(Vec<String>),
    OwnerTo(String),
    RenameTo(String),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlterViewStmt {
    pub name: String,
    pub kind: AlterViewKind,
    pub if_exists: bool,
    pub action: AlterViewAction,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlterForeignTableAction {
    OwnerTo(String),
    RenameTo(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlterForeignTableStmt {
    pub name: String,
    pub if_exists: bool,
    pub action: AlterForeignTableAction,
}

#[derive(Serialize, Deserialize)]
struct AlterForeignTableStmtSerde {
    name: String,
    if_exists: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    owner: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    rename_to: Option<String>,
}

impl Serialize for AlterForeignTableStmt {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let (owner, rename_to) = match &self.action {
            AlterForeignTableAction::OwnerTo(owner) => (Some(owner.clone()), None),
            AlterForeignTableAction::RenameTo(name) => (None, Some(name.clone())),
        };
        AlterForeignTableStmtSerde {
            name: self.name.clone(),
            if_exists: self.if_exists,
            owner,
            rename_to,
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for AlterForeignTableStmt {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = AlterForeignTableStmtSerde::deserialize(deserializer)?;
        let action = match (value.owner, value.rename_to) {
            (Some(owner), None) => AlterForeignTableAction::OwnerTo(owner),
            (None, Some(name)) => AlterForeignTableAction::RenameTo(name),
            (Some(_), Some(_)) => {
                return Err(serde::de::Error::custom(
                    "ALTER FOREIGN TABLE cannot contain both owner and rename_to",
                ));
            }
            (None, None) => {
                return Err(serde::de::Error::custom(
                    "ALTER FOREIGN TABLE requires owner or rename_to",
                ));
            }
        };
        Ok(Self {
            name: value.name,
            if_exists: value.if_exists,
            action,
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSequence {
    pub name: String,
    pub if_not_exists: bool,
    pub start: i64,
    pub increment: i64,
    #[serde(default)]
    pub persistence: RelationPersistence,
    #[serde(default)]
    pub data_type: SequenceDataType,
    /// Concrete bounds are written by current compilers. `None` is retained for backward-compatible plans and means the `PostgreSQL` default for the declared type and increment direction.
    #[serde(default)]
    pub min_value: Option<i64>,
    #[serde(default)]
    pub max_value: Option<i64>,
    #[serde(default)]
    pub cycle: bool,
    #[serde(default = "default_sequence_cache_size")]
    pub cache_size: i64,
    #[serde(default)]
    pub ownership: SequenceOwnership,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SequenceDataType {
    SmallInt,
    Integer,
    #[default]
    BigInt,
}

const fn default_sequence_cache_size() -> i64 {
    1
}

impl SequenceDataType {
    #[must_use]
    pub const fn sql_name(self) -> &'static str {
        match self {
            Self::SmallInt => "smallint",
            Self::Integer => "integer",
            Self::BigInt => "bigint",
        }
    }

    #[must_use]
    pub const fn bounds(self) -> (i64, i64) {
        match self {
            Self::SmallInt => (i16::MIN as i64, i16::MAX as i64),
            Self::Integer => (i32::MIN as i64, i32::MAX as i64),
            Self::BigInt => (i64::MIN, i64::MAX),
        }
    }
}

/// Physical restart action carried by `ALTER SEQUENCE`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SequenceRestart {
    /// No `RESTART` clause was specified.
    #[default]
    Unchanged,
    /// Bare `RESTART`; allocate the configured start value next.
    FromStart,
    /// `RESTART WITH value`; allocate the supplied value next.
    With(i64),
}

/// `ALTER SEQUENCE` bound action, distinguishing omission from `NO MINVALUE` or `NO MAXVALUE`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SequenceBound {
    #[default]
    Unchanged,
    Default,
    Value(i64),
}

/// `OWNED BY` action carried by `CREATE SEQUENCE` and `ALTER SEQUENCE`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SequenceOwnership {
    /// No ownership clause was specified. On `CREATE SEQUENCE` this creates an unowned sequence; on `ALTER SEQUENCE` it preserves the current dependency.
    #[default]
    Unchanged,
    /// Explicit `OWNED BY NONE`.
    Unowned,
    /// A table relation and one of its columns. The engine resolves both names to stable catalog object identities before persisting the dependency.
    Column { table: String, column: String },
}

/// Name or namespace lifecycle action carried by `ALTER SEQUENCE`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SequenceLifecycle {
    /// No name or namespace change was specified.
    #[default]
    Unchanged,
    RenameTo {
        name: String,
    },
    SetSchema {
        schema: String,
    },
}

fn deserialize_sequence_restart<'de, D>(deserializer: D) -> Result<SequenceRestart, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    enum Current {
        Unchanged,
        FromStart,
        With(i64),
    }

    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Representation {
        Current(Current),
        // Before SequenceRestart existed this field was
        // Option<Option<i64>>, serialized as null or an integer.
        Legacy(Option<i64>),
    }

    Ok(match Representation::deserialize(deserializer)? {
        Representation::Current(Current::Unchanged) | Representation::Legacy(None) => {
            SequenceRestart::Unchanged
        }
        Representation::Current(Current::FromStart) => SequenceRestart::FromStart,
        Representation::Current(Current::With(value)) | Representation::Legacy(Some(value)) => {
            SequenceRestart::With(value)
        }
    })
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AlterSequence {
    pub name: String,
    /// `ALTER SEQUENCE IF EXISTS` suppresses only a missing sequence.
    #[serde(default)]
    pub if_exists: bool,
    /// `RESTART [WITH n]`, preserving omitted, bare, and explicit forms.
    #[serde(default, deserialize_with = "deserialize_sequence_restart")]
    pub restart: SequenceRestart,
    pub increment: Option<i64>,
    pub start: Option<i64>,
    #[serde(default)]
    pub data_type: Option<SequenceDataType>,
    #[serde(default)]
    pub min_value: SequenceBound,
    #[serde(default)]
    pub max_value: SequenceBound,
    #[serde(default)]
    pub cycle: Option<bool>,
    pub cache_size: Option<i64>,
    #[serde(default)]
    pub ownership: SequenceOwnership,
    /// `SET LOGGED` or `SET UNLOGGED`. Temporary is never a valid requested target state.
    #[serde(default)]
    pub persistence: Option<RelationPersistence>,
    /// `OWNER TO role`, distinct from column ownership expressed by `OWNED BY`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role_owner: Option<String>,
    /// `RENAME TO` or `SET SCHEMA`, kept distinct from definition changes.
    #[serde(default)]
    pub lifecycle: SequenceLifecycle,
}

/// One requested sequence privilege. Unsupported names survive compilation so execution can preserve `PostgreSQL` target- and role-resolution precedence.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum SequencePrivilege {
    Select,
    Update,
    Usage,
    ColumnsUnsupported,
    Unsupported(String),
}

/// One table privilege and its optional column list. Unsupported names and column forms survive compilation so execution can preserve `PostgreSQL` object- and role-resolution precedence.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TablePrivilegeSpec {
    pub privilege: TablePrivilege,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub columns: Vec<String>,
}

/// One requested ordinary-table privilege.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum TablePrivilege {
    Select,
    Insert,
    Update,
    Delete,
    Truncate,
    References,
    Trigger,
    Maintain,
    Usage,
    Unsupported(String),
}

/// Relation targets carried by `GRANT` or `REVOKE` with the `TABLE` object class.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GrantTableTarget {
    Relations { names: Vec<String> },
    AllTablesInSchemas { schemas: Vec<String> },
}

/// Dependency behavior for ordinary-table privilege revocation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum TableRevokeBehavior {
    #[default]
    Restrict,
    Cascade,
}

/// `GRANT` or `REVOKE` of privileges on ordinary tables. An empty privilege list records `ALL PRIVILEGES` so explicit sequence targets can expand against their own privilege set.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GrantTableStmt {
    pub is_grant: bool,
    pub grant_option: bool,
    pub grant_option_only: bool,
    pub privileges: Vec<TablePrivilegeSpec>,
    pub target: GrantTableTarget,
    pub grantees: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grantor: Option<String>,
    #[serde(default)]
    pub revoke_behavior: TableRevokeBehavior,
}

/// Relation targets carried by `GRANT` or `REVOKE` for sequences.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GrantSequenceTarget {
    Sequences { names: Vec<String> },
    AllSequencesInSchemas { schemas: Vec<String> },
}

/// Dependency behavior for sequence privilege revocation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SequenceRevokeBehavior {
    #[default]
    Restrict,
    Cascade,
}

/// `GRANT` or `REVOKE` of `USAGE`, `SELECT`, and `UPDATE` on sequences.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GrantSequenceStmt {
    pub is_grant: bool,
    pub grant_option: bool,
    pub grant_option_only: bool,
    pub privileges: Vec<SequencePrivilege>,
    pub target: GrantSequenceTarget,
    pub grantees: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grantor: Option<String>,
    #[serde(default)]
    pub revoke_behavior: SequenceRevokeBehavior,
}

/// One requested database privilege. Unsupported names survive compilation so execution can preserve `PostgreSQL` target- and role-resolution precedence.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum DatabasePrivilege {
    Connect,
    Create,
    Temporary,
    Unsupported(String),
}

/// Dependency behavior for database privilege revocation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum DatabaseRevokeBehavior {
    #[default]
    Restrict,
    Cascade,
}

/// `GRANT` or `REVOKE` of `CONNECT`, `CREATE`, and `TEMPORARY` on databases.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GrantDatabaseStmt {
    pub is_grant: bool,
    pub grant_option: bool,
    pub grant_option_only: bool,
    pub privileges: Vec<DatabasePrivilege>,
    pub databases: Vec<String>,
    pub grantees: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grantor: Option<String>,
    #[serde(default)]
    pub revoke_behavior: DatabaseRevokeBehavior,
}

/// One requested schema privilege. Unsupported names survive compilation so execution can preserve `PostgreSQL` target- and role-resolution precedence.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum SchemaPrivilege {
    Usage,
    Create,
    Unsupported(String),
}

/// Dependency behavior for schema privilege revocation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SchemaRevokeBehavior {
    #[default]
    Restrict,
    Cascade,
}

/// `GRANT` or `REVOKE` of `USAGE` and `CREATE` on schemas.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GrantSchemaStmt {
    pub is_grant: bool,
    pub grant_option: bool,
    pub grant_option_only: bool,
    pub privileges: Vec<SchemaPrivilege>,
    pub schemas: Vec<String>,
    pub grantees: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grantor: Option<String>,
    #[serde(default)]
    pub revoke_behavior: SchemaRevokeBehavior,
}