pgevolve-core 0.4.3

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
//! `ALTER DEFAULT PRIVILEGES ... GRANT ...` — future-object grants.
//!
//! Decodes the options list to extract `FOR ROLE` targets and optional
//! `IN SCHEMA` scopes, then decodes the nested `GrantStmt` for privileges and
//! grantees. Produces one [`DefaultPrivilegeRule`] per (`target_role` × schema)
//! cross-product entry.
//!
//! REVOKE in source → [`ParseError::Structural`]. Missing `FOR ROLE` → error.

use pg_query::NodeEnum;
use pg_query::protobuf::{AlterDefaultPrivilegesStmt, ObjectType, RoleSpecType};

use crate::identifier::Identifier;
use crate::ir::catalog::Catalog;
use crate::ir::default_privileges::{DefaultPrivObjectType, DefaultPrivilegeRule};
use crate::ir::grant::{Grant, GrantTarget, Privilege};
use crate::parse::builder::shared;
use crate::parse::error::{ParseError, SourceLocation};

/// Apply an `ALTER DEFAULT PRIVILEGES` statement to the catalog.
///
/// The statement produces one [`DefaultPrivilegeRule`] per
/// (`target_role` × schema) cross-product. Each rule carries the full grants
/// decoded from the nested `GrantStmt.action`.
#[allow(clippy::too_many_lines)] // exhaustive `ALTER DEFAULT PRIVILEGES` decoder; one arm per object-type / action combination.
pub(crate) fn apply(
    s: &AlterDefaultPrivilegesStmt,
    cat: &mut Catalog,
    loc: &SourceLocation,
) -> Result<(), ParseError> {
    // Decode options: `FOR ROLE` and `IN SCHEMA`.
    let (target_roles, schemas) = decode_options(&s.options, loc)?;

    // FOR ROLE is required — no current_user fallback in source.
    if target_roles.is_empty() {
        return Err(ParseError::Structural {
            location: loc.clone(),
            message: "ALTER DEFAULT PRIVILEGES requires a FOR ROLE clause in source DDL; \
                      current_user-scoped defaults are not supported in source files"
                .into(),
        });
    }

    // Decode the nested GrantStmt (`action`).
    let action = s.action.as_ref().ok_or_else(|| ParseError::Structural {
        location: loc.clone(),
        message: "ALTER DEFAULT PRIVILEGES missing GRANT/REVOKE action".into(),
    })?;

    // Reject REVOKE in source.
    if !action.is_grant {
        return Err(ParseError::Structural {
            location: loc.clone(),
            message: "REVOKE in ALTER DEFAULT PRIVILEGES in source is not supported — \
                      revocations come from diff"
                .into(),
        });
    }

    // Reject GRANTED BY.
    if let Some(ref grantor) = action.grantor {
        let roletype = pg_query::protobuf::RoleSpecType::try_from(grantor.roletype)
            .unwrap_or(RoleSpecType::Undefined);
        if roletype != RoleSpecType::Undefined || !grantor.rolename.is_empty() {
            return Err(ParseError::Structural {
                location: loc.clone(),
                message: "ALTER DEFAULT PRIVILEGES ... GRANT ... GRANTED BY is not supported \
                          in source DDL (v0.3.1)"
                    .into(),
            });
        }
    }

    // Object type.
    let objtype = ObjectType::try_from(action.objtype).unwrap_or(ObjectType::Undefined);
    let default_obj_type = default_priv_obj_type(objtype, loc)?;

    // Privileges — expand GRANT ALL per object type.
    let privs: Vec<Privilege> = if action.privileges.is_empty() {
        all_privs_for_default(default_obj_type)
    } else {
        let mut out = Vec::new();
        for node in &action.privileges {
            let Some(NodeEnum::AccessPriv(ap)) = node.node.as_ref() else {
                return Err(ParseError::Structural {
                    location: loc.clone(),
                    message: format!(
                        "expected AccessPriv in ALTER DEFAULT PRIVILEGES privileges list, \
                         got {:?}",
                        node.node.as_ref().map(std::mem::discriminant)
                    ),
                });
            };
            if ap.priv_name.is_empty() {
                // ALL
                out.extend(all_privs_for_default(default_obj_type));
            } else {
                out.push(priv_from_keyword(&ap.priv_name, loc)?);
            }
        }
        out
    };

    // Grantees.
    let grantees = decode_grantees(&action.grantees, loc)?;

    // Build one rule per (target_role × schema) cross-product, merging into
    // any existing rule with the same key so that multiple
    // `ALTER DEFAULT PRIVILEGES FOR ROLE x GRANT ... TO ...` statements
    // accumulate their grants rather than silently overwriting each other.
    for target_role in &target_roles {
        let target_schemas: Vec<Option<Identifier>> = if schemas.is_empty() {
            vec![None]
        } else {
            schemas.iter().map(|s| Some(s.clone())).collect()
        };
        for schema in target_schemas {
            let new_grants: Vec<Grant> = grantees
                .iter()
                .flat_map(|grantee| {
                    privs.iter().map(move |&pv| Grant {
                        grantee: grantee.clone(),
                        privilege: pv,
                        with_grant_option: action.grant_option,
                        columns: None,
                    })
                })
                .collect();
            // Find an existing rule with the same (target_role, schema,
            // object_type) and extend it; push a fresh rule if none exists.
            let existing = cat.default_privileges.iter_mut().find(|r| {
                r.target_role == *target_role
                    && r.schema == schema
                    && r.object_type == default_obj_type
            });
            // Strip implicit grants from source so that source IR and live IR
            // remain in the same canonical form:
            //
            // 1. Self-grants (#34): `GRANT ... TO <target_role>` is a no-op —
            //    Postgres always grants the target_role its own implicit
            //    privileges on objects it creates. These are PG bookkeeping.
            //
            // 2. Implicit PUBLIC grants (#37): `GRANT USAGE ON TYPES TO PUBLIC`
            //    and `GRANT EXECUTE ON FUNCTIONS TO PUBLIC` are always present in
            //    `pg_default_acl.defaclacl` and are never user-revocable. The
            //    reader strips them too; declaring them in source causes a
            //    permanent phantom divergence.
            let new_grants: Vec<Grant> =
                crate::catalog::grants::strip_owner_self_grants(new_grants, target_role);
            let new_grants: Vec<Grant> =
                crate::catalog::grants::strip_public_implicit_grants(new_grants, default_obj_type);
            if let Some(rule) = existing {
                rule.grants.extend(new_grants);
            } else {
                cat.default_privileges.push(DefaultPrivilegeRule {
                    target_role: target_role.clone(),
                    schema,
                    object_type: default_obj_type,
                    grants: new_grants,
                });
            }
        }
    }

    Ok(())
}

