uqa-sql 0.3.6

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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! SQL/PLpgSQL routine creation, invocation, bodies, and drops.

use super::dispatch::compile_stmt;
use super::{
    compile_expr, compile_qualified_name, extract_string, render_relation_component, Expr, Node,
    NodeEnum, Result, SQLError, Statement,
};

mod roles;

pub(super) use roles::{
    compile_alter_role, compile_alter_routine_owner, compile_create_role, compile_drop_role,
    compile_grant, compile_grant_role, compile_object_with_args, compile_role_spec,
    CompiledRoutineTarget,
};

struct CompiledFunctionTypeName {
    name: String,
    reference: Option<crate::ast::RoutineColumnTypeReference>,
}

/// Canonical spelling of a routine `TypeName`. A leading `pg_catalog`
/// qualifier is redundant, while relation qualification on `%TYPE` and
/// schema qualification on named types must survive compilation for catalog
/// resolution by the engine.
fn compile_function_type_name(
    t: &pg_query::protobuf::TypeName,
) -> Result<CompiledFunctionTypeName> {
    let mut components = t
        .names
        .iter()
        .map(extract_string)
        .collect::<Result<Vec<_>>>()?;
    if !t.pct_type
        && components
            .first()
            .is_some_and(|component| component.eq_ignore_ascii_case("pg_catalog"))
    {
        components.remove(0);
    }
    if components.is_empty() {
        return Err(SQLError::Internal(
            "function type has no name components".into(),
        ));
    }
    // `setof` is inspected separately by the caller; the name itself
    // stays scalar.
    let reference = if t.pct_type {
        let reference = match components.as_slice() {
            [relation, column] => {
                crate::ast::RoutineColumnTypeReference::new(None, relation.clone(), column.clone())
            }
            [schema, relation, column] => crate::ast::RoutineColumnTypeReference::new(
                Some(schema.clone()),
                relation.clone(),
                column.clone(),
            ),
            _ => {
                return Err(SQLError::TypeMismatch(
                    "%TYPE requires a relation and column reference".into(),
                ))
            }
        };
        Some(reference)
    } else {
        None
    };
    let mut name = components
        .iter()
        .map(|component| render_relation_component(component))
        .collect::<Vec<_>>()
        .join(".");
    if !t.pct_type && t.array_bounds.is_empty() && components.len() == 1 {
        if let Some(element) = crate::ast::builtin_array_element_name(&components[0]) {
            name = format!("{element}[]");
        }
    }
    if t.pct_type {
        name.push_str("%type");
    }
    for _ in &t.array_bounds {
        name.push_str("[]");
    }
    Ok(CompiledFunctionTypeName { name, reference })
}

/// String payload of a `DefElem` argument.
fn def_elem_string(elem: &pg_query::protobuf::DefElem) -> Result<String> {
    match elem.arg.as_ref().and_then(|a| a.node.as_ref()) {
        Some(NodeEnum::String(s)) => Ok(s.sval.clone()),
        other => Err(SQLError::TypeMismatch(format!(
            "option `{}` expects a string, got {other:?}",
            elem.defname
        ))),
    }
}

fn def_elem_bool(elem: &pg_query::protobuf::DefElem, context: &str) -> Result<bool> {
    match elem
        .arg
        .as_ref()
        .and_then(|argument| argument.node.as_ref())
    {
        Some(NodeEnum::Boolean(value)) => Ok(value.boolval),
        other => Err(SQLError::TypeMismatch(format!(
            "{context} expects a boolean, got {other:?}"
        ))),
    }
}

fn compile_support_name(elem: &pg_query::protobuf::DefElem, context: &str) -> Result<String> {
    let Some(NodeEnum::List(list)) = elem
        .arg
        .as_ref()
        .and_then(|argument| argument.node.as_ref())
    else {
        return Err(SQLError::TypeMismatch(format!(
            "{context} SUPPORT expects a routine name"
        )));
    };
    compile_qualified_name(&list.items, context)
}

