pgevolve-core 0.4.6

Postgres declarative schema management — core library (parser, IR, diff, planner) powering the pgevolve CLI.
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
//! Source-side parser for `CREATE FUNCTION` and `CREATE PROCEDURE`.
//!
//! Both statements are represented in `pg_query` by a single
//! `CreateFunctionStmt` with an `is_procedure: bool` discriminant.
//! This builder dispatches on that flag and returns either a
//! [`Routine::Function`] or a [`Routine::Procedure`].
//!
//! **Body parsing (T2 stub)**: SQL-language bodies are canonicalized via
//! [`NormalizedBody::from_sql`]; PL/pgSQL bodies fall back to
//! [`NormalizedBody::empty`] because `pg_query` cannot parse PL/pgSQL.
//! T4 replaces the fallback with real PL/pgSQL AST parsing.

use pg_query::NodeEnum;
use pg_query::protobuf::{CreateFunctionStmt, FunctionParameterMode};

use crate::identifier::Identifier;
use crate::ir::function::{
    ArgMode, Function, FunctionArg, FunctionLanguage, NormalizedArgTypes, ParallelSafety,
    ReturnType, SecurityMode, TableColumn, Volatility,
};
use crate::ir::procedure::Procedure;
use crate::parse::builder::plpgsql;
use crate::parse::builder::shared;
use crate::parse::error::{ParseError, SourceLocation};
use crate::parse::normalize_body::NormalizedBody;
use crate::parse::normalize_expr;

/// Dispatch output for this builder.
#[derive(Debug)]
pub enum Routine {
    /// A `CREATE FUNCTION` statement.
    Function(Function),
    /// A `CREATE PROCEDURE` statement.
    Procedure(Procedure),
}

