Skip to main content

demesne_postgres/
drift.rs

1use crate::{Error, query_error};
2use demesne_emit_sql::{Execute, Manifest, Object, POLICY_ROLE, granted_to_public, objects, revoked_from_public};
3use demesne_runtime::quote_literal;
4use postgres::{Client, Transaction};
5use std::collections::{BTreeMap, BTreeSet};
6
7/// How a live object differs from the spec's.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
9#[non_exhaustive]
10pub enum DriftKind {
11    /// The spec creates it and the database has no such object.
12    Missing,
13    /// Both have it, with different definitions.
14    Changed,
15    /// The spec's statement for it does not compile against the live database.
16    Invalid,
17    /// The database has it where the spec governs, and the spec does not create it.
18    Orphan,
19    /// An allow-list entry that no live orphan matches.
20    Stale,
21    /// A role other than the owner may execute a function the SQL revokes from PUBLIC, or default privileges grant new
22    /// functions to one. The detail gives the statement that takes it back.
23    Granted,
24}
25
26impl DriftKind {
27    /// The label `demesne diff` prints for it.
28    #[must_use]
29    pub fn label(self) -> &'static str {
30        match self {
31            Self::Missing => "MISSING",
32            Self::Changed => "CHANGED",
33            Self::Invalid => "INVALID",
34            Self::Orphan => "ORPHAN",
35            Self::Stale => "STALE",
36            Self::Granted => "GRANTED",
37        }
38    }
39}
40
41/// One difference between the live database and the spec's SQL.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Finding {
44    /// What kind of difference it is.
45    pub kind: DriftKind,
46    /// The object, such as `policy notes_select on public.notes` or `function auth.f(text)`.
47    pub object: String,
48    /// What differs, or what to do about it.
49    pub detail: String,
50}
51
52/// The roles a deployment grants the manifest's `grantable` functions to, which [`drift`] accepts as holding them.
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct Grantees {
55    roles: Vec<String>,
56    grantable: BTreeSet<String>,
57}
58
59impl Grantees {
60    /// Accepts each of `roles`, a role's name as Postgres stores it, holding `EXECUTE` on a function `manifest` lists as
61    /// grantable. Its grant of any other function the SQL revokes, and every default privilege, are still reported.
62    ///
63    /// # Errors
64    ///
65    /// A role is empty; or is PUBLIC, which holds exactly the functions the SQL grants to PUBLIC; or is the role every
66    /// policy is written for, since a grantable function answers for any id; or `manifest` records no lists of who may
67    /// run each function.
68    pub fn new(manifest: &Manifest, roles: &[String]) -> Result<Self, Error> {
69        if let Some(why) = roles.iter().find_map(|role| no_grantee(role)) {
70            return Err(Error::grantee(why));
71        }
72        let Some(lists) = &manifest.execute else {
73            return Err(Error::sql("the manifest records no lists of who may run each function, so none is grantable"));
74        };
75        let mut roles = roles.to_vec();
76        roles.sort();
77        roles.dedup();
78        Ok(Grantees { roles, grantable: lists.grantable.clone() })
79    }
80}
81
82/// Every difference between the live database and the spec's SQL, and how many objects match.
83#[derive(Debug, Clone, Default, PartialEq, Eq)]
84pub struct Drift {
85    /// The differences: tables, policies, functions, then triggers, each in the order the SQL creates them, then orphans and stale allow entries.
86    pub findings: Vec<Finding>,
87    /// Policies whose live definition is the generated one.
88    pub policies: usize,
89    /// Functions whose live definition is the generated one.
90    pub functions: usize,
91    /// Triggers whose live definition is the generated one.
92    pub triggers: usize,
93}
94
95/// Compares the live database with `sql`, the spec's whole SQL, in both directions.
96///
97/// Policies are compared by command, roles, permissive, `USING` and `WITH CHECK`, and functions and triggers by their whole definition. A function is also changed when PUBLIC may execute it live and the SQL revokes that, or may not and the SQL grants it. Where the SQL revokes a function from PUBLIC, each other role but its owner that may execute it live is reported as granted, unless the function is grantable and the role is one of `grantees`, and so is each default privilege that grants new functions in a definer schema, or in every schema, to a role other than the one whose functions it covers. Orphans are the policies on a governed table, and the functions in a definer schema or triggers calling them, that the SQL does not create.
98///
99/// Each generated object is created as a temporary copy and read back, so both sides are compared as Postgres deparses them. Nothing outside the session's temporary schema is created, and the transaction is rolled back. An `allow` entry is an orphan's object text, such as `function auth.f(text)`, to leave unreported; an entry that matches no orphan is reported as stale.
100///
101/// # Errors
102///
103/// The SQL creates an object the manifest does not record, or a catalog query fails.
104pub fn drift(client: &mut Client, sql: &str, allow: &[String], grantees: &Grantees) -> Result<Drift, Error> {
105    let objs = objects(sql).map_err(|e| Error::sql(e.to_string()))?;
106    let revoked = revoked_from_public(sql).into_iter().map(|f| {
107        let said = if grantees.grantable.contains(&f) { Execute::Grantable } else { Execute::Revoked };
108        (f, said)
109    });
110    let execute = revoked.chain(granted_to_public(sql).into_iter().map(|f| (f, Execute::Public))).collect();
111    compare(client, &objs, &execute, allow, &grantees.roles).map_err(Error::query)
112}
113
114fn compare(
115    client: &mut Client,
116    objs: &[(Object, String)],
117    execute: &BTreeMap<String, Execute>,
118    allow: &[String],
119    grantees: &[String],
120) -> Result<Drift, String> {
121    let mut tx = client.transaction().map_err(|e| query_error(&e))?;
122    tx.batch_execute("SET LOCAL check_function_bodies = off; SELECT set_config('search_path', current_setting('search_path') || ', pg_temp', true)")
123        .map_err(|e| query_error(&e))?;
124    let mut c = Comparison {
125        objs,
126        execute,
127        grantees,
128        live: BTreeMap::new(),
129        shadow: BTreeMap::new(),
130        governed: BTreeSet::new(),
131        scratch: BTreeMap::new(),
132        invalid: BTreeMap::new(),
133        schemas: Vec::new(),
134        out: Drift::default(),
135        orphans: Vec::new(),
136    };
137    c.shadow_tables(&mut tx)?;
138    c.create_generated(&mut tx);
139    tx.batch_execute("SET LOCAL search_path = ''").map_err(|e| query_error(&e))?;
140    c.policies(&mut tx)?;
141    c.functions(&mut tx)?;
142    c.default_privileges(&mut tx)?;
143    c.triggers(&mut tx)?;
144    tx.rollback().map_err(|e| query_error(&e))?;
145    Ok(c.finish(allow))
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
149struct PolicyDef {
150    cmd: String,
151    permissive: bool,
152    roles: Vec<String>,
153    using: String,
154    check: String,
155}
156
157struct Comparison<'a> {
158    objs: &'a [(Object, String)],
159    execute: &'a BTreeMap<String, Execute>,
160    grantees: &'a [String],
161    live: BTreeMap<String, u32>,
162    shadow: BTreeMap<String, (String, u32)>,
163    governed: BTreeSet<String>,
164    scratch: BTreeMap<Object, String>,
165    invalid: BTreeMap<Object, String>,
166    schemas: Vec<u32>,
167    out: Drift,
168    orphans: Vec<Finding>,
169}
170
171impl Comparison<'_> {
172    fn found(&mut self, kind: DriftKind, object: String, detail: String) {
173        self.out.findings.push(Finding { kind, object, detail });
174    }
175
176    fn shadow_tables(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
177        let mut tables = BTreeSet::new();
178        for (o, _) in self.objs {
179            match o {
180                Object::Policy { table, .. } | Object::Rls(table) => {
181                    tables.insert(table.clone());
182                    self.governed.insert(table.clone());
183                }
184                Object::Trigger { table, .. } => {
185                    tables.insert(table.clone());
186                }
187                _ => {}
188            }
189        }
190        let mut used = BTreeSet::new();
191        for (i, t) in tables.into_iter().enumerate() {
192            let row = tx
193                .query_one(
194                    "SELECT to_regclass($1)::oid, (SELECT string_agg(format('%I %s', attname, format_type(atttypid, atttypmod)), ', ' ORDER BY attnum)
195                       FROM pg_attribute WHERE attrelid = to_regclass($1) AND attnum > 0 AND NOT attisdropped)",
196                    &[&t],
197                )
198                .map_err(|e| query_error(&e))?;
199            let Some(oid) = row.get::<_, Option<u32>>(0) else {
200                self.found(DriftKind::Missing, format!("table {t}"), "the spec governs it, but the database has no such table".into());
201                continue;
202            };
203            let bare = t.rsplit_once('.').map_or(t.as_str(), |(_, b)| b).to_string();
204            let name = if used.insert(bare.clone()) { bare } else { format!("demesne_shadow_{i}") };
205            let cols: Option<String> = row.get(1);
206            tx.batch_execute(&format!("CREATE TEMP TABLE {name} ({})", cols.unwrap_or_default())).map_err(|e| query_error(&e))?;
207            let shadow_oid: u32 =
208                tx.query_one(&format!("SELECT {}::regclass::oid", quote_literal(&format!("pg_temp.{name}"))), &[]).map_err(|e| query_error(&e))?.get(0);
209            self.live.insert(t.clone(), oid);
210            self.shadow.insert(t, (name, shadow_oid));
211        }
212        Ok(())
213    }
214
215    fn create_generated(&mut self, tx: &mut Transaction<'_>) {
216        for (i, (o, stmt)) in self.objs.iter().enumerate() {
217            let scratch = match o {
218                Object::Function(sig) => {
219                    let name = format!("pg_temp.demesne_fn_{i}");
220                    self.scratch.insert(o.clone(), format!("{name}{}", arguments(sig)));
221                    renamed(stmt, &name)
222                }
223                Object::Policy { table, .. } | Object::Trigger { table, .. } => {
224                    self.shadow.get(table).and_then(|(name, _)| retarget(stmt, table, &format!("pg_temp.{name}")))
225                }
226                _ => None,
227            };
228            let Some(scratch) = scratch else { continue };
229            if let Err(e) = attempt(tx, &scratch) {
230                self.invalid.insert(o.clone(), e);
231            }
232        }
233    }
234
235    fn policies(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
236        let mut by_oid: BTreeMap<u32, (String, bool)> = self.live.iter().map(|(t, oid)| (*oid, (t.clone(), false))).collect();
237        by_oid.extend(self.shadow.iter().map(|(t, (_, oid))| (*oid, (t.clone(), true))));
238        let oids: Vec<u32> = by_oid.keys().copied().collect();
239        let rows = tx
240            .query(
241                "SELECT pol.polrelid, pol.polname::text, pol.polcmd::text, pol.polpermissive,
242                        ARRAY(SELECT CASE WHEN r = 0 THEN 'public' ELSE pg_get_userbyid(r)::text END FROM unnest(pol.polroles) r ORDER BY 1),
243                        coalesce(pg_get_expr(pol.polqual, pol.polrelid), ''), coalesce(pg_get_expr(pol.polwithcheck, pol.polrelid), '')
244                   FROM pg_policy pol WHERE pol.polrelid = ANY($1)",
245                &[&oids],
246            )
247            .map_err(|e| query_error(&e))?;
248        let mut live = BTreeMap::new();
249        let mut generated = BTreeMap::new();
250        for row in rows {
251            let Some((table, is_shadow)) = by_oid.get(&row.get::<_, u32>(0)) else { continue };
252            let def =
253                PolicyDef { cmd: command(&row.get::<_, String>(2)).into(), permissive: row.get(3), roles: row.get(4), using: row.get(5), check: row.get(6) };
254            let side = if *is_shadow { &mut generated } else { &mut live };
255            side.insert((table.clone(), row.get::<_, String>(1)), def);
256        }
257        let mut wanted = BTreeSet::new();
258        for (o, _) in self.objs {
259            let Object::Policy { table, name } = o else { continue };
260            let key = (table.clone(), name.clone());
261            wanted.insert(key.clone());
262            let object = format!("policy {name} on {table}");
263            if !self.live.contains_key(table) {
264                continue;
265            }
266            if let Some(e) = self.invalid.get(o).cloned() {
267                self.found(DriftKind::Invalid, object, format!("the generated policy does not compile against the live database: {e}"));
268                continue;
269            }
270            match (live.get(&key), generated.get(&key)) {
271                (None, _) => self.found(DriftKind::Missing, object, "generated but not live (apply it)".into()),
272                (Some(l), Some(g)) if l != g => self.found(DriftKind::Changed, object, policy_change(l, g)),
273                _ => self.out.policies += 1,
274            }
275        }
276        for (table, name) in live.keys() {
277            if self.governed.contains(table) && !wanted.contains(&(table.clone(), name.clone())) {
278                self.orphans.push(Finding {
279                    kind: DriftKind::Orphan,
280                    object: format!("policy {name} on {table}"),
281                    detail: "live on a governed table but not generated (remove it, or model it)".into(),
282                });
283            }
284        }
285        Ok(())
286    }
287
288    fn functions(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
289        let mut schemas = BTreeSet::new();
290        let mut generated_oids: Vec<u32> = Vec::new();
291        for (o, _) in self.objs {
292            let Object::Function(sig) = o else { continue };
293            let object = format!("function {sig}");
294            let row = tx.query_one("SELECT to_regnamespace($1)::oid, to_regprocedure($2)::oid", &[&schema_of(sig), sig]).map_err(|e| query_error(&e))?;
295            schemas.extend(row.get::<_, Option<u32>>(0));
296            let live_oid = row.get::<_, Option<u32>>(1);
297            generated_oids.extend(live_oid);
298            if let Some(e) = self.invalid.get(o).cloned() {
299                self.found(DriftKind::Invalid, object, format!("the generated function does not compile against the live database: {e}"));
300                continue;
301            }
302            let Some(live_oid) = live_oid else {
303                self.found(DriftKind::Missing, object, "generated but not live (apply it)".into());
304                continue;
305            };
306            let said = self.execute.get(sig).copied();
307            let mut off = match said {
308                Some(said) if public_right(tx, live_oid)? != for_public(said) => Some(said),
309                _ => None,
310            };
311            if let Some(said) = off {
312                let detail = match said {
313                    Execute::Public => "PUBLIC may not execute it, and the generated SQL grants that (re-apply it)".to_string(),
314                    Execute::Revoked | Execute::Grantable => "PUBLIC may execute it, and the generated SQL revokes that (re-apply it)".to_string(),
315                };
316                self.found(DriftKind::Changed, object.clone(), detail);
317            }
318            if let Some(said @ (Execute::Revoked | Execute::Grantable)) = said
319                && self.grants_of_a_revoked_function(tx, sig, &object, live_oid, said)?
320            {
321                off = off.or(Some(said));
322            }
323            let scratch = self.scratch.get(o).cloned().unwrap_or_default();
324            let defs = tx
325                .query_one("SELECT pg_get_functiondef($1), pg_get_functiondef(to_regprocedure($2)::oid)", &[&live_oid, &scratch])
326                .map_err(|e| query_error(&e))?;
327            let (live, generated): (String, String) = (defs.get(0), defs.get(1));
328            match first_difference(after_name(&live), after_name(&generated)) {
329                Some((l, g)) => {
330                    self.found(DriftKind::Changed, object, format!("its live definition is not the generated one (re-apply it): live `{l}`, generated `{g}`"));
331                }
332                None if off.is_none() => self.out.functions += 1,
333                None => {}
334            }
335        }
336        self.schemas = schemas.into_iter().collect();
337        let rows = tx
338            .query(
339                "SELECT p.oid::regprocedure::text FROM pg_proc p WHERE p.pronamespace = ANY($1) AND NOT (p.oid = ANY($2)) ORDER BY 1",
340                &[&self.schemas, &generated_oids],
341            )
342            .map_err(|e| query_error(&e))?;
343        for row in rows {
344            self.orphans.push(Finding {
345                kind: DriftKind::Orphan,
346                object: format!("function {}", row.get::<_, String>(0)),
347                detail: "live in a definer schema but not generated (drop it, or allow it)".into(),
348            });
349        }
350        Ok(())
351    }
352
353    fn grants_of_a_revoked_function(&mut self, tx: &mut Transaction<'_>, sig: &str, object: &str, oid: u32, said: Execute) -> Result<bool, String> {
354        let accepted = if said == Execute::Grantable { self.grantees } else { &[] };
355        let roles = granted_to(tx, oid, accepted)?;
356        for role in &roles {
357            let why = match said {
358                Execute::Grantable => "the manifest lists it as grantable, and no grantee is that role",
359                Execute::Revoked | Execute::Public => "the generated SQL revokes it from PUBLIC",
360            };
361            let detail = format!("{role} may execute it, and {why}: REVOKE EXECUTE ON FUNCTION {sig} FROM {role};");
362            self.found(DriftKind::Granted, object.to_string(), detail);
363        }
364        Ok(!roles.is_empty())
365    }
366
367    fn default_privileges(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
368        if !self.execute.values().any(|e| matches!(e, Execute::Revoked | Execute::Grantable)) {
369            return Ok(());
370        }
371        let rows = tx
372            .query(
373                "SELECT quote_ident(pg_get_userbyid(d.defaclrole)), COALESCE(quote_ident(n.nspname), ''), quote_ident(pg_get_userbyid(a.grantee)) \
374                 FROM pg_default_acl d LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace, aclexplode(d.defaclacl) a \
375                 WHERE d.defaclobjtype = 'f' AND a.privilege_type = 'EXECUTE' AND a.grantee <> 0 AND a.grantee <> d.defaclrole \
376                 AND (d.defaclnamespace = 0 OR d.defaclnamespace = ANY($1::oid[])) ORDER BY 1, 2, 3",
377                &[&self.schemas],
378            )
379            .map_err(|e| query_error(&e))?;
380        for row in rows {
381            let (owner, schema, grantee): (String, String, String) = (row.get(0), row.get(1), row.get(2));
382            let (object, scope) = if schema.is_empty() {
383                (format!("default privileges for role {owner}"), String::new())
384            } else {
385                (format!("default privileges for role {owner} in schema {schema}"), format!(" IN SCHEMA {schema}"))
386            };
387            let detail = format!(
388                "the functions {owner} creates are granted EXECUTE to {grantee}, those the SQL revokes from PUBLIC included: ALTER DEFAULT PRIVILEGES FOR ROLE {owner}{scope} REVOKE EXECUTE ON FUNCTIONS FROM {grantee};"
389            );
390            self.found(DriftKind::Granted, object, detail);
391        }
392        Ok(())
393    }
394
395    fn triggers(&mut self, tx: &mut Transaction<'_>) -> Result<(), String> {
396        let mut wanted = BTreeSet::new();
397        for (o, _) in self.objs {
398            let Object::Trigger { table, name } = o else { continue };
399            wanted.insert((table.clone(), name.clone()));
400            let object = format!("trigger {name} on {table}");
401            let (Some(live_oid), Some((shadow, shadow_oid))) = (self.live.get(table).copied(), self.shadow.get(table).cloned()) else { continue };
402            if let Some(e) = self.invalid.get(o).cloned() {
403                self.found(DriftKind::Invalid, object, format!("the generated trigger does not compile against the live database: {e}"));
404                continue;
405            }
406            let row = tx
407                .query_one(
408                    "SELECT (SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid = $1 AND tgname = $3 AND NOT tgisinternal),
409                            (SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid = $2 AND tgname = $3),
410                            $1::regclass::text",
411                    &[&live_oid, &shadow_oid, name],
412                )
413                .map_err(|e| query_error(&e))?;
414            let (live, generated, live_table): (Option<String>, Option<String>, String) = (row.get(0), row.get(1), row.get(2));
415            let Some(live) = live else {
416                self.found(DriftKind::Missing, object, "generated but not live (apply it)".into());
417                continue;
418            };
419            let generated = generated.unwrap_or_default().replacen(&format!("pg_temp.{shadow}"), &live_table, 1);
420            if live == generated {
421                self.out.triggers += 1;
422            } else {
423                self.found(DriftKind::Changed, object, format!("live `{live}`, generated `{generated}`"));
424            }
425        }
426        let by_oid: BTreeMap<u32, String> = self.live.iter().map(|(t, oid)| (*oid, t.clone())).collect();
427        let oids: Vec<u32> = by_oid.keys().copied().collect();
428        let rows = tx
429            .query(
430                "SELECT t.tgrelid, t.tgname::text FROM pg_trigger t JOIN pg_proc p ON p.oid = t.tgfoid
431                  WHERE NOT t.tgisinternal AND t.tgrelid = ANY($1) AND p.pronamespace = ANY($2) ORDER BY 1, 2",
432                &[&oids, &self.schemas],
433            )
434            .map_err(|e| query_error(&e))?;
435        for row in rows {
436            let (Some(table), name) = (by_oid.get(&row.get::<_, u32>(0)), row.get::<_, String>(1)) else { continue };
437            if !wanted.contains(&(table.clone(), name.clone())) {
438                self.orphans.push(Finding {
439                    kind: DriftKind::Orphan,
440                    object: format!("trigger {name} on {table}"),
441                    detail: "live, calling a definer-schema function, but not generated (drop it, or allow it)".into(),
442                });
443            }
444        }
445        Ok(())
446    }
447
448    fn finish(mut self, allow: &[String]) -> Drift {
449        let allowed: BTreeSet<&str> = allow.iter().map(String::as_str).collect();
450        let orphaned: BTreeSet<String> = self.orphans.iter().map(|f| f.object.clone()).collect();
451        self.out.findings.extend(self.orphans.into_iter().filter(|f| !allowed.contains(f.object.as_str())));
452        self.out.findings.extend(allowed.into_iter().filter(|a| !orphaned.contains(*a)).map(|a| Finding {
453            kind: DriftKind::Stale,
454            object: a.to_string(),
455            detail: "allowed as an orphan, but nothing live matches it (remove the entry)".into(),
456        }));
457        self.out
458    }
459}
460
461fn attempt(tx: &mut Transaction<'_>, stmt: &str) -> Result<(), String> {
462    let mut sp = tx.savepoint("demesne_diff").map_err(|e| query_error(&e))?;
463    match sp.batch_execute(stmt) {
464        Ok(()) => sp.commit().map_err(|e| query_error(&e)),
465        Err(e) => Err(e.as_db_error().map_or_else(|| query_error(&e), |d| d.message().to_string())),
466    }
467}
468
469fn command(polcmd: &str) -> &'static str {
470    match polcmd {
471        "r" => "SELECT",
472        "a" => "INSERT",
473        "w" => "UPDATE",
474        "d" => "DELETE",
475        _ => "ALL",
476    }
477}
478
479fn policy_change(live: &PolicyDef, generated: &PolicyDef) -> String {
480    let mut parts = Vec::new();
481    if live.cmd != generated.cmd {
482        parts.push(format!("command: live {}, generated {}", live.cmd, generated.cmd));
483    }
484    if live.permissive != generated.permissive {
485        let kind = |p: bool| if p { "permissive" } else { "restrictive" };
486        parts.push(format!("live {}, generated {}", kind(live.permissive), kind(generated.permissive)));
487    }
488    if live.roles != generated.roles {
489        parts.push(format!("roles: live {}, generated {}", live.roles.join(", "), generated.roles.join(", ")));
490    }
491    if live.using != generated.using {
492        parts.push(format!("USING: live `{}`, generated `{}`", live.using, generated.using));
493    }
494    if live.check != generated.check {
495        parts.push(format!("WITH CHECK: live `{}`, generated `{}`", live.check, generated.check));
496    }
497    parts.join("; ")
498}
499
500fn granted_to(tx: &mut Transaction<'_>, oid: u32, accepted: &[String]) -> Result<Vec<String>, String> {
501    let rows = tx
502        .query(
503            "SELECT quote_ident(pg_get_userbyid(a.grantee)) FROM pg_proc p, aclexplode(p.proacl) a \
504             WHERE p.oid = $1::oid AND a.privilege_type = 'EXECUTE' AND a.grantee <> 0 AND a.grantee <> p.proowner \
505             AND NOT (pg_get_userbyid(a.grantee) = ANY($2::text[])) ORDER BY 1",
506            &[&oid, &accepted],
507        )
508        .map_err(|e| query_error(&e))?;
509    Ok(rows.iter().map(|row| row.get(0)).collect())
510}
511
512fn no_grantee(role: &str) -> Option<String> {
513    if role.is_empty() {
514        return Some("a grantee names a role, and this one is empty".to_string());
515    }
516    if role.eq_ignore_ascii_case("public") {
517        return Some(format!("{role} is no grantee: PUBLIC holds exactly the functions the SQL grants to PUBLIC, and no grantable one"));
518    }
519    if role == POLICY_ROLE {
520        return Some(format!(
521            "{role} is no grantee: it is the role every policy is written for; a grantable function answers for any id, so it is never a grantee"
522        ));
523    }
524    None
525}
526
527fn for_public(said: Execute) -> Execute {
528    match said {
529        Execute::Grantable => Execute::Revoked,
530        Execute::Revoked | Execute::Public => said,
531    }
532}
533
534fn public_right(tx: &mut Transaction<'_>, oid: u32) -> Result<Execute, String> {
535    let public = tx.query_one("SELECT has_function_privilege('public', $1::oid, 'EXECUTE')", &[&oid]).map_err(|e| query_error(&e))?.get::<_, bool>(0);
536    Ok(if public { Execute::Public } else { Execute::Revoked })
537}
538
539fn schema_of(sig: &str) -> String {
540    let name = sig.split('(').next().unwrap_or_default();
541    name.rsplit_once('.').map(|(schema, _)| schema.to_string()).unwrap_or_default()
542}
543
544fn arguments(sig: &str) -> &str {
545    sig.find('(').map_or("()", |k| &sig[k..])
546}
547
548fn renamed(stmt: &str, name: &str) -> Option<String> {
549    let start = stmt.find("FUNCTION")? + "FUNCTION".len();
550    let open = start + stmt[start..].find('(')?;
551    Some(format!("{} {name}{}", &stmt[..start], &stmt[open..]))
552}
553
554fn retarget(stmt: &str, table: &str, to: &str) -> Option<String> {
555    let needle = format!(" ON {table}");
556    let mut from = 0;
557    while let Some(k) = stmt[from..].find(&needle).map(|k| from + k) {
558        let end = k + needle.len();
559        if stmt[end..].chars().next().is_none_or(char::is_whitespace) {
560            return Some(format!("{} ON {to}{}", &stmt[..k], &stmt[end..]));
561        }
562        from = end;
563    }
564    None
565}
566
567fn after_name(def: &str) -> &str {
568    def.split_once('(').map_or(def, |(_, rest)| rest)
569}
570
571fn first_difference<'a>(live: &'a str, generated: &'a str) -> Option<(&'a str, &'a str)> {
572    if live == generated {
573        return None;
574    }
575    let mut l = live.lines();
576    let mut g = generated.lines();
577    loop {
578        match (l.next(), g.next()) {
579            (Some(a), Some(b)) if a == b => {}
580            (a, b) => return Some((a.unwrap_or("<end>").trim(), b.unwrap_or("<end>").trim())),
581        }
582    }
583}