fn compile_routine_config_action(
    element: &pg_query::protobuf::DefElem,
    context: &str,
) -> Result<crate::ast::RoutineConfigAction> {
    use crate::ast::RoutineConfigAction;
    use pg_query::protobuf::VariableSetKind;

    let Some(NodeEnum::VariableSetStmt(setting)) = element
        .arg
        .as_ref()
        .and_then(|argument| argument.node.as_ref())
    else {
        return Err(SQLError::TypeMismatch(format!(
            "{context} SET expects a configuration action"
        )));
    };
    match setting.kind() {
        VariableSetKind::VarSetValue => {
            let Statement::SetVariable { name, value, .. } =
                super::administrative::compile_variable_set(setting)?
            else {
                return Err(SQLError::Internal(
                    "routine SET did not compile as a variable assignment".into(),
                ));
            };
            Ok(RoutineConfigAction::Set { name, value })
        }
        VariableSetKind::VarSetDefault => Ok(RoutineConfigAction::Reset {
            name: setting.name.clone(),
        }),
        VariableSetKind::VarSetCurrent => Ok(RoutineConfigAction::FromCurrent {
            name: setting.name.clone(),
        }),
        VariableSetKind::VarReset => Ok(RoutineConfigAction::Reset {
            name: setting.name.clone(),
        }),
        VariableSetKind::VarResetAll => Ok(RoutineConfigAction::ResetAll),
        other => Err(SQLError::Unsupported(format!(
            "{context}: configuration action {other:?} is not supported"
        ))),
    }
}