// ─── Options decoding ─────────────────────────────────────────────────────────

/// Decode the `options` list of `AlterDefaultPrivilegesStmt`.
///
/// Returns `(target_roles, schemas)`. Schemas is empty if no `IN SCHEMA` was given.
fn decode_options(
    options: &[pg_query::protobuf::Node],
    loc: &SourceLocation,
) -> Result<(Vec<Identifier>, Vec<Identifier>), ParseError> {
    let mut target_roles: Vec<Identifier> = Vec::new();
    let mut schemas: Vec<Identifier> = Vec::new();

    for opt_node in options {
        let Some(NodeEnum::DefElem(de)) = opt_node.node.as_ref() else {
            return Err(ParseError::Structural {
                location: loc.clone(),
                message: format!(
                    "expected DefElem in ALTER DEFAULT PRIVILEGES options, got {:?}",
                    opt_node.node.as_ref().map(std::mem::discriminant)
                ),
            });
        };
        match de.defname.as_str() {
            "roles" => {
                // arg is a List of RoleSpec nodes.
                let arg_node = de
                    .arg
                    .as_ref()
                    .and_then(|a| a.node.as_ref())
                    .ok_or_else(|| ParseError::Structural {
                        location: loc.clone(),
                        message: "FOR ROLE DefElem missing arg".into(),
                    })?;
                let NodeEnum::List(list) = arg_node else {
                    return Err(ParseError::Structural {
                        location: loc.clone(),
                        message: format!(
                            "expected List in FOR ROLE DefElem arg, got {:?}",
                            std::mem::discriminant(arg_node)
                        ),
                    });
                };
                for item in &list.items {
                    let Some(NodeEnum::RoleSpec(rs)) = item.node.as_ref() else {
                        return Err(ParseError::Structural {
                            location: loc.clone(),
                            message: format!(
                                "expected RoleSpec in FOR ROLE list, got {:?}",
                                item.node.as_ref().map(std::mem::discriminant)
                            ),
                        });
                    };
                    target_roles.push(shared::ident(&rs.rolename, loc)?);
                }
            }
            "schemas" => {
                // arg is a List of String nodes.
                let arg_node = de
                    .arg
                    .as_ref()
                    .and_then(|a| a.node.as_ref())
                    .ok_or_else(|| ParseError::Structural {
                        location: loc.clone(),
                        message: "IN SCHEMA DefElem missing arg".into(),
                    })?;
                let NodeEnum::List(list) = arg_node else {
                    return Err(ParseError::Structural {
                        location: loc.clone(),
                        message: format!(
                            "expected List in IN SCHEMA DefElem arg, got {:?}",
                            std::mem::discriminant(arg_node)
                        ),
                    });
                };
                for item in &list.items {
                    let Some(NodeEnum::String(s)) = item.node.as_ref() else {
                        return Err(ParseError::Structural {
                            location: loc.clone(),
                            message: format!(
                                "expected String in IN SCHEMA list, got {:?}",
                                item.node.as_ref().map(std::mem::discriminant)
                            ),
                        });
                    };
                    schemas.push(shared::ident(&s.sval, loc)?);
                }
            }
            other => {
                return Err(ParseError::Structural {
                    location: loc.clone(),
                    message: format!(
                        "unknown ALTER DEFAULT PRIVILEGES option '{other}'; \
                         expected 'roles' or 'schemas'"
                    ),
                });
            }
        }
    }

    Ok((target_roles, schemas))
}

