pgmt 0.5.1

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
//! Shared SQL rendering for GRANT and REVOKE statements
//!
//! This module provides consistent grant rendering across both schema generation
//! and migration operations to ensure identical SQL output.

use crate::catalog::grant::{Grant, GranteeType};
use crate::catalog::id::DbObjectId;
use crate::diff::operations::ColumnGrants;
use crate::render::quote_ident;
use std::collections::{BTreeMap, BTreeSet};

/// Render a grantee for the `TO`/`FROM` clause: a quoted role name, or `PUBLIC`.
fn render_grantee(grantee: &GranteeType) -> String {
    match grantee {
        GranteeType::Role(name) => quote_ident(name),
        GranteeType::Public => "PUBLIC".to_string(),
    }
}

/// Render a complete GRANT statement for the given grant.
///
/// This function handles all PostgreSQL grant object types:
/// - Tables and views (without object type keyword)
/// - Schemas, functions, sequences, types (with object type keyword)
/// - Role and PUBLIC grantees
/// - WITH GRANT OPTION clause
/// - Proper SQL formatting and identifier quoting
pub fn render_grant_statement(grant: &Grant) -> String {
    let grant_option = if grant.with_grant_option {
        " WITH GRANT OPTION"
    } else {
        ""
    };

    let (privileges, object_clause) = render_privileges_and_object(grant);

    format!(
        "GRANT {} ON {} TO {}{};",
        privileges,
        object_clause,
        render_grantee(&grant.grantee),
        grant_option
    )
}

/// Render a complete REVOKE statement for the given grant.
pub fn render_revoke_statement(grant: &Grant) -> String {
    let (privileges, object_clause) = render_privileges_and_object(grant);

    format!(
        "REVOKE {} ON {} FROM {};",
        privileges,
        object_clause,
        render_grantee(&grant.grantee)
    )
}

/// Render a folded column GRANT covering many columns of one relation in a
/// single statement: `GRANT SELECT (a, b), UPDATE (a) ON "s"."t" TO role [WITH GRANT OPTION];`
pub fn render_column_grant_statement(cg: &ColumnGrants) -> String {
    let grant_option = if cg.with_grant_option {
        " WITH GRANT OPTION"
    } else {
        ""
    };

    format!(
        "GRANT {} ON {} TO {}{};",
        render_column_privilege_list(&cg.privilege_columns),
        render_grant_object_clause(&cg.relation),
        render_grantee(&cg.grantee),
        grant_option
    )
}

/// Render the REVOKE counterpart of [`render_column_grant_statement`].
pub fn render_column_revoke_statement(cg: &ColumnGrants) -> String {
    format!(
        "REVOKE {} ON {} FROM {};",
        render_column_privilege_list(&cg.privilege_columns),
        render_grant_object_clause(&cg.relation),
        render_grantee(&cg.grantee)
    )
}