/// Build a [`Routine`] from a `CreateFunctionStmt` AST node.
///
/// * `default_schema` — used when the statement has no schema prefix and a
///   `-- @pgevolve schema=` directive is in effect.
/// * Unsupported languages (anything other than `sql` / `plpgsql`) are
///   rejected with a [`ParseError::Structural`] naming the bad language.
/// * Procedure-specific constraints: `VOLATILE/STABLE/IMMUTABLE`, `STRICT`,
///   `PARALLEL`, `LEAKPROOF`, `COST`, `ROWS`, and a return-type clause are
///   all rejected on procedures.
#[allow(clippy::too_many_lines)] // exhaustive walk of `CREATE FUNCTION`/`CREATE PROCEDURE` options; one arm per option kind.
pub(crate) fn build_function_or_procedure(
    stmt: &CreateFunctionStmt,
    default_schema: Option<&Identifier>,
    location: &SourceLocation,
) -> Result<Routine, ParseError> {
    let qname = shared::qname_from_string_list(&stmt.funcname, default_schema, location)?;
    let is_procedure = stmt.is_procedure;

    // ── Parameters ──────────────────────────────────────────────────────────
    let mut args: Vec<FunctionArg> = Vec::new();
    let mut table_columns: Vec<TableColumn> = Vec::new();

    for param_node in &stmt.parameters {
        let Some(NodeEnum::FunctionParameter(p)) = param_node.node.as_ref() else {
            return Err(ParseError::Structural {
                location: location.clone(),
                message: format!("CREATE FUNCTION/PROCEDURE {qname}: unexpected parameter node"),
            });
        };

        let raw_mode =
            FunctionParameterMode::try_from(p.mode).unwrap_or(FunctionParameterMode::Undefined);

        // TABLE mode parameters are collected separately for RETURNS TABLE.
        if raw_mode == FunctionParameterMode::FuncParamTable {
            let tn = p.arg_type.as_ref().ok_or_else(|| ParseError::Structural {
                location: location.clone(),
                message: format!("{qname}: TABLE column missing type"),
            })?;
            let ty = shared::type_name_to_column_type(tn, location)?;
            let name = if p.name.is_empty() {
                return Err(ParseError::Structural {
                    location: location.clone(),
                    message: format!("{qname}: TABLE column missing name"),
                });
            } else {
                shared::ident(&p.name, location)?
            };
            table_columns.push(TableColumn { name, ty });
            continue;
        }

        let mode = match raw_mode {
            FunctionParameterMode::FuncParamIn
            | FunctionParameterMode::FuncParamDefault
            | FunctionParameterMode::Undefined => ArgMode::In,
            FunctionParameterMode::FuncParamOut => ArgMode::Out,
            FunctionParameterMode::FuncParamInout => ArgMode::InOut,
            FunctionParameterMode::FuncParamVariadic => ArgMode::Variadic,
            FunctionParameterMode::FuncParamTable => unreachable!("handled above"),
        };

        let tn = p.arg_type.as_ref().ok_or_else(|| ParseError::Structural {
            location: location.clone(),
            message: format!("{qname}: parameter missing type"),
        })?;
        let ty = shared::type_name_to_column_type(tn, location)?;

        let name = if p.name.is_empty() {
            None
        } else {
            Some(shared::ident(&p.name, location)?)
        };

        // Default expression (stubbed normalize via from_pg_node)
        let default = if let Some(defexpr_boxed) = p.defexpr.as_ref() {
            let node_enum = defexpr_boxed
                .node
                .as_ref()
                .ok_or_else(|| ParseError::Structural {
                    location: location.clone(),
                    message: format!("{qname}: argument default expression is empty"),
                })?;
            Some(normalize_expr::from_pg_node(
                node_enum,
                Some(&ty),
                location,
            )?)
        } else {
            None
        };

        args.push(FunctionArg {
            name,
            mode,
            ty,
            default,
        });
    }

    // ── Options ──────────────────────────────────────────────────────────────
    let mut language: Option<FunctionLanguage> = None;
    let mut volatility: Option<Volatility> = None;
    let mut strict = false;
    let mut security: Option<SecurityMode> = None;
    let mut parallel: Option<ParallelSafety> = None;
    let mut leakproof = false;
    let mut cost: Option<f32> = None;
    let mut rows: Option<f32> = None;
    let mut body_text: Option<String> = None;

    for opt_node in &stmt.options {
        let Some(NodeEnum::DefElem(de)) = opt_node.node.as_ref() else {
            return Err(ParseError::Structural {
                location: location.clone(),
                message: format!("{qname}: unexpected option node"),
            });
        };

        match de.defname.as_str() {
            "language" => {
                let lang_str =
                    shared::def_elem_string(de).ok_or_else(|| ParseError::Structural {
                        location: location.clone(),
                        message: format!("{qname}: LANGUAGE option missing value"),
                    })?;
                language = Some(match lang_str.to_lowercase().as_str() {
                    "sql" => FunctionLanguage::Sql,
                    "plpgsql" => FunctionLanguage::PlPgSql,
                    other => {
                        return Err(ParseError::Structural {
                            location: location.clone(),
                            message: format!(
                                "{qname}: unsupported language {other:?} \
                                 (pgevolve v0.2 supports sql and plpgsql)"
                            ),
                        });
                    }
                });
            }
            "volatility" => {
                if is_procedure {
                    return Err(ParseError::Structural {
                        location: location.clone(),
                        message: format!(
                            "{qname}: VOLATILE/STABLE/IMMUTABLE is not valid on procedures"
                        ),
                    });
                }
                let v_str = shared::def_elem_string(de).ok_or_else(|| ParseError::Structural {
                    location: location.clone(),
                    message: format!("{qname}: volatility option missing value"),
                })?;
                volatility = Some(match v_str.to_lowercase().as_str() {
                    "immutable" => Volatility::Immutable,
                    "stable" => Volatility::Stable,
                    "volatile" => Volatility::Volatile,
                    other => {
                        return Err(ParseError::Structural {
                            location: location.clone(),
                            message: format!("{qname}: unknown volatility {other:?}"),
                        });
                    }
                });
            }
            "strict" => {
                if is_procedure {
                    return Err(ParseError::Structural {
                        location: location.clone(),
                        message: format!("{qname}: STRICT is not valid on procedures"),
                    });
                }
                strict = bool_from_def_elem(de);
            }
            "security" => {
                // PG encodes SECURITY DEFINER as defname="security" with
                // arg = Boolean(true); SECURITY INVOKER as Boolean(false).
                // Also accept Integer/String values for robustness.
                security = Some(match de.arg.as_ref().and_then(|a| a.node.as_ref()) {
                    Some(NodeEnum::Boolean(b)) => {
                        if b.boolval {
                            SecurityMode::Definer
                        } else {
                            SecurityMode::Invoker
                        }
                    }
                    Some(NodeEnum::Integer(i)) => {
                        if i.ival != 0 {
                            SecurityMode::Definer
                        } else {
                            SecurityMode::Invoker
                        }
                    }
                    Some(NodeEnum::String(s)) => match s.sval.to_lowercase().as_str() {
                        "invoker" => SecurityMode::Invoker,
                        "definer" => SecurityMode::Definer,
                        other => {
                            return Err(ParseError::Structural {
                                location: location.clone(),
                                message: format!("{qname}: unknown security mode {other:?}"),
                            });
                        }
                    },
                    None => SecurityMode::Invoker, // bare "security" without qualifier
                    _ => {
                        return Err(ParseError::Structural {
                            location: location.clone(),
                            message: format!("{qname}: SECURITY option has unexpected value"),
                        });
                    }
                });
            }
            "parallel" => {
                if is_procedure {
                    return Err(ParseError::Structural {
                        location: location.clone(),
                        message: format!("{qname}: PARALLEL is not valid on procedures"),
                    });
                }
                let p_str = shared::def_elem_string(de).ok_or_else(|| ParseError::Structural {
                    location: location.clone(),
                    message: format!("{qname}: PARALLEL option missing value"),
                })?;
                parallel = Some(match p_str.to_lowercase().as_str() {
                    "safe" => ParallelSafety::Safe,
                    "restricted" => ParallelSafety::Restricted,
                    "unsafe" => ParallelSafety::Unsafe,
                    other => {
                        return Err(ParseError::Structural {
                            location: location.clone(),
                            message: format!("{qname}: unknown parallel safety {other:?}"),
                        });
                    }
                });
            }
            "leakproof" => {
                if is_procedure {
                    return Err(ParseError::Structural {
                        location: location.clone(),
                        message: format!("{qname}: LEAKPROOF is not valid on procedures"),
                    });
                }
                leakproof = bool_from_def_elem(de);
            }
            "cost" => {
                if is_procedure {
                    return Err(ParseError::Structural {
                        location: location.clone(),
                        message: format!("{qname}: COST is not valid on procedures"),
                    });
                }
                // Raw parse: `ir::canon::filter_pg_defaults` strips the
                // PG-default value of 100 to None on both sides.
                cost = float_from_def_elem(de);
            }
            "rows" => {
                if is_procedure {
                    return Err(ParseError::Structural {
                        location: location.clone(),
                        message: format!("{qname}: ROWS is not valid on procedures"),
                    });
                }
                // Raw parse: `ir::canon::filter_pg_defaults` strips the
                // PG-default (1000 for SETOF, 0 otherwise) to None.
                rows = float_from_def_elem(de);
            }
            "as" => {
                // The body is the first element (the $$ string $$).
                // For sql_body-style functions, body comes via stmt.sql_body instead.
                body_text = Some(shared::def_elem_string(de).unwrap_or_default());
            }
            other => {
                return Err(ParseError::Structural {
                    location: location.clone(),
                    message: format!("{qname}: unsupported function option {other:?}"),
                });
            }
        }
    }

    let lang = language.unwrap_or(FunctionLanguage::Sql);

    // ── Body parsing ─────────────────────────────────────────────────────────
    // Delegate to the T4 PL/pgSQL body parser which handles both SQL and
    // PL/pgSQL languages, extracts dep edges, and detects COMMIT/ROLLBACK.
    let raw_body = body_text.as_deref().unwrap_or("").trim().to_string();
    let (body, body_deps, commits_in_body) = if raw_body.is_empty() {
        (NormalizedBody::empty(), vec![], false)
    } else {
        plpgsql::parse_routine_body(&raw_body, lang, &qname, location)?
    };

    if is_procedure {
        // Procedure: no return type clause allowed.
        if stmt.return_type.is_some() {
            return Err(ParseError::Structural {
                location: location.clone(),
                message: format!("{qname}: procedures cannot have a RETURNS clause"),
            });
        }

        let security = security.unwrap_or(SecurityMode::Invoker);

        return Ok(Routine::Procedure(Procedure {
            qname,
            args,
            language: lang,
            body,
            body_dependencies: body_deps,
            security,
            commits_in_body,
            comment: None,
            owner: None,
            grants: vec![],
        }));
    }

    // ── Return type ──────────────────────────────────────────────────────────
    let return_type = if !table_columns.is_empty() {
        // RETURNS TABLE(...) — collected from FuncParamTable parameters.
        ReturnType::Table {
            columns: table_columns,
        }
    } else if let Some(tn) = stmt.return_type.as_ref() {
        let type_str =
            shared::render_type_name_to_string(tn).ok_or_else(|| ParseError::Structural {
                location: location.clone(),
                message: format!("{qname}: could not stringify return type"),
            })?;
        match type_str.to_lowercase().as_str() {
            "trigger" => ReturnType::Trigger,
            "event_trigger" => ReturnType::EventTrigger,
            "void" => ReturnType::Void,
            _ => {
                let ty = shared::type_name_to_column_type(tn, location)?;
                if tn.setof {
                    ReturnType::SetOf { ty }
                } else {
                    ReturnType::Scalar { ty }
                }
            }
        }
    } else {
        return Err(ParseError::Structural {
            location: location.clone(),
            message: format!("{qname}: function is missing a RETURNS clause"),
        });
    };

    let arg_types_normalized = NormalizedArgTypes::from_args(&args);

    Ok(Routine::Function(Function {
        qname,
        args,
        arg_types_normalized,
        return_type,
        language: lang,
        body,
        body_dependencies: body_deps,
        volatility: volatility.unwrap_or(Volatility::Volatile),
        strict,
        security: security.unwrap_or(SecurityMode::Invoker),
        parallel: parallel.unwrap_or(ParallelSafety::Unsafe),
        leakproof,
        cost,
        rows,
        comment: None,
        owner: None,
        grants: vec![],
    }))
}