#[expect(
    clippy::too_many_lines,
    reason = "ordered PostgreSQL lowering preserves syntax and error precedence"
)]
pub(super) fn compile_create_function(
    stmt: &pg_query::protobuf::CreateFunctionStmt,
) -> Result<crate::ast::CreateFunction> {
    use crate::ast::{
        CreateFunction, FunctionBody, FunctionParam, FunctionParamMode, FunctionReturns,
        FunctionVolatility,
    };
    use pg_query::protobuf::FunctionParameterMode;

    let keyword = if stmt.is_procedure {
        "CREATE PROCEDURE"
    } else {
        "CREATE FUNCTION"
    };
    let name = compile_qualified_name(&stmt.funcname, keyword)?;

    let mut params: Vec<FunctionParam> = Vec::with_capacity(stmt.parameters.len());
    let mut has_table_param = false;
    for p in &stmt.parameters {
        let Some(NodeEnum::FunctionParameter(fp)) = p.node.as_ref() else {
            return Err(SQLError::Internal(format!(
                "{keyword}: malformed parameter"
            )));
        };
        let mode = match fp.mode() {
            FunctionParameterMode::FuncParamIn | FunctionParameterMode::FuncParamDefault => {
                FunctionParamMode::In
            }
            FunctionParameterMode::FuncParamOut => FunctionParamMode::Out,
            FunctionParameterMode::FuncParamInout => FunctionParamMode::InOut,
            FunctionParameterMode::FuncParamTable => {
                has_table_param = true;
                FunctionParamMode::Table
            }
            FunctionParameterMode::FuncParamVariadic => FunctionParamMode::Variadic,
            FunctionParameterMode::Undefined => {
                return Err(SQLError::Internal(format!(
                    "{keyword}: parameter mode missing"
                )));
            }
        };
        let compiled_type = fp
            .arg_type
            .as_ref()
            .map(compile_function_type_name)
            .transpose()?
            .ok_or_else(|| SQLError::Internal(format!("{keyword}: parameter without type")))?;
        let default = match fp.defexpr.as_ref() {
            Some(node) => Some(compile_expr(node)?),
            None => None,
        };
        params.push(FunctionParam {
            // libpg_query has already folded unquoted identifiers while
            // preserving quoted identifiers. Keep that distinction: named
            // argument matching in PostgreSQL is case-sensitive after parse
            // analysis.
            name: fp.name.clone(),
            type_name: compiled_type.name,
            type_reference: compiled_type.reference,
            mode,
            default,
        });
    }

    // Mirror PostgreSQL's parse-time rule: once an input parameter
    // has a DEFAULT, every following input parameter needs one too.
    let mut saw_default = false;
    for p in &params {
        if !matches!(
            p.mode,
            FunctionParamMode::In | FunctionParamMode::InOut | FunctionParamMode::Variadic
        ) {
            continue;
        }
        if p.default.is_some() {
            saw_default = true;
        } else if saw_default {
            return Err(SQLError::Unsupported(
                "input parameters after one with a default value must also have defaults".into(),
            ));
        }
    }

    let (returns, return_type_reference) = if has_table_param {
        (FunctionReturns::Table, None)
    } else {
        match stmt.return_type.as_ref() {
            None => (FunctionReturns::None, None),
            Some(t) => {
                let compiled = compile_function_type_name(t)?;
                let returns = if t.setof {
                    FunctionReturns::SetOf {
                        type_name: compiled.name,
                    }
                } else {
                    FunctionReturns::Scalar {
                        type_name: compiled.name,
                    }
                };
                (returns, compiled.reference)
            }
        }
    };

    let mut language = String::new();
    let mut volatility = FunctionVolatility::Volatile;
    let mut strict = false;
    let mut security_definer = false;
    let mut leakproof = false;
    let mut parallel = crate::ast::FunctionParallel::Unsafe;
    let mut support = None;
    let mut config_actions = Vec::new();
    let mut source: Option<String> = None;
    for opt in &stmt.options {
        let Some(NodeEnum::DefElem(elem)) = opt.node.as_ref() else {
            return Err(SQLError::Internal(format!("{keyword}: malformed option")));
        };
        match elem.defname.to_ascii_lowercase().as_str() {
            "language" => {
                language = def_elem_string(elem)?.to_ascii_lowercase();
            }
            "volatility" => {
                volatility = match def_elem_string(elem)?.as_str() {
                    "immutable" => FunctionVolatility::Immutable,
                    "stable" => FunctionVolatility::Stable,
                    "volatile" => FunctionVolatility::Volatile,
                    other => {
                        return Err(SQLError::TypeMismatch(format!(
                            "{keyword}: invalid volatility `{other}`"
                        )));
                    }
                };
            }
            "strict" => {
                strict = def_elem_bool(elem, &format!("{keyword}: STRICT"))?;
            }
            "security" => {
                security_definer = def_elem_bool(elem, &format!("{keyword}: SECURITY"))?;
            }
            "leakproof" => {
                leakproof = def_elem_bool(elem, &format!("{keyword}: LEAKPROOF"))?;
            }
            "parallel" => {
                parallel = match def_elem_string(elem)?.as_str() {
                    "unsafe" => crate::ast::FunctionParallel::Unsafe,
                    "restricted" => crate::ast::FunctionParallel::Restricted,
                    "safe" => crate::ast::FunctionParallel::Safe,
                    other => {
                        return Err(SQLError::TypeMismatch(format!(
                            "{keyword}: invalid PARALLEL value `{other}`"
                        )))
                    }
                };
            }
            "support" => support = Some(compile_support_name(elem, keyword)?),
            "set" => config_actions.push(compile_routine_config_action(elem, keyword)?),
            "as" => {
                let items: Vec<String> = match elem.arg.as_ref().and_then(|a| a.node.as_ref()) {
                    Some(NodeEnum::List(list)) => list
                        .items
                        .iter()
                        .map(extract_string)
                        .collect::<Result<Vec<_>>>()?,
                    Some(NodeEnum::String(s)) => vec![s.sval.clone()],
                    other => {
                        return Err(SQLError::TypeMismatch(format!(
                            "{keyword}: AS expects a string body, got {other:?}"
                        )));
                    }
                };
                match items.len() {
                    1 => source = items.into_iter().next(),
                    _ => {
                        return Err(SQLError::Unsupported(format!(
                            "{keyword}: AS 'obj_file', 'link_symbol' bodies"
                        )));
                    }
                }
            }
            "window" => {
                return Err(SQLError::Unsupported(format!(
                    "{keyword}: WINDOW functions"
                )));
            }
            // Planner / execution hints outside this routine contract: COST and ROWS.
            other => {
                return Err(SQLError::Unsupported(format!(
                    "{keyword}: option `{other}` is not supported"
                )));
            }
        }
    }

    let body = match (source, stmt.sql_body.as_deref()) {
        (Some(src), None) => FunctionBody::Source(src),
        (None, Some(node)) => FunctionBody::Statements(compile_sql_standard_body(node)?),
        (Some(_), Some(_)) => {
            return Err(SQLError::Unsupported(format!(
                "{keyword}: both AS body and SQL-standard body"
            )));
        }
        (None, None) => {
            return Err(SQLError::Unsupported(format!(
                "{keyword}: no function body"
            )));
        }
    };
    if language.is_empty() {
        if matches!(body, FunctionBody::Statements(_)) {
            language = "sql".into();
        } else {
            return Err(SQLError::Unsupported(format!(
                "{keyword}: no language specified"
            )));
        }
    }

    Ok(CreateFunction {
        object_id: None,
        name,
        or_replace: stmt.replace,
        is_procedure: stmt.is_procedure,
        params,
        returns,
        return_type_reference,
        language,
        body,
        creation_search_path: Vec::new(),
        volatility,
        strict,
        owner: String::new(),
        security: crate::ast::RoutineSecurityAttributes {
            security_definer,
            leakproof,
        },
        parallel,
        support,
        config: Vec::new(),
        config_actions,
        execute_acl: None,
    })
}