// ─── Privilege helpers ────────────────────────────────────────────────────────

/// Map an `ObjectType` to a [`DefaultPrivObjectType`].
fn default_priv_obj_type(
    objtype: ObjectType,
    loc: &SourceLocation,
) -> Result<DefaultPrivObjectType, ParseError> {
    match objtype {
        ObjectType::ObjectTable => Ok(DefaultPrivObjectType::Tables),
        ObjectType::ObjectSequence => Ok(DefaultPrivObjectType::Sequences),
        ObjectType::ObjectFunction | ObjectType::ObjectRoutine => {
            Ok(DefaultPrivObjectType::Functions)
        }
        ObjectType::ObjectType => Ok(DefaultPrivObjectType::Types),
        ObjectType::ObjectSchema => Ok(DefaultPrivObjectType::Schemas),
        other => Err(ParseError::Structural {
            location: loc.clone(),
            message: format!(
                "ALTER DEFAULT PRIVILEGES: unsupported object type {other:?}; \
                 expected TABLES, SEQUENCES, FUNCTIONS, TYPES, or SCHEMAS"
            ),
        }),
    }
}

/// Privileges applicable for GRANT ALL on a given `DefaultPrivObjectType`.
fn all_privs_for_default(kind: DefaultPrivObjectType) -> Vec<Privilege> {
    match kind {
        DefaultPrivObjectType::Tables => vec![
            Privilege::Select,
            Privilege::Insert,
            Privilege::Update,
            Privilege::Delete,
            Privilege::Truncate,
            Privilege::References,
            Privilege::Trigger,
        ],
        DefaultPrivObjectType::Sequences => {
            vec![Privilege::Usage, Privilege::Select, Privilege::Update]
        }
        DefaultPrivObjectType::Functions => vec![Privilege::Execute],
        DefaultPrivObjectType::Types => vec![Privilege::Usage],
        DefaultPrivObjectType::Schemas => vec![Privilege::Usage, Privilege::Create],
    }
}