/// Extract a boolean value from a `DefElem.arg`, defaulting to `true` if
/// the arg is absent (bare keyword like `STRICT` or `LEAKPROOF`).
fn bool_from_def_elem(de: &pg_query::protobuf::DefElem) -> bool {
    let Some(arg) = de.arg.as_ref() else {
        return true; // bare keyword = true
    };
    match arg.node.as_ref() {
        Some(NodeEnum::Integer(i)) => i.ival != 0,
        _ => true,
    }
}

/// Extract a float cost/rows value from a `DefElem.arg`.
fn float_from_def_elem(de: &pg_query::protobuf::DefElem) -> Option<f32> {
    let arg = de.arg.as_ref()?;
    match arg.node.as_ref()? {
        NodeEnum::Float(f) => f.fval.parse::<f32>().ok(),
        #[allow(clippy::cast_precision_loss)]
        NodeEnum::Integer(i) => Some(i.ival as f32),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    use pg_query::NodeEnum as PgNodeEnum;

    fn loc() -> SourceLocation {
        SourceLocation::new(PathBuf::from("test.sql"), 1, 1)
    }

    fn parse_function(sql: &str) -> CreateFunctionStmt {
        let parsed = pg_query::parse(sql).expect("parses");
        let node = parsed
            .protobuf
            .stmts
            .into_iter()
            .next()
            .and_then(|r| r.stmt)
            .and_then(|n| n.node)
            .expect("stmt");
        let PgNodeEnum::CreateFunctionStmt(boxed) = node else {
            panic!("expected CreateFunctionStmt, got: {node:?}");
        };
        *boxed
    }

    fn build_fn(sql: &str) -> Function {
        let stmt = parse_function(sql);
        match build_function_or_procedure(&stmt, None, &loc()).expect("build") {
            Routine::Function(f) => f,
            Routine::Procedure(_) => panic!("expected Function"),
        }
    }

    fn build_proc(sql: &str) -> Procedure {
        let stmt = parse_function(sql);
        match build_function_or_procedure(&stmt, None, &loc()).expect("build") {
            Routine::Procedure(p) => p,
            Routine::Function(_) => panic!("expected Procedure"),
        }
    }

    #[test]
    fn simple_sql_function() {
        let f = build_fn(
            "CREATE FUNCTION app.double(x integer) RETURNS integer \
             LANGUAGE sql IMMUTABLE STRICT AS $$ SELECT x * 2 $$;",
        );
        assert_eq!(f.qname.to_string(), "app.double");
        assert_eq!(f.args.len(), 1);
        assert_eq!(
            f.args[0]
                .name
                .as_ref()
                .map(crate::identifier::Identifier::as_str),
            Some("x")
        );
        assert_eq!(f.args[0].mode, ArgMode::In);
        assert!(matches!(
            f.return_type,
            ReturnType::Scalar {
                ty: crate::ir::column_type::ColumnType::Integer
            }
        ));
        assert_eq!(f.language, FunctionLanguage::Sql);
        assert!(matches!(f.volatility, Volatility::Immutable));
        assert!(f.strict);
    }

    #[test]
    fn plpgsql_function_body_parsed() {
        let f = build_fn(
            "CREATE FUNCTION app.greet(name text) RETURNS text \
             LANGUAGE plpgsql AS $$ BEGIN RETURN 'hello'; END $$;",
        );
        assert_eq!(f.qname.to_string(), "app.greet");
        assert_eq!(f.language, FunctionLanguage::PlPgSql);
        // T4: body is now parsed; canonical text should be non-empty.
        assert!(
            !f.body.canonical_text().is_empty(),
            "PL/pgSQL body should be canonicalized, got empty string"
        );
    }

    #[test]
    fn unqualified_uses_default_schema() {
        let stmt = parse_function(
            "CREATE FUNCTION double(x integer) RETURNS integer \
             LANGUAGE sql AS $$ SELECT x $$;",
        );
        let app = Identifier::from_unquoted("app").unwrap();
        let Routine::Function(f) = build_function_or_procedure(&stmt, Some(&app), &loc()).unwrap()
        else {
            panic!()
        };
        assert_eq!(f.qname.to_string(), "app.double");
    }

    #[test]
    fn unsupported_language_rejected() {
        let stmt = parse_function("CREATE FUNCTION app.f() RETURNS void LANGUAGE plperl AS $$ $$;");
        let err = build_function_or_procedure(&stmt, None, &loc()).unwrap_err();
        let msg = match &err {
            ParseError::Structural { message, .. } => message.clone(),
            other => panic!("expected Structural, got {other:?}"),
        };
        assert!(msg.contains("plperl"), "should name bad language: {msg}");
    }

    #[test]
    fn procedure_builds() {
        let p = build_proc(
            "CREATE PROCEDURE app.do_work() \
             LANGUAGE plpgsql AS $$ BEGIN NULL; END $$;",
        );
        assert_eq!(p.qname.to_string(), "app.do_work");
        assert!(p.args.is_empty());
        assert_eq!(p.language, FunctionLanguage::PlPgSql);
    }

    #[test]
    fn procedure_rejects_volatility() {
        let stmt = parse_function(
            "CREATE PROCEDURE app.p() LANGUAGE plpgsql VOLATILE AS $$ BEGIN NULL; END $$;",
        );
        let err = build_function_or_procedure(&stmt, None, &loc()).unwrap_err();
        let msg = match &err {
            ParseError::Structural { message, .. } => message.clone(),
            other => panic!("expected Structural, got {other:?}"),
        };
        assert!(
            msg.contains("VOLATILE") || msg.contains("STABLE") || msg.contains("IMMUTABLE"),
            "msg: {msg}"
        );
    }

    #[test]
    fn procedure_rejects_return_type() {
        // pg_query rejects CREATE PROCEDURE ... RETURNS at the grammar level,
        // so the builder's defensive check is unreachable via parsed SQL. We
        // construct a synthetic CreateFunctionStmt with is_procedure=true and
        // return_type=Some(...) to exercise the rejection path directly.
        use pg_query::NodeEnum;
        use pg_query::protobuf::{CreateFunctionStmt, Node, TypeName};

        // Build the type-name list for "app.proc".
        let funcname = vec![
            Node {
                node: Some(NodeEnum::String(pg_query::protobuf::String {
                    sval: "app".into(),
                })),
            },
            Node {
                node: Some(NodeEnum::String(pg_query::protobuf::String {
                    sval: "proc".into(),
                })),
            },
        ];
        // Build a return-type TypeName for "integer".
        let return_type = TypeName {
            names: vec![Node {
                node: Some(NodeEnum::String(pg_query::protobuf::String {
                    sval: "integer".into(),
                })),
            }],
            type_oid: 0,
            setof: false,
            pct_type: false,
            typmods: vec![],
            typemod: -1,
            array_bounds: vec![],
            location: 0,
        };

        let stmt = CreateFunctionStmt {
            is_procedure: true,
            replace: false,
            funcname,
            parameters: vec![],
            return_type: Some(return_type),
            options: vec![],
            sql_body: None,
        };

        let err = build_function_or_procedure(&stmt, None, &loc()).unwrap_err();
        let msg = match &err {
            ParseError::Structural { message, .. } => message.clone(),
            other => panic!("expected Structural, got {other:?}"),
        };
        let lower = msg.to_lowercase();
        assert!(
            lower.contains("return") || lower.contains("returns"),
            "expected a 'returns/return-type' rejection message; got: {msg}",
        );
    }

    #[test]
    fn function_with_default_arg() {
        let f = build_fn(
            "CREATE FUNCTION app.greet(name text DEFAULT 'world') RETURNS text \
             LANGUAGE sql AS $$ SELECT 'hello ' || name $$;",
        );
        assert_eq!(f.args.len(), 1);
        assert!(f.args[0].default.is_some(), "should have a default");
    }

    #[test]
    fn security_definer() {
        let f = build_fn(
            "CREATE FUNCTION app.f() RETURNS void LANGUAGE sql SECURITY DEFINER \
             AS $$ SELECT NULL $$;",
        );
        assert!(matches!(f.security, SecurityMode::Definer));
    }
}