/// Compile a SQL-standard function body (`RETURN expr` or
/// `BEGIN ATOMIC stmt; ... END`) into plain statements.
pub(super) fn compile_sql_standard_body(node: &Node) -> Result<Vec<Statement>> {
    let Some(inner) = node.node.as_ref() else {
        return Err(SQLError::Internal("empty SQL function body".into()));
    };
    match inner {
        NodeEnum::ReturnStmt(ret) => {
            let value = ret
                .returnval
                .as_deref()
                .ok_or_else(|| SQLError::Internal("RETURN without a value".into()))?;
            Ok(vec![select_of_expr(compile_expr(value)?)])
        }
        NodeEnum::List(list) => {
            let mut out = Vec::with_capacity(list.items.len());
            for item in &list.items {
                let item_inner = item.node.as_ref().ok_or_else(|| {
                    SQLError::Internal("SQL function body contains an empty statement".into())
                })?;
                match item_inner {
                    // BEGIN ATOMIC wraps each statement in a nested list.
                    NodeEnum::List(stmts) => {
                        for s in &stmts.items {
                            out.push(compile_stmt(s)?);
                        }
                    }
                    NodeEnum::ReturnStmt(ret) => {
                        let value = ret
                            .returnval
                            .as_deref()
                            .ok_or_else(|| SQLError::Internal("RETURN without a value".into()))?;
                        out.push(select_of_expr(compile_expr(value)?));
                    }
                    _ => out.push(compile_stmt(item)?),
                }
            }
            Ok(out)
        }
        other => Err(SQLError::Unsupported(format!(
            "SQL function body node {other:?}"
        ))),
    }
}

/// `SELECT <expr>` statement wrapping a single expression.
fn select_of_expr(expr: Expr) -> Statement {
    Statement::Select(Box::new(crate::ast::SelectStmt {
        projections: vec![crate::ast::Projection { expr, alias: None }],
        values: Vec::new(),
        from: None,
        r#where: None,
        group_by: Vec::new(),
        grouping_sets: Vec::new(),
        group_distinct: false,
        having: None,
        order_by: Vec::new(),
        limit: None,
        with_ties: false,
        offset: None,
        with: Vec::new(),
        set_op: None,
        distinct: false,
        distinct_on: Vec::new(),
        locking: Vec::new(),
    }))
}

pub(super) fn compile_do(stmt: &pg_query::protobuf::DoStmt) -> Result<Statement> {
    let mut language = "plpgsql".to_string();
    let mut body: Option<String> = None;
    for arg in &stmt.args {
        let Some(NodeEnum::DefElem(elem)) = arg.node.as_ref() else {
            return Err(SQLError::Internal("DO contains a malformed option".into()));
        };
        match elem.defname.to_ascii_lowercase().as_str() {
            "as" => body = Some(def_elem_string(elem)?),
            "language" => {
                language = def_elem_string(elem)?.to_ascii_lowercase();
            }
            other => {
                return Err(SQLError::Unsupported(format!(
                    "DO option `{other}` is not supported"
                )));
            }
        }
    }
    let body = body.ok_or_else(|| SQLError::Internal("DO without a body".into()))?;
    Ok(Statement::DoBlock { language, body })
}