/// Parse a SQL privilege keyword into [`Privilege`].
fn priv_from_keyword(kw: &str, loc: &SourceLocation) -> Result<Privilege, ParseError> {
    match kw.to_ascii_uppercase().as_str() {
        "SELECT" => Ok(Privilege::Select),
        "INSERT" => Ok(Privilege::Insert),
        "UPDATE" => Ok(Privilege::Update),
        "DELETE" => Ok(Privilege::Delete),
        "TRUNCATE" => Ok(Privilege::Truncate),
        "REFERENCES" => Ok(Privilege::References),
        "TRIGGER" => Ok(Privilege::Trigger),
        "USAGE" => Ok(Privilege::Usage),
        "EXECUTE" => Ok(Privilege::Execute),
        "CREATE" => Ok(Privilege::Create),
        other => Err(ParseError::Structural {
            location: loc.clone(),
            message: format!("unknown privilege keyword '{other}'"),
        }),
    }
}

/// Decode the grantees list from the nested `GrantStmt`.
fn decode_grantees(
    nodes: &[pg_query::protobuf::Node],
    loc: &SourceLocation,
) -> Result<Vec<GrantTarget>, ParseError> {
    let mut out = Vec::with_capacity(nodes.len());
    for n in nodes {
        let Some(NodeEnum::RoleSpec(rs)) = n.node.as_ref() else {
            return Err(ParseError::Structural {
                location: loc.clone(),
                message: format!(
                    "expected RoleSpec in GRANT grantees, got {:?}",
                    n.node.as_ref().map(std::mem::discriminant)
                ),
            });
        };
        let roletype = RoleSpecType::try_from(rs.roletype).unwrap_or(RoleSpecType::Undefined);
        let target = if roletype == RoleSpecType::RolespecPublic {
            GrantTarget::Public
        } else {
            GrantTarget::Role(shared::ident(&rs.rolename, loc)?)
        };
        out.push(target);
    }
    Ok(out)
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

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

    fn id(s: &str) -> Identifier {
        Identifier::from_unquoted(s).unwrap()
    }

    fn empty_cat() -> Catalog {
        Catalog::empty()
    }

    fn parse_adp(sql: &str) -> AlterDefaultPrivilegesStmt {
        let parsed = pg_query::parse(sql).expect("parses");
        let stmt = parsed
            .protobuf
            .stmts
            .into_iter()
            .next()
            .and_then(|raw| raw.stmt)
            .and_then(|n| n.node)
            .expect("stmt");
        let NodeEnum::AlterDefaultPrivilegesStmt(s) = stmt else {
            panic!("not AlterDefaultPrivilegesStmt")
        };
        s
    }

    #[test]
    fn in_schema_tables() {
        let mut cat = empty_cat();
        let s = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE x IN SCHEMA y GRANT SELECT ON TABLES TO z;",
        );
        apply(&s, &mut cat, &loc()).unwrap();
        assert_eq!(cat.default_privileges.len(), 1);
        let rule = &cat.default_privileges[0];
        assert_eq!(rule.target_role, id("x"));
        assert_eq!(rule.schema, Some(id("y")));
        assert_eq!(rule.object_type, DefaultPrivObjectType::Tables);
        assert_eq!(rule.grants.len(), 1);
        assert_eq!(rule.grants[0].privilege, Privilege::Select);
        assert_eq!(rule.grants[0].grantee, GrantTarget::Role(id("z")));
    }

    #[test]
    fn global_functions() {
        let mut cat = empty_cat();
        let s = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE owner_role GRANT EXECUTE ON FUNCTIONS TO app_role;",
        );
        apply(&s, &mut cat, &loc()).unwrap();
        assert_eq!(cat.default_privileges.len(), 1);
        let rule = &cat.default_privileges[0];
        assert_eq!(rule.target_role, id("owner_role"));
        assert_eq!(rule.schema, None);
        assert_eq!(rule.object_type, DefaultPrivObjectType::Functions);
        assert_eq!(rule.grants[0].privilege, Privilege::Execute);
    }

    #[test]
    fn for_role_required() {
        let mut cat = empty_cat();
        // Omit FOR ROLE — pg_query will parse this as current_user; the options
        // list will have no "roles" entry.
        let s = parse_adp("ALTER DEFAULT PRIVILEGES GRANT SELECT ON TABLES TO alice;");
        let err = apply(&s, &mut cat, &loc()).unwrap_err();
        assert!(
            matches!(err, ParseError::Structural { ref message, .. }
                if message.contains("FOR ROLE") || message.contains("for role") || message.contains("requires")),
            "expected FOR ROLE error, got: {err:?}"
        );
    }

    #[test]
    fn revoke_rejected() {
        let mut cat = empty_cat();
        let s = parse_adp("ALTER DEFAULT PRIVILEGES FOR ROLE x REVOKE SELECT ON TABLES FROM z;");
        let err = apply(&s, &mut cat, &loc()).unwrap_err();
        assert!(
            matches!(err, ParseError::Structural { ref message, .. }
                if message.contains("REVOKE") || message.contains("revoke")),
            "expected REVOKE error, got: {err:?}"
        );
    }

    #[test]
    fn grant_all_expansion_for_default_privileges() {
        let mut cat = empty_cat();
        let s =
            parse_adp("ALTER DEFAULT PRIVILEGES FOR ROLE x IN SCHEMA s GRANT ALL ON TABLES TO z;");
        apply(&s, &mut cat, &loc()).unwrap();
        assert_eq!(cat.default_privileges.len(), 1);
        let rule = &cat.default_privileges[0];
        // 7 table privileges: SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER
        assert_eq!(rule.grants.len(), 7);
        let privs: Vec<Privilege> = rule.grants.iter().map(|g| g.privilege).collect();
        assert!(privs.contains(&Privilege::Select));
        assert!(privs.contains(&Privilege::Insert));
        assert!(privs.contains(&Privilege::Update));
        assert!(privs.contains(&Privilege::Delete));
        assert!(privs.contains(&Privilege::Truncate));
        assert!(privs.contains(&Privilege::References));
        assert!(privs.contains(&Privilege::Trigger));
    }

    /// Regression for issue #34: self-grants in source SQL must be stripped.
    ///
    /// `ALTER DEFAULT PRIVILEGES FOR ROLE ops GRANT EXECUTE ON FUNCTIONS TO ops`
    /// is a no-op in Postgres — the `target_role` always has implicit EXECUTE on
    /// its own future functions. Declaring it in source causes a phantom
    /// divergence because the live catalog reader also strips self-grants (they
    /// are PG bookkeeping). By stripping here at parse time we keep source and
    /// live IR in the same canonical form and avoid spurious revoke/re-grant
    /// cycles.
    #[test]
    fn strips_target_role_self_grant_from_source_ir() {
        let mut cat = empty_cat();
        // Self-grant: ops grants EXECUTE to ops (self).
        let s = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE ops \
             GRANT EXECUTE ON FUNCTIONS TO ops;",
        );
        apply(&s, &mut cat, &loc()).unwrap();
        // The rule is created (empty grants list) rather than being silently dropped.
        // Empty-rules are filtered later in canonicalize; here we just verify
        // that the self-grant is not present.
        let rule = cat
            .default_privileges
            .iter()
            .find(|r| r.target_role == id("ops"));
        if let Some(rule) = rule {
            assert!(
                rule.grants.is_empty(),
                "self-grant ops/Execute must be stripped; got: {:?}",
                rule.grants
            );
        }
        // No rule at all is also acceptable (empty-grants rules may be elided).
    }

    /// Regression for issue #37: parser must strip the implicit Public/Usage grant
    /// when the user writes `GRANT USAGE ON TYPES TO PUBLIC` for any `target_role`.
    /// PG always has this entry in `defaclacl`; declaring it in source would cause
    /// a phantom divergence because the reader also strips it.
    #[test]
    fn strips_implicit_public_usage_on_types_from_source_ir() {
        let mut cat = empty_cat();
        let s = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE app_owner \
             GRANT USAGE ON TYPES TO PUBLIC;",
        );
        apply(&s, &mut cat, &loc()).unwrap();
        // Rule may be created with empty grants or not at all.
        let rule = cat
            .default_privileges
            .iter()
            .find(|r| r.target_role == id("app_owner"));
        if let Some(rule) = rule {
            assert!(
                rule.grants.is_empty(),
                "implicit Public/Usage on TYPES must be stripped; got: {:?}",
                rule.grants
            );
        }
    }

    /// Parser strips Public/Usage on TYPES but keeps explicit grants to other roles.
    #[test]
    fn strips_public_usage_on_types_but_keeps_others() {
        let mut cat = empty_cat();
        // Implicit grant (stripped) + explicit grant to readers (kept).
        let s1 = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE app_owner \
             GRANT USAGE ON TYPES TO PUBLIC;",
        );
        let s2 = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE app_owner \
             GRANT USAGE ON TYPES TO readers;",
        );
        apply(&s1, &mut cat, &loc()).unwrap();
        apply(&s2, &mut cat, &loc()).unwrap();
        let rule = cat
            .default_privileges
            .iter()
            .find(|r| r.target_role == id("app_owner"))
            .expect("rule should exist");
        assert_eq!(
            rule.grants.len(),
            1,
            "only readers/Usage should remain; got: {:?}",
            rule.grants
        );
        assert!(
            matches!(&rule.grants[0].grantee, GrantTarget::Role(r) if r.as_str() == "readers"),
            "remaining grant must be to readers; got: {:?}",
            rule.grants[0]
        );
    }

    /// Parser strips Public/Execute on FUNCTIONS.
    #[test]
    fn strips_implicit_public_execute_on_functions_from_source_ir() {
        let mut cat = empty_cat();
        let s = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE ops \
             GRANT EXECUTE ON FUNCTIONS TO PUBLIC;",
        );
        apply(&s, &mut cat, &loc()).unwrap();
        let rule = cat
            .default_privileges
            .iter()
            .find(|r| r.target_role == id("ops"));
        if let Some(rule) = rule {
            assert!(
                rule.grants.is_empty(),
                "implicit Public/Execute on FUNCTIONS must be stripped; got: {:?}",
                rule.grants
            );
        }
    }

    /// Self-grant is stripped even when other grantees are present.
    #[test]
    fn strips_self_grant_but_keeps_others() {
        let mut cat = empty_cat();
        // Two statements: grant to self (stripped) and grant to readers (kept).
        let s1 = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE ops \
             GRANT EXECUTE ON FUNCTIONS TO ops;",
        );
        let s2 = parse_adp(
            "ALTER DEFAULT PRIVILEGES FOR ROLE ops \
             GRANT EXECUTE ON FUNCTIONS TO readers;",
        );
        apply(&s1, &mut cat, &loc()).unwrap();
        apply(&s2, &mut cat, &loc()).unwrap();
        let rule = cat
            .default_privileges
            .iter()
            .find(|r| r.target_role == id("ops"))
            .expect("rule should exist");
        assert_eq!(
            rule.grants.len(),
            1,
            "only readers/Execute should remain; got: {:?}",
            rule.grants
        );
        assert!(
            matches!(&rule.grants[0].grantee, GrantTarget::Role(r) if r.as_str() == "readers"),
            "remaining grant must be to readers; got: {:?}",
            rule.grants[0]
        );
    }
}