pgmt 0.4.8

PostgreSQL migration tool that keeps your schema files as the source of truth
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
//! Fetch grants/privileges from PostgreSQL system catalogs
use anyhow::Result;
use sqlx::postgres::PgConnection;
use tracing::info;

use super::id::{DbObjectId, DependsOn};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GranteeType {
    Role(String),
    Public,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ObjectType {
    Table {
        schema: String,
        name: String,
    },
    View {
        schema: String,
        name: String,
    },
    Schema {
        name: String,
    },
    Function {
        schema: String,
        name: String,
        arguments: String,
    },
    Procedure {
        schema: String,
        name: String,
        arguments: String,
    },
    Aggregate {
        schema: String,
        name: String,
        arguments: String,
    },
    Sequence {
        schema: String,
        name: String,
    },
    Type {
        schema: String,
        name: String,
    },
    Domain {
        schema: String,
        name: String,
    },
}

impl ObjectType {
    pub fn db_object_id(&self) -> DbObjectId {
        match self {
            ObjectType::Table { schema, name } => DbObjectId::Table {
                schema: schema.clone(),
                name: name.clone(),
            },
            ObjectType::View { schema, name } => DbObjectId::View {
                schema: schema.clone(),
                name: name.clone(),
            },
            ObjectType::Schema { name } => DbObjectId::Schema { name: name.clone() },
            ObjectType::Function {
                schema,
                name,
                arguments,
            } => DbObjectId::Function {
                schema: schema.clone(),
                name: name.clone(),
                arguments: arguments.clone(),
            },
            ObjectType::Procedure {
                schema,
                name,
                arguments,
            } => DbObjectId::Function {
                schema: schema.clone(),
                name: name.clone(),
                arguments: arguments.clone(),
            },
            ObjectType::Aggregate {
                schema,
                name,
                arguments,
            } => DbObjectId::Aggregate {
                schema: schema.clone(),
                name: name.clone(),
                arguments: arguments.clone(),
            },
            ObjectType::Sequence { schema, name } => DbObjectId::Sequence {
                schema: schema.clone(),
                name: name.clone(),
            },
            ObjectType::Type { schema, name } => DbObjectId::Type {
                schema: schema.clone(),
                name: name.clone(),
            },
            ObjectType::Domain { schema, name } => DbObjectId::Domain {
                schema: schema.clone(),
                name: name.clone(),
            },
        }
    }

    /// Returns the schema this object belongs to.
    /// For Schema objects, returns the schema name itself.
    pub fn schema(&self) -> &str {
        match self {
            ObjectType::Table { schema, .. } => schema,
            ObjectType::View { schema, .. } => schema,
            ObjectType::Schema { name } => name,
            ObjectType::Function { schema, .. } => schema,
            ObjectType::Procedure { schema, .. } => schema,
            ObjectType::Aggregate { schema, .. } => schema,
            ObjectType::Sequence { schema, .. } => schema,
            ObjectType::Type { schema, .. } => schema,
            ObjectType::Domain { schema, .. } => schema,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Grant {
    pub grantee: GranteeType,
    pub object: ObjectType,
    pub privileges: Vec<String>, // e.g., ["SELECT", "INSERT"]
    pub with_grant_option: bool,
    pub depends_on: Vec<DbObjectId>,
    pub object_owner: String, // Owner role name for this object
    /// Whether this grant came from the default ACL (NULL ACL in pg_catalog).
    /// true = object uses PostgreSQL defaults (e.g., PUBLIC has EXECUTE on functions)
    /// false = object has explicit ACL (grants/revokes have been made)
    pub is_default_acl: bool,
}

impl Grant {
    pub fn id(&self) -> String {
        // Create a unique identifier for this grant
        let grantee_str = match &self.grantee {
            GranteeType::Role(name) => name.clone(),
            GranteeType::Public => "public".to_string(),
        };

        let object_str = match &self.object {
            ObjectType::Table { schema, name } => format!("table:{}.{}", schema, name),
            ObjectType::View { schema, name } => format!("view:{}.{}", schema, name),
            ObjectType::Schema { name } => format!("schema:{}", name),
            ObjectType::Function {
                schema,
                name,
                arguments,
            } => format!("function:{}.{}({})", schema, name, arguments),
            ObjectType::Procedure {
                schema,
                name,
                arguments,
            } => format!("procedure:{}.{}({})", schema, name, arguments),
            ObjectType::Aggregate {
                schema,
                name,
                arguments,
            } => format!("aggregate:{}.{}({})", schema, name, arguments),
            ObjectType::Sequence { schema, name } => format!("sequence:{}.{}", schema, name),
            ObjectType::Type { schema, name } => format!("type:{}.{}", schema, name),
            ObjectType::Domain { schema, name } => format!("domain:{}.{}", schema, name),
        };

        format!("{}@{}", grantee_str, object_str)
    }
}

impl DependsOn for Grant {
    fn id(&self) -> DbObjectId {
        DbObjectId::Grant { id: self.id() }
    }

    fn depends_on(&self) -> &[DbObjectId] {
        &self.depends_on
    }
}

pub async fn fetch(conn: &mut PgConnection) -> Result<Vec<Grant>> {
    let mut grants = Vec::new();

    // Fetch table privileges
    info!("Fetching table grants...");
    grants.extend(fetch_table_privileges(&mut *conn).await?);

    // Fetch view privileges
    info!("Fetching view grants...");
    grants.extend(fetch_view_privileges(&mut *conn).await?);

    // Fetch schema privileges
    info!("Fetching schema grants...");
    grants.extend(fetch_schema_privileges(&mut *conn).await?);

    // Fetch function privileges
    info!("Fetching function grants...");
    grants.extend(fetch_function_privileges(&mut *conn).await?);

    // Fetch sequence privileges
    info!("Fetching sequence grants...");
    grants.extend(fetch_sequence_privileges(&mut *conn).await?);

    // Fetch type privileges
    info!("Fetching type grants...");
    grants.extend(fetch_type_privileges(&mut *conn).await?);

    Ok(grants)
}

async fn fetch_table_privileges(conn: &mut PgConnection) -> Result<Vec<Grant>> {
    let rows = sqlx::query!(
        r#"
        SELECT
            n.nspname as "schema_name!",
            c.relname as "table_name!",
            CASE
                WHEN acl.grantee = 0 THEN 'PUBLIC'
                ELSE r.rolname
            END as "grantee!",
            acl.privilege_type as "privilege_type!",
            CASE WHEN acl.is_grantable THEN 'YES' ELSE 'NO' END as "is_grantable!",
            owner_role.rolname as "object_owner!",
            CASE WHEN c.relacl IS NULL THEN true ELSE false END as "is_default_acl!"
        FROM pg_class c
        JOIN pg_namespace n ON c.relnamespace = n.oid
        JOIN pg_roles owner_role ON c.relowner = owner_role.oid,
        LATERAL aclexplode(COALESCE(c.relacl, acldefault('r', c.relowner))) AS acl
        LEFT JOIN pg_roles r ON r.oid = acl.grantee
        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
          AND c.relkind = 'r' -- tables only (views handled separately)
          -- Exclude tables that belong to extensions
          AND NOT EXISTS (
              SELECT 1 FROM pg_depend dep
              WHERE dep.objid = c.oid
              AND dep.deptype = 'e'
          )
        ORDER BY n.nspname, c.relname, CASE WHEN acl.grantee = 0 THEN 'PUBLIC' ELSE r.rolname END, acl.privilege_type
        "#
    )
    .fetch_all(&mut *conn)
    .await?;

    let mut result = Vec::new();
    let mut current_grant: Option<Grant> = None;

    for row in rows {
        let grantee = if row.grantee == "PUBLIC" {
            GranteeType::Public
        } else {
            GranteeType::Role(row.grantee.clone())
        };

        let object = ObjectType::Table {
            schema: row.schema_name.clone(),
            name: row.table_name.clone(),
        };

        let with_grant_option = row.is_grantable == "YES";

        // Group privileges by grantee and object
        match &mut current_grant {
            Some(grant)
                if grant.grantee == grantee
                    && grant.object == object
                    && grant.with_grant_option == with_grant_option =>
            {
                grant.privileges.push(row.privilege_type);
            }
            _ => {
                if let Some(grant) = current_grant.take() {
                    result.push(grant);
                }

                // Grants only depend on the target object, not the grantee role
                // (roles are assumed to exist externally to pgmt)
                let depends_on = vec![object.db_object_id()];

                current_grant = Some(Grant {
                    grantee,
                    object,
                    privileges: vec![row.privilege_type],
                    with_grant_option,
                    depends_on,
                    object_owner: row.object_owner.clone(),
                    is_default_acl: row.is_default_acl,
                });
            }
        }
    }

    if let Some(grant) = current_grant {
        result.push(grant);
    }

    Ok(result)
}

async fn fetch_view_privileges(conn: &mut PgConnection) -> Result<Vec<Grant>> {
    let rows = sqlx::query!(
        r#"
        SELECT
            n.nspname as "schema_name!",
            c.relname as "view_name!",
            CASE
                WHEN acl.grantee = 0 THEN 'PUBLIC'
                ELSE r.rolname
            END as "grantee!",
            acl.privilege_type as "privilege_type!",
            CASE WHEN acl.is_grantable THEN 'YES' ELSE 'NO' END as "is_grantable!",
            owner_role.rolname as "object_owner!",
            CASE WHEN c.relacl IS NULL THEN true ELSE false END as "is_default_acl!"
        FROM pg_class c
        JOIN pg_namespace n ON c.relnamespace = n.oid
        JOIN pg_roles owner_role ON c.relowner = owner_role.oid,
        LATERAL aclexplode(COALESCE(c.relacl, acldefault('r', c.relowner))) AS acl
        LEFT JOIN pg_roles r ON r.oid = acl.grantee
        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
          AND c.relkind IN ('v', 'm') -- views and materialized views
          -- Exclude views that belong to extensions
          AND NOT EXISTS (
              SELECT 1 FROM pg_depend dep
              WHERE dep.objid = c.oid
              AND dep.deptype = 'e'
          )
        ORDER BY n.nspname, c.relname, CASE WHEN acl.grantee = 0 THEN 'PUBLIC' ELSE r.rolname END, acl.privilege_type
        "#
    )
    .fetch_all(&mut *conn)
    .await?;

    let mut result = Vec::new();
    let mut current_grant: Option<Grant> = None;

    for row in rows {
        let grantee = if row.grantee == "PUBLIC" {
            GranteeType::Public
        } else {
            GranteeType::Role(row.grantee.clone())
        };

        let object = ObjectType::View {
            schema: row.schema_name.clone(),
            name: row.view_name.clone(),
        };

        let with_grant_option = row.is_grantable == "YES";

        // Group privileges by grantee and object
        match &mut current_grant {
            Some(grant)
                if grant.grantee == grantee
                    && grant.object == object
                    && grant.with_grant_option == with_grant_option =>
            {
                grant.privileges.push(row.privilege_type);
            }
            _ => {
                if let Some(grant) = current_grant.take() {
                    result.push(grant);
                }

                // Grants only depend on the target object, not the grantee role
                // (roles are assumed to exist externally to pgmt)
                let depends_on = vec![object.db_object_id()];

                current_grant = Some(Grant {
                    grantee,
                    object,
                    privileges: vec![row.privilege_type],
                    with_grant_option,
                    depends_on,
                    object_owner: row.object_owner.clone(),
                    is_default_acl: row.is_default_acl,
                });
            }
        }
    }

    if let Some(grant) = current_grant {
        result.push(grant);
    }

    Ok(result)
}

async fn fetch_schema_privileges(conn: &mut PgConnection) -> Result<Vec<Grant>> {
    let rows = sqlx::query!(
        r#"
        SELECT
            n.nspname as "schema_name!",
            CASE
                WHEN acl.grantee = 0 THEN 'PUBLIC'
                ELSE r.rolname
            END as "grantee!",
            acl.privilege_type as "privilege_type!",
            CASE WHEN acl.is_grantable THEN 'YES' ELSE 'NO' END as "is_grantable!",
            owner_role.rolname as "object_owner!",
            CASE WHEN n.nspacl IS NULL THEN true ELSE false END as "is_default_acl!"
        FROM pg_namespace n
        JOIN pg_roles owner_role ON n.nspowner = owner_role.oid,
        LATERAL aclexplode(COALESCE(n.nspacl, acldefault('n', n.nspowner))) AS acl
        LEFT JOIN pg_roles r ON r.oid = acl.grantee
        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast', 'public')
          AND NOT n.nspname LIKE 'pg_temp_%'
          AND NOT n.nspname LIKE 'pg_toast_temp_%'
        ORDER BY n.nspname, CASE WHEN acl.grantee = 0 THEN 'PUBLIC' ELSE r.rolname END, acl.privilege_type
        "#
    )
    .fetch_all(&mut *conn)
    .await?;

    let mut result = Vec::new();
    let mut current_grant: Option<Grant> = None;

    for row in rows {
        let grantee = if row.grantee == "PUBLIC" {
            GranteeType::Public
        } else {
            GranteeType::Role(row.grantee.clone())
        };

        let object = ObjectType::Schema {
            name: row.schema_name.clone(),
        };

        let with_grant_option = row.is_grantable == "YES";

        match &mut current_grant {
            Some(grant)
                if grant.grantee == grantee
                    && grant.object == object
                    && grant.with_grant_option == with_grant_option =>
            {
                grant.privileges.push(row.privilege_type);
            }
            _ => {
                if let Some(grant) = current_grant.take() {
                    result.push(grant);
                }

                // Grants only depend on the target object, not the grantee role
                // (roles are assumed to exist externally to pgmt)
                let depends_on = vec![object.db_object_id()];

                current_grant = Some(Grant {
                    grantee,
                    object,
                    privileges: vec![row.privilege_type],
                    with_grant_option,
                    depends_on,
                    object_owner: row.object_owner.clone(),
                    is_default_acl: row.is_default_acl,
                });
            }
        }
    }

    if let Some(grant) = current_grant {
        result.push(grant);
    }

    Ok(result)
}

async fn fetch_function_privileges(conn: &mut PgConnection) -> Result<Vec<Grant>> {
    let rows = sqlx::query!(
        r#"
        SELECT
            n.nspname as "schema_name!",
            p.proname as "function_name!",
            p.prokind::text as "prokind!",
            pg_get_function_identity_arguments(p.oid) as "arguments!",
            CASE
                WHEN acl.grantee = 0 THEN 'PUBLIC'
                ELSE r.rolname
            END as "grantee!",
            acl.privilege_type as "privilege_type!",
            CASE WHEN acl.is_grantable THEN 'YES' ELSE 'NO' END as "is_grantable!",
            owner_role.rolname as "object_owner!",
            CASE WHEN p.proacl IS NULL THEN true ELSE false END as "is_default_acl!"
        FROM pg_proc p
        JOIN pg_namespace n ON p.pronamespace = n.oid
        JOIN pg_roles owner_role ON p.proowner = owner_role.oid,
        LATERAL aclexplode(COALESCE(p.proacl, acldefault('f', p.proowner))) AS acl
        LEFT JOIN pg_roles r ON r.oid = acl.grantee
        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
          -- Exclude functions that belong to extensions
          AND NOT EXISTS (
              SELECT 1 FROM pg_depend dep
              WHERE dep.objid = p.oid
              AND dep.deptype = 'e'
          )
        ORDER BY n.nspname, p.proname, pg_get_function_identity_arguments(p.oid), CASE WHEN acl.grantee = 0 THEN 'PUBLIC' ELSE r.rolname END, acl.privilege_type
        "#
    )
    .fetch_all(&mut *conn)
    .await?;

    let mut result = Vec::new();
    let mut current_grant: Option<Grant> = None;

    for row in rows {
        let grantee = if row.grantee == "PUBLIC" {
            GranteeType::Public
        } else {
            GranteeType::Role(row.grantee.clone())
        };

        // Use appropriate variant based on prokind:
        // 'a' = aggregate, 'p' = procedure, others = function
        let object = match row.prokind.as_str() {
            "a" => ObjectType::Aggregate {
                schema: row.schema_name.clone(),
                name: row.function_name.clone(),
                arguments: row.arguments.clone(),
            },
            "p" => ObjectType::Procedure {
                schema: row.schema_name.clone(),
                name: row.function_name.clone(),
                arguments: row.arguments.clone(),
            },
            _ => ObjectType::Function {
                schema: row.schema_name.clone(),
                name: row.function_name.clone(),
                arguments: row.arguments.clone(),
            },
        };

        let with_grant_option = row.is_grantable == "YES";

        match &mut current_grant {
            Some(grant)
                if grant.grantee == grantee
                    && grant.object == object
                    && grant.with_grant_option == with_grant_option =>
            {
                grant.privileges.push(row.privilege_type);
            }
            _ => {
                if let Some(grant) = current_grant.take() {
                    result.push(grant);
                }

                // Grants only depend on the target object, not the grantee role
                // (roles are assumed to exist externally to pgmt)
                let depends_on = vec![object.db_object_id()];

                current_grant = Some(Grant {
                    grantee,
                    object,
                    privileges: vec![row.privilege_type],
                    with_grant_option,
                    depends_on,
                    object_owner: row.object_owner.clone(),
                    is_default_acl: row.is_default_acl,
                });
            }
        }
    }

    if let Some(grant) = current_grant {
        result.push(grant);
    }

    Ok(result)
}

async fn fetch_sequence_privileges(conn: &mut PgConnection) -> Result<Vec<Grant>> {
    let rows = sqlx::query!(
        r#"
        SELECT
            n.nspname as "schema_name!",
            c.relname as "sequence_name!",
            CASE
                WHEN acl.grantee = 0 THEN 'PUBLIC'
                ELSE r.rolname
            END as "grantee!",
            acl.privilege_type as "privilege_type!",
            CASE WHEN acl.is_grantable THEN 'YES' ELSE 'NO' END as "is_grantable!",
            CASE WHEN c.relacl IS NULL THEN true ELSE false END as "is_default_acl!",
            owner_role.rolname as "object_owner!"
        FROM pg_class c
        JOIN pg_namespace n ON c.relnamespace = n.oid
        JOIN pg_roles owner_role ON c.relowner = owner_role.oid,
        LATERAL aclexplode(COALESCE(c.relacl, acldefault('S', c.relowner))) AS acl
        LEFT JOIN pg_roles r ON r.oid = acl.grantee
        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
          AND c.relkind = 'S' -- sequences only
          -- Exclude sequences that belong to extensions
          AND NOT EXISTS (
              SELECT 1 FROM pg_depend dep
              WHERE dep.objid = c.oid
              AND dep.deptype = 'e'
          )
        ORDER BY n.nspname, c.relname, CASE WHEN acl.grantee = 0 THEN 'PUBLIC' ELSE r.rolname END, acl.privilege_type
        "#
    )
    .fetch_all(&mut *conn)
    .await?;

    let mut result = Vec::new();
    let mut current_grant: Option<Grant> = None;

    for row in rows {
        let grantee = if row.grantee == "PUBLIC" {
            GranteeType::Public
        } else {
            GranteeType::Role(row.grantee.clone())
        };

        let object = ObjectType::Sequence {
            schema: row.schema_name.clone(),
            name: row.sequence_name.clone(),
        };

        let with_grant_option = row.is_grantable == "YES";

        match &mut current_grant {
            Some(grant)
                if grant.grantee == grantee
                    && grant.object == object
                    && grant.with_grant_option == with_grant_option =>
            {
                grant.privileges.push(row.privilege_type);
            }
            _ => {
                if let Some(grant) = current_grant.take() {
                    result.push(grant);
                }

                // Grants only depend on the target object, not the grantee role
                // (roles are assumed to exist externally to pgmt)
                let depends_on = vec![object.db_object_id()];

                current_grant = Some(Grant {
                    grantee,
                    object,
                    privileges: vec![row.privilege_type],
                    with_grant_option,
                    depends_on,
                    object_owner: row.object_owner.clone(),
                    is_default_acl: row.is_default_acl,
                });
            }
        }
    }

    if let Some(grant) = current_grant {
        result.push(grant);
    }

    Ok(result)
}

async fn fetch_type_privileges(conn: &mut PgConnection) -> Result<Vec<Grant>> {
    let rows = sqlx::query!(
        r#"
        SELECT
            n.nspname as "schema_name!",
            t.typname as "type_name!",
            t.typtype as "type_kind!",
            CASE
                WHEN acl.grantee = 0 THEN 'PUBLIC'
                ELSE r.rolname
            END as "grantee!",
            acl.privilege_type as "privilege_type!",
            CASE WHEN acl.is_grantable THEN 'YES' ELSE 'NO' END as "is_grantable!",
            owner_role.rolname as "object_owner!",
            CASE WHEN t.typacl IS NULL THEN true ELSE false END as "is_default_acl!"
        FROM pg_type t
        JOIN pg_namespace n ON t.typnamespace = n.oid
        JOIN pg_roles owner_role ON t.typowner = owner_role.oid,
        LATERAL aclexplode(COALESCE(t.typacl, acldefault('T', t.typowner))) AS acl
        LEFT JOIN pg_roles r ON r.oid = acl.grantee
        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
          AND t.typtype IN ('e', 'd', 'c')  -- Only enums, domains, and composite types
          AND NOT EXISTS (
              -- Exclude composite types that are automatically created for tables
              SELECT 1 FROM pg_class c
              WHERE c.relname = t.typname
                AND c.relnamespace = t.typnamespace
                AND c.relkind IN ('r', 'v', 'm', 'S')
          )
          AND NOT t.typname LIKE '\_%'  -- Exclude array types (they start with underscore)
          -- Exclude types that belong to extensions
          AND NOT EXISTS (
              SELECT 1 FROM pg_depend dep
              WHERE dep.objid = t.oid
              AND dep.deptype = 'e'
          )
        ORDER BY n.nspname, t.typname, CASE WHEN acl.grantee = 0 THEN 'PUBLIC' ELSE r.rolname END, acl.privilege_type
        "#
    )
    .fetch_all(&mut *conn)
    .await?;

    let mut result = Vec::new();
    let mut current_grant: Option<Grant> = None;

    for row in rows {
        let grantee = if row.grantee == "PUBLIC" {
            GranteeType::Public
        } else {
            GranteeType::Role(row.grantee.clone())
        };

        // Distinguish between domains and other types (typtype: 'd' for domain)
        let object = if row.type_kind == b'd' as i8 {
            ObjectType::Domain {
                schema: row.schema_name.clone(),
                name: row.type_name.clone(),
            }
        } else {
            ObjectType::Type {
                schema: row.schema_name.clone(),
                name: row.type_name.clone(),
            }
        };

        let with_grant_option = row.is_grantable == "YES";

        match &mut current_grant {
            Some(grant)
                if grant.grantee == grantee
                    && grant.object == object
                    && grant.with_grant_option == with_grant_option =>
            {
                grant.privileges.push(row.privilege_type);
            }
            _ => {
                if let Some(grant) = current_grant.take() {
                    result.push(grant);
                }

                // Grants only depend on the target object, not the grantee role
                // (roles are assumed to exist externally to pgmt)
                let depends_on = vec![object.db_object_id()];

                current_grant = Some(Grant {
                    grantee,
                    object,
                    privileges: vec![row.privilege_type],
                    with_grant_option,
                    depends_on,
                    object_owner: row.object_owner.clone(),
                    is_default_acl: row.is_default_acl,
                });
            }
        }
    }

    if let Some(grant) = current_grant {
        result.push(grant);
    }

    Ok(result)
}