pub(super) fn compile_call(stmt: &pg_query::protobuf::CallStmt) -> Result<Statement> {
    let call = stmt
        .funccall
        .as_ref()
        .ok_or_else(|| SQLError::Internal("CALL without a function".into()))?;
    let name = compile_qualified_name(&call.funcname, "CALL")?;
    crate::expr::validate_named_argument_order(call.args.iter().map(|argument| {
        match argument.node.as_ref() {
            Some(NodeEnum::NamedArgExpr(argument)) => Some(argument.name.as_str()),
            _ => None,
        }
    }))?;
    let mut args = call
        .args
        .iter()
        .map(compile_expr)
        .collect::<Result<Vec<_>>>()?;
    if call.func_variadic {
        let argument = args.pop().ok_or_else(|| {
            SQLError::Internal(format!("VARIADIC invocation of `{name}` has no argument"))
        })?;
        args.push(crate::expr::wrap_variadic_argument(argument));
    }
    Ok(Statement::Call { name, args })
}

pub(super) fn compile_drop_function(
    stmt: &pg_query::protobuf::DropStmt,
    is_procedure: bool,
) -> Result<Statement> {
    use crate::ast::{DropFunctionItem, DropFunctionStmt};
    let mut items = Vec::new();
    for object in &stmt.objects {
        let Some(NodeEnum::ObjectWithArgs(owa)) = object.node.as_ref() else {
            return Err(SQLError::Unsupported(
                "DROP FUNCTION target is not a function signature".into(),
            ));
        };
        let name = compile_qualified_name(
            &owa.objname,
            if is_procedure {
                "DROP PROCEDURE"
            } else {
                "DROP FUNCTION"
            },
        )?;
        let arg_types = if owa.args_unspecified {
            None
        } else {
            Some(
                owa.objargs
                    .iter()
                    .map(|arg| match arg.node.as_ref() {
                        Some(NodeEnum::TypeName(t)) => {
                            compile_function_type_name(t).map(|compiled| compiled.name)
                        }
                        other => Err(SQLError::Unsupported(format!(
                            "DROP FUNCTION argument type node {other:?}"
                        ))),
                    })
                    .collect::<Result<Vec<_>>>()?,
            )
        };
        items.push(DropFunctionItem { name, arg_types });
    }
    if items.is_empty() {
        return Err(SQLError::Internal("DROP FUNCTION without target".into()));
    }
    Ok(Statement::DropFunction(DropFunctionStmt {
        is_procedure,
        if_exists: stmt.missing_ok,
        cascade: matches!(
            stmt.behavior(),
            pg_query::protobuf::DropBehavior::DropCascade
        ),
        items,
    }))
}