/// Render a `privilege (columns)` list like `SELECT (a, b), UPDATE (a)`.
/// Privileges and columns come out sorted (driven by `BTreeMap`/`BTreeSet`),
/// so the same grant set always renders identically.
fn render_column_privilege_list(privilege_columns: &BTreeMap<String, BTreeSet<String>>) -> String {
    privilege_columns
        .iter()
        .map(|(privilege, columns)| {
            let cols = columns
                .iter()
                .map(|c| quote_ident(c))
                .collect::<Vec<_>>()
                .join(", ");
            format!("{} ({})", privilege, cols)
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// Render the privilege list and object clause for a grant. Column grants attach
/// the column to each privilege (`SELECT (col), UPDATE (col)`) and reference the
/// bare relation; all other objects list privileges plainly.
fn render_privileges_and_object(grant: &Grant) -> (String, String) {
    if let Some(column) = grant.target.column_name() {
        // Column grants attach the column to each privilege and reference the bare relation.
        let col = quote_ident(column);
        let privileges = grant
            .privileges
            .iter()
            .map(|p| format!("{} ({})", p, col))
            .collect::<Vec<_>>()
            .join(", ");
        let (schema, table) = grant.target.schema_and_name();
        let object_clause = format!("{}.{}", quote_ident(&schema), quote_ident(&table));
        return (privileges, object_clause);
    }
    (
        grant.privileges.join(", "),
        render_grant_object_clause(&grant.target.object),
    )
}

/// Render the object clause for GRANT/REVOKE statements.
///
/// PostgreSQL GRANT syntax rules:
/// - Tables and views: No object type keyword (just schema.name)
/// - Other objects: Require object type keyword (e.g., SCHEMA name, FUNCTION schema.name)
pub fn render_grant_object_clause(object: &DbObjectId) -> String {
    match object {
        // Tables and views don't require a keyword.
        DbObjectId::Table { schema, name } | DbObjectId::View { schema, name } => {
            format!("{}.{}", quote_ident(schema), quote_ident(name))
        }
        DbObjectId::Schema { name } => format!("SCHEMA {}", quote_ident(name)),
        DbObjectId::Function {
            schema,
            name,
            arguments,
        } => format!(
            "FUNCTION {}.{}({})",
            quote_ident(schema),
            quote_ident(name),
            arguments
        ),
        DbObjectId::Procedure {
            schema,
            name,
            arguments,
        } => format!(
            "PROCEDURE {}.{}({})",
            quote_ident(schema),
            quote_ident(name),
            arguments
        ),
        // PostgreSQL grants on aggregates use the FUNCTION keyword, not AGGREGATE.
        DbObjectId::Aggregate {
            schema,
            name,
            arguments,
        } => format!(
            "FUNCTION {}.{}({})",
            quote_ident(schema),
            quote_ident(name),
            arguments
        ),
        DbObjectId::Sequence { schema, name } => {
            format!("SEQUENCE {}.{}", quote_ident(schema), quote_ident(name))
        }
        DbObjectId::Type { schema, name } => {
            format!("TYPE {}.{}", quote_ident(schema), quote_ident(name))
        }
        DbObjectId::Domain { schema, name } => {
            format!("DOMAIN {}.{}", quote_ident(schema), quote_ident(name))
        }
        // Columns are handled by render_privileges_and_object; the rest are not
        // grantable object kinds.
        DbObjectId::Index { .. }
        | DbObjectId::Constraint { .. }
        | DbObjectId::Trigger { .. }
        | DbObjectId::Policy { .. }
        | DbObjectId::Extension { .. }
        | DbObjectId::Operator { .. }
        | DbObjectId::Cast { .. }
        | DbObjectId::Grant { .. }
        | DbObjectId::Comment { .. }
        | DbObjectId::Column { .. } => {
            unreachable!("not a grantable object kind: {object}")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::catalog::target::AttrTarget;

    #[test]
    fn test_render_grant_on_table() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Table {
                schema: "public".to_string(),
                name: "users".to_string(),
            }),
            grantee: GranteeType::Role("app_user".to_string()),
            privileges: vec!["SELECT".to_string(), "INSERT".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT SELECT, INSERT ON \"public\".\"users\" TO \"app_user\";"
        );
    }

    #[test]
    fn test_render_grant_on_view_no_view_keyword() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::View {
                schema: "public".to_string(),
                name: "current_subscriptions".to_string(),
            }),
            grantee: GranteeType::Role("postgres".to_string()),
            privileges: vec!["SELECT".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        // Should NOT contain "VIEW" keyword
        assert_eq!(
            sql,
            "GRANT SELECT ON \"public\".\"current_subscriptions\" TO \"postgres\";"
        );
        assert!(!sql.contains("VIEW"));
    }

    #[test]
    fn test_render_grant_on_view_all_privileges() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::View {
                schema: "public".to_string(),
                name: "current_subscriptions".to_string(),
            }),
            grantee: GranteeType::Role("postgres".to_string()),
            privileges: vec![
                "DELETE".to_string(),
                "INSERT".to_string(),
                "REFERENCES".to_string(),
                "SELECT".to_string(),
                "TRIGGER".to_string(),
                "TRUNCATE".to_string(),
                "UPDATE".to_string(),
            ],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        // Should NOT contain "VIEW" keyword even with all privileges
        assert_eq!(
            sql,
            "GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON \"public\".\"current_subscriptions\" TO \"postgres\";"
        );
        assert!(!sql.contains("VIEW"));
    }

    #[test]
    fn test_render_grant_on_schema() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Schema {
                name: "analytics".to_string(),
            }),
            grantee: GranteeType::Role("data_analyst".to_string()),
            privileges: vec!["USAGE".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT USAGE ON SCHEMA \"analytics\" TO \"data_analyst\";"
        );
    }

    #[test]
    fn test_render_grant_on_function() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Function {
                schema: "public".to_string(),
                name: "calculate_total".to_string(),
                arguments: "integer, numeric".to_string(),
            }),
            grantee: GranteeType::Role("app_user".to_string()),
            privileges: vec!["EXECUTE".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT EXECUTE ON FUNCTION \"public\".\"calculate_total\"(integer, numeric) TO \"app_user\";"
        );
    }

    #[test]
    fn test_render_grant_on_procedure() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Procedure {
                schema: "public".to_string(),
                name: "analyze_database".to_string(),
                arguments: "".to_string(),
            }),
            grantee: GranteeType::Role("app_user".to_string()),
            privileges: vec!["EXECUTE".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT EXECUTE ON PROCEDURE \"public\".\"analyze_database\"() TO \"app_user\";"
        );
    }

    #[test]
    fn test_render_grant_on_aggregate() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Aggregate {
                schema: "public".to_string(),
                name: "array_agg_custom".to_string(),
                arguments: "integer".to_string(),
            }),
            grantee: GranteeType::Role("app_user".to_string()),
            privileges: vec!["EXECUTE".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        // PostgreSQL grants on aggregates use FUNCTION keyword, not AGGREGATE
        assert_eq!(
            sql,
            "GRANT EXECUTE ON FUNCTION \"public\".\"array_agg_custom\"(integer) TO \"app_user\";"
        );
    }

    #[test]
    fn test_render_grant_with_grant_option() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Table {
                schema: "public".to_string(),
                name: "orders".to_string(),
            }),
            grantee: GranteeType::Role("manager".to_string()),
            privileges: vec!["ALL".to_string()],
            with_grant_option: true,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT ALL ON \"public\".\"orders\" TO \"manager\" WITH GRANT OPTION;"
        );
    }

    #[test]
    fn test_render_grant_to_public() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::View {
                schema: "public".to_string(),
                name: "public_stats".to_string(),
            }),
            grantee: GranteeType::Public,
            privileges: vec!["SELECT".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT SELECT ON \"public\".\"public_stats\" TO PUBLIC;"
        );
    }

    #[test]
    fn test_render_revoke_statement() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Table {
                schema: "public".to_string(),
                name: "sensitive_data".to_string(),
            }),
            grantee: GranteeType::Role("temp_user".to_string()),
            privileges: vec!["SELECT".to_string(), "INSERT".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_revoke_statement(&grant);
        assert_eq!(
            sql,
            "REVOKE SELECT, INSERT ON \"public\".\"sensitive_data\" FROM \"temp_user\";"
        );
    }

    #[test]
    fn test_render_grant_on_sequence() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Sequence {
                schema: "public".to_string(),
                name: "users_id_seq".to_string(),
            }),
            grantee: GranteeType::Role("app_user".to_string()),
            privileges: vec!["USAGE".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT USAGE ON SEQUENCE \"public\".\"users_id_seq\" TO \"app_user\";"
        );
    }

    #[test]
    fn test_render_grant_on_column() {
        let grant = Grant {
            target: AttrTarget::column(
                DbObjectId::Table {
                    schema: "public".to_string(),
                    name: "users".to_string(),
                },
                "email",
            ),
            grantee: GranteeType::Role("app_user".to_string()),
            privileges: vec!["SELECT".to_string(), "UPDATE".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT SELECT (\"email\"), UPDATE (\"email\") ON \"public\".\"users\" TO \"app_user\";"
        );
    }

    #[test]
    fn test_render_revoke_on_column() {
        let grant = Grant {
            target: AttrTarget::column(
                DbObjectId::Table {
                    schema: "public".to_string(),
                    name: "users".to_string(),
                },
                "ssn",
            ),
            grantee: GranteeType::Role("app_user".to_string()),
            privileges: vec!["SELECT".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_revoke_statement(&grant);
        assert_eq!(
            sql,
            "REVOKE SELECT (\"ssn\") ON \"public\".\"users\" FROM \"app_user\";"
        );
    }

    #[test]
    fn test_render_grant_on_type() {
        let grant = Grant {
            target: AttrTarget::object(DbObjectId::Type {
                schema: "public".to_string(),
                name: "status_enum".to_string(),
            }),
            grantee: GranteeType::Role("app_user".to_string()),
            privileges: vec!["USAGE".to_string()],
            with_grant_option: false,
            depends_on: vec![],
            object_owner: "postgres".to_string(),
            is_default_acl: false,
        };

        let sql = render_grant_statement(&grant);
        assert_eq!(
            sql,
            "GRANT USAGE ON TYPE \"public\".\"status_enum\" TO \"app_user\";"
        );
    }

    fn column_grants_fixture(with_grant_option: bool) -> ColumnGrants {
        let mut privilege_columns: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
        privilege_columns.insert(
            "INSERT".to_string(),
            ["a", "b", "c"].iter().map(|s| s.to_string()).collect(),
        );
        privilege_columns.insert(
            "UPDATE".to_string(),
            ["a", "b"].iter().map(|s| s.to_string()).collect(),
        );
        ColumnGrants {
            grantee: GranteeType::Role("app_user".to_string()),
            relation: DbObjectId::Table {
                schema: "public".to_string(),
                name: "t".to_string(),
            },
            with_grant_option,
            privilege_columns,
            depends_on: vec![],
            rep_id: "app_user@column:public.t.a".to_string(),
        }
    }

    #[test]
    fn test_render_folded_column_grant() {
        // Privileges and columns are sorted; one statement covers every column.
        let sql = render_column_grant_statement(&column_grants_fixture(false));
        assert_eq!(
            sql,
            "GRANT INSERT (\"a\", \"b\", \"c\"), UPDATE (\"a\", \"b\") ON \"public\".\"t\" TO \"app_user\";"
        );
    }

    #[test]
    fn test_render_folded_column_grant_with_grant_option() {
        let sql = render_column_grant_statement(&column_grants_fixture(true));
        assert!(
            sql.ends_with("TO \"app_user\" WITH GRANT OPTION;"),
            "got: {sql}"
        );
    }

    #[test]
    fn test_render_folded_column_revoke() {
        let sql = render_column_revoke_statement(&column_grants_fixture(false));
        assert_eq!(
            sql,
            "REVOKE INSERT (\"a\", \"b\", \"c\"), UPDATE (\"a\", \"b\") ON \"public\".\"t\" FROM \"app_user\";"
        );
    }
}