#[expect(
    clippy::too_many_lines,
    reason = "ordered PostgreSQL lowering preserves syntax and error precedence"
)]
pub(super) fn compile_alter_routine(
    stmt: &pg_query::protobuf::AlterFunctionStmt,
) -> Result<crate::ast::AlterRoutineStmt> {
    use crate::ast::{AlterRoutineKind, AlterRoutineStmt, FunctionParallel, FunctionVolatility};
    use pg_query::protobuf::ObjectType;

    let (kind, keyword) = match stmt.objtype() {
        ObjectType::ObjectFunction => (AlterRoutineKind::Function, "ALTER FUNCTION"),
        ObjectType::ObjectProcedure => (AlterRoutineKind::Procedure, "ALTER PROCEDURE"),
        ObjectType::ObjectRoutine => (AlterRoutineKind::Routine, "ALTER ROUTINE"),
        other => {
            return Err(SQLError::Unsupported(format!(
                "ALTER routine target {other:?} is not supported"
            )))
        }
    };
    let target = stmt
        .func
        .as_ref()
        .ok_or_else(|| SQLError::Internal(format!("{keyword} without a target")))?;
    let name = compile_qualified_name(&target.objname, keyword)?;
    let (arg_types, mut arg_type_references) = if target.args_unspecified {
        (None, Vec::new())
    } else {
        let mut arg_types = Vec::with_capacity(target.objargs.len());
        let mut references = Vec::with_capacity(target.objargs.len());
        for argument in &target.objargs {
            let Some(NodeEnum::TypeName(type_name)) = argument.node.as_ref() else {
                return Err(SQLError::Unsupported(format!(
                    "{keyword}: malformed argument type node {:?}",
                    argument.node
                )));
            };
            let compiled = compile_function_type_name(type_name)?;
            arg_types.push(compiled.name);
            references.push(compiled.reference);
        }
        (Some(arg_types), references)
    };
    if arg_type_references.iter().all(Option::is_none) {
        arg_type_references.clear();
    }

    let mut volatility = None;
    let mut strict = None;
    let mut security_definer = None;
    let mut leakproof = None;
    let mut parallel = None;
    let mut support = None;
    let mut config_actions = Vec::new();
    for action in &stmt.actions {
        let Some(NodeEnum::DefElem(element)) = action.node.as_ref() else {
            return Err(SQLError::Unsupported(format!(
                "{keyword}: malformed action node {:?}",
                action.node
            )));
        };
        match element.defname.to_ascii_lowercase().as_str() {
            "volatility" => {
                if volatility.is_some() {
                    return Err(SQLError::Routine {
                        sqlstate: "42601".into(),
                        message: format!("{keyword}: conflicting or redundant volatility option"),
                    });
                }
                volatility = Some(match def_elem_string(element)?.as_str() {
                    "immutable" => FunctionVolatility::Immutable,
                    "stable" => FunctionVolatility::Stable,
                    "volatile" => FunctionVolatility::Volatile,
                    other => {
                        return Err(SQLError::TypeMismatch(format!(
                            "{keyword}: invalid volatility `{other}`"
                        )))
                    }
                });
            }
            "strict" => {
                if strict.is_some() {
                    return Err(SQLError::Routine {
                        sqlstate: "42601".into(),
                        message: format!("{keyword}: conflicting or redundant null-input option"),
                    });
                }
                strict = Some(
                    match element.arg.as_ref().and_then(|arg| arg.node.as_ref()) {
                        Some(NodeEnum::Boolean(value)) => value.boolval,
                        other => {
                            return Err(SQLError::TypeMismatch(format!(
                                "{keyword}: null-input option expects a boolean, got {other:?}"
                            )))
                        }
                    },
                );
            }
            "security" => {
                if security_definer.is_some() {
                    return Err(SQLError::Routine {
                        sqlstate: "42601".into(),
                        message: format!("{keyword}: conflicting or redundant security option"),
                    });
                }
                security_definer = Some(def_elem_bool(element, &format!("{keyword}: SECURITY"))?);
            }
            "leakproof" => {
                if leakproof.is_some() {
                    return Err(SQLError::Routine {
                        sqlstate: "42601".into(),
                        message: format!("{keyword}: conflicting or redundant leakproof option"),
                    });
                }
                leakproof = Some(def_elem_bool(element, &format!("{keyword}: LEAKPROOF"))?);
            }
            "parallel" => {
                if parallel.is_some() {
                    return Err(SQLError::Routine {
                        sqlstate: "42601".into(),
                        message: format!("{keyword}: conflicting or redundant parallel option"),
                    });
                }
                parallel = Some(match def_elem_string(element)?.as_str() {
                    "unsafe" => FunctionParallel::Unsafe,
                    "restricted" => FunctionParallel::Restricted,
                    "safe" => FunctionParallel::Safe,
                    other => {
                        return Err(SQLError::TypeMismatch(format!(
                            "{keyword}: invalid PARALLEL value `{other}`"
                        )))
                    }
                });
            }
            "support" => {
                if support.is_some() {
                    return Err(SQLError::Routine {
                        sqlstate: "42601".into(),
                        message: format!("{keyword}: conflicting or redundant support option"),
                    });
                }
                support = Some(compile_support_name(element, keyword)?);
            }
            "set" => config_actions.push(compile_routine_config_action(element, keyword)?),
            other => {
                return Err(SQLError::Unsupported(format!(
                    "{keyword}: action `{other}` is not supported"
                )))
            }
        }
    }
    if volatility.is_none()
        && strict.is_none()
        && security_definer.is_none()
        && leakproof.is_none()
        && parallel.is_none()
        && support.is_none()
        && config_actions.is_empty()
    {
        return Err(SQLError::Unsupported(format!(
            "{keyword}: no supported action"
        )));
    }
    Ok(AlterRoutineStmt {
        kind,
        name,
        arg_types,
        arg_type_references,
        volatility,
        strict,
        security_definer,
        leakproof,
        parallel,
        support,
        config_actions,
    })
}