Skip to main content

safe_migrate/
sync.rs

1// FILE: src/sync.rs
2
3use crate::ast::identifiers::ObjectId;
4use crate::db::cache::{CACHE_V4_MAGIC, DbCache, DbCacheVersioned, ForeignKeyCache, IndexCache};
5use crate::db::cache_file::protect_cache_bytes;
6use crate::model::relation::{Persistence, RelationKind, RelationState};
7use anyhow::{Context, Result};
8use postgres::config::Host;
9use postgres::{Client, Config as PostgresConfig, NoTls};
10use std::io::Write;
11use std::path::Path;
12use std::time::{SystemTime, UNIX_EPOCH};
13use tempfile::NamedTempFile;
14
15#[cfg(windows)]
16use std::fs;
17
18pub fn sync_cache(
19    out_path: &Path,
20    schemas: Option<&[String]>,
21    cache_encryption: bool,
22) -> Result<()> {
23    // Strict env-only credential enforcement
24    let db_url = std::env::var("DATABASE_URL")
25        .context("DATABASE_URL environment variable is required to sync PostgreSQL schema metadata and statistics. Do not pass credentials via CLI flags or config files.")?;
26
27    let mut client = connect_database(&db_url)?;
28
29    let cache = populate_cache(&mut client, schemas)?;
30
31    write_cache(out_path, cache, cache_encryption)
32}
33
34fn connect_database(db_url: &str) -> Result<Client> {
35    let config: PostgresConfig = db_url
36        .parse()
37        .context("DATABASE_URL is not a valid PostgreSQL connection string")?;
38
39    if config
40        .get_hosts()
41        .iter()
42        .any(|host| matches!(host, Host::Tcp(name) if !is_local_host(name)))
43    {
44        anyhow::bail!(
45            "Remote DATABASE_URL connections are not supported by this build. Use an SSH tunnel and connect through localhost or a Unix socket."
46        );
47    }
48
49    config
50        .connect(NoTls)
51        .context("Failed to connect to PostgreSQL")
52}
53
54pub(crate) fn is_local_host(host: &str) -> bool {
55    if host.starts_with('/') || host.eq_ignore_ascii_case("localhost") {
56        return true;
57    }
58    host.trim_start_matches('[')
59        .trim_end_matches(']')
60        .parse::<std::net::IpAddr>()
61        .is_ok_and(|address| address.is_loopback())
62}
63
64pub(crate) fn cache_search_path(
65    database_search_path: Vec<String>,
66    schemas: Option<&[String]>,
67) -> Vec<String> {
68    let Some(schemas) = schemas else {
69        return database_search_path;
70    };
71
72    let mut scoped_search_path = Vec::new();
73    for schema in database_search_path
74        .into_iter()
75        .filter(|schema| schemas.contains(schema))
76        .chain(schemas.iter().cloned())
77    {
78        if !scoped_search_path.contains(&schema) {
79            scoped_search_path.push(schema);
80        }
81    }
82    scoped_search_path
83}
84
85/// Parse PostgreSQL's canonical `SHOW search_path` representation while
86/// preserving the special `$user` placeholder and quoted identifier casing.
87pub(crate) fn parse_search_path_setting(setting: &str) -> Vec<String> {
88    let mut entries = Vec::new();
89    let mut current = String::new();
90    let mut chars = setting.chars().peekable();
91    let mut quoted = false;
92
93    while let Some(ch) = chars.next() {
94        match ch {
95            '"' if quoted && chars.peek() == Some(&'"') => {
96                current.push('"');
97                chars.next();
98            }
99            '"' => quoted = !quoted,
100            ',' if !quoted => {
101                let entry = current.trim();
102                if !entry.is_empty() {
103                    entries.push(entry.to_string());
104                }
105                current.clear();
106            }
107            _ => current.push(ch),
108        }
109    }
110
111    let entry = current.trim();
112    if !entry.is_empty() {
113        entries.push(entry.to_string());
114    }
115    entries
116}
117
118pub(crate) fn relation_owner_id(owner_name: impl Into<String>) -> ObjectId {
119    ObjectId::new("", owner_name)
120}
121
122pub(crate) fn is_system_schema(schema: &str) -> bool {
123    schema == "information_schema" || schema.starts_with("pg_")
124}
125
126fn write_cache(out_path: &Path, cache: DbCache, cache_encryption: bool) -> Result<()> {
127    write_cache_with_protection(out_path, cache, |compressed| {
128        protect_cache_bytes(compressed, cache_encryption)
129    })
130}
131
132fn write_cache_with_protection(
133    out_path: &Path,
134    cache: DbCache,
135    protect: impl FnOnce(Vec<u8>) -> Result<Vec<u8>>,
136) -> Result<()> {
137    let parent = out_path.parent().unwrap_or_else(|| Path::new("."));
138    let mut temp_file = NamedTempFile::new_in(parent).with_context(|| {
139        format!(
140            "Failed to create temporary cache file beside {}",
141            out_path.display()
142        )
143    })?;
144    let mut compressed = Vec::new();
145    let mut encoder = zstd::stream::Encoder::new(&mut compressed, 3)
146        .context("Failed to init zstd compression")?;
147
148    encoder
149        .write_all(CACHE_V4_MAGIC)
150        .context("Failed to write cache V4 payload header")?;
151
152    let versioned = DbCacheVersioned::V4(cache);
153    let bincode_config = bincode::config::standard().with_variable_int_encoding();
154
155    bincode::serde::encode_into_std_write(&versioned, &mut encoder, bincode_config)
156        .context("Failed bincode schema compilation and write")?;
157
158    encoder
159        .finish()
160        .context("Failed to flush final zstd stream to disk")?;
161
162    let cache_bytes = protect(compressed)?;
163    temp_file
164        .write_all(&cache_bytes)
165        .context("Failed to write cache payload")?;
166    temp_file.flush().context("Failed to flush cache payload")?;
167
168    replace_cache(temp_file, out_path)?;
169
170    Ok(())
171}
172
173#[cfg(not(windows))]
174fn replace_cache(temp_file: NamedTempFile, out_path: &Path) -> Result<()> {
175    temp_file
176        .persist(out_path)
177        .map_err(|error| error.error)
178        .with_context(|| {
179            format!(
180                "Failed to atomically replace cache file: {}",
181                out_path.display()
182            )
183        })?;
184    Ok(())
185}
186
187#[cfg(windows)]
188fn replace_cache(temp_file: NamedTempFile, out_path: &Path) -> Result<()> {
189    if !out_path.exists() {
190        temp_file
191            .persist(out_path)
192            .map_err(|error| error.error)
193            .with_context(|| format!("Failed to install cache file: {}", out_path.display()))?;
194        return Ok(());
195    }
196
197    let backup = out_path.with_extension("safe-migrate.backup");
198    fs::rename(out_path, &backup).with_context(|| {
199        format!(
200            "Failed to stage existing cache for replacement: {}",
201            out_path.display()
202        )
203    })?;
204
205    match temp_file.persist(out_path) {
206        Ok(_) => {
207            fs::remove_file(&backup).with_context(|| {
208                format!(
209                    "Installed new cache but failed to remove backup: {}",
210                    backup.display()
211                )
212            })?;
213            Ok(())
214        }
215        Err(error) => {
216            let restore_result = fs::rename(&backup, out_path);
217            let message = if let Err(restore_error) = restore_result {
218                format!(
219                    "Failed to install new cache: {}. The old cache could not be restored: {}",
220                    error.error, restore_error
221                )
222            } else {
223                format!(
224                    "Failed to install new cache; restored the previous cache: {}",
225                    error.error
226                )
227            };
228            Err(anyhow::anyhow!(message))
229        }
230    }
231}
232
233pub fn populate_cache(client: &mut Client, schemas: Option<&[String]>) -> Result<DbCache> {
234    let mut cache = DbCache::new();
235    let schema_values = schemas.map(|items| items.to_vec());
236    cache.metadata.created_at_unix_secs = Some(
237        SystemTime::now()
238            .duration_since(UNIX_EPOCH)
239            .unwrap_or_default()
240            .as_secs(),
241    );
242    cache.metadata.schemas = schema_values.clone();
243
244    let schema_filter = "AND ($1::text[] IS NULL OR n.nspname = ANY($1))";
245    let schema_filter_with_fk = r#"
246        AND (
247            $1::text[] IS NULL
248            OR n.nspname = ANY($1)
249            OR c.oid IN (
250                SELECT conrelid FROM pg_constraint cst
251                JOIN pg_class c2 ON c2.oid = cst.confrelid
252                JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
253                WHERE n2.nspname = ANY($1)
254            )
255            OR c.oid IN (
256                SELECT confrelid FROM pg_constraint cst
257                JOIN pg_class c2 ON c2.oid = cst.conrelid
258                JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
259                WHERE n2.nspname = ANY($1)
260            )
261        )
262    "#;
263    let schema_filter_n1_or_n2 =
264        "AND ($1::text[] IS NULL OR n1.nspname = ANY($1) OR n2.nspname = ANY($1))";
265    let schema_filter_nt = r#"
266        AND (
267            $1::text[] IS NULL
268            OR n_t.nspname = ANY($1)
269            OR t.oid IN (
270                SELECT conrelid FROM pg_constraint cst
271                JOIN pg_class c2 ON c2.oid = cst.confrelid
272                JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
273                WHERE n2.nspname = ANY($1)
274            )
275            OR t.oid IN (
276                SELECT confrelid FROM pg_constraint cst
277                JOIN pg_class c2 ON c2.oid = cst.conrelid
278                JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
279                WHERE n2.nspname = ANY($1)
280            )
281        )
282    "#;
283
284    // Query 1: Server Version
285    let version_row = client.query_one("SHOW server_version_num;", &[])?;
286    let version_str: String = version_row.get(0);
287    cache.pg_version_num = version_str.parse::<u32>().ok();
288
289    let provenance_row = client.query_one(
290        "SELECT current_database(), current_user, session_user, current_setting('search_path');",
291        &[],
292    )?;
293    cache.metadata.source_database = Some(provenance_row.get(0));
294    cache.metadata.source_role = Some(provenance_row.get(1));
295    cache.metadata.source_session_role = Some(provenance_row.get(2));
296    let search_path_setting: String = provenance_row.get(3);
297    cache.metadata.source_search_path = Some(parse_search_path_setting(&search_path_setting));
298
299    // Resolve role/database defaults and special entries such as "$user" exactly
300    // as PostgreSQL does, while excluding the implicit pg_catalog lookup. An
301    // explicit schema scope remains the resolution boundary, but selected
302    // schemas retain their live PostgreSQL priority.
303    let search_path_row = client.query_one("SELECT current_schemas(false);", &[])?;
304    cache.search_path = cache_search_path(search_path_row.get(0), schemas);
305
306    // Query 2: Relations + Staleness
307    let table_query = format!(
308        "
309        SELECT
310            n.nspname AS schema_name,
311            c.relname AS relation_name,
312            c.relkind AS relation_kind,
313            c.relpersistence AS persistence,
314            pg_catalog.pg_get_userbyid(c.relowner) AS owner_name,
315            CASE WHEN c.reltuples < 0 THEN -1 ELSE c.reltuples::bigint END AS estimated_rows,
316            c.relpages::bigint AS relpages,
317            to_char(s.last_analyze, 'YYYY-MM-DD HH24:MI:SS') AS last_analyze,
318            to_char(s.last_autoanalyze, 'YYYY-MM-DD HH24:MI:SS') AS last_autoanalyze,
319            p.partstrat::text AS partition_strategy
320        FROM pg_class c
321        JOIN pg_namespace n ON n.oid = c.relnamespace
322        LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid
323        LEFT JOIN pg_partitioned_table p ON p.partrelid = c.oid
324        WHERE c.relkind IN ('r', 'p', 'v', 'm')
325          AND n.nspname NOT IN ('pg_catalog', 'information_schema')
326          {schema_filter_with_fk};
327    "
328    );
329
330    for row in client.query(&table_query, &[&schema_values])? {
331        let schema_name: String = row.get("schema_name");
332        let relation_name: String = row.get("relation_name");
333        let relkind: i8 = row.get("relation_kind");
334        let persistence_char: i8 = row.get("persistence");
335        let owner_name: String = row.get("owner_name");
336        let raw_rows: i64 = row.get("estimated_rows");
337        let relpages: i64 = row.get("relpages");
338
339        let last_analyze: Option<String> = row.get("last_analyze");
340        let last_autoanalyze: Option<String> = row.get("last_autoanalyze");
341
342        let object_id = ObjectId::new(&schema_name, &relation_name);
343
344        let kind = match relkind as u8 {
345            b'v' => RelationKind::View,
346            b'm' => RelationKind::MaterializedView,
347            _ => RelationKind::Table,
348        };
349
350        let persistence = match persistence_char as u8 {
351            b't' => Persistence::Temporary,
352            b'u' => Persistence::Unlogged,
353            _ => Persistence::Permanent,
354        };
355
356        let estimated_rows = if raw_rows < 0 {
357            None
358        } else {
359            Some(raw_rows as u64)
360        };
361
362        let mut state = RelationState::new(
363            object_id.clone(),
364            relation_owner_id(owner_name),
365            0,
366            estimated_rows,
367            kind,
368            persistence,
369            0,
370        );
371        state.relpages = Some(relpages as u64);
372        state.last_analyze = last_analyze;
373        state.last_autoanalyze = last_autoanalyze;
374
375        let partition_strategy: Option<String> = row.get("partition_strategy");
376        if let Some(ref strat) = partition_strategy {
377            state.partition_type = Some(match strat.as_str() {
378                "r" => "RANGE".to_string(),
379                "l" => "LIST".to_string(),
380                "h" => "HASH".to_string(),
381                _ => strat.to_uppercase(),
382            });
383        }
384
385        if let Some(s) = schemas
386            && !s.contains(&schema_name)
387        {
388            state.mark_fk_dependency();
389        }
390
391        cache.insert_baseline(object_id, state);
392    }
393
394    // Query 3: Columns + Width
395    let col_query = format!("
396        SELECT
397            n.nspname AS schema_name,
398            c.relname AS relation_name,
399            a.attname AS column_name,
400            pg_catalog.format_type(a.atttypid, a.atttypmod) AS type_name,
401            a.attnotnull AS not_null,
402            s.avg_width AS avg_width,
403            pg_get_expr(ad.adbin, ad.adrelid) AS default_expr_text,
404            a.atttypmod AS type_modifier
405        FROM pg_attribute a
406        JOIN pg_class c ON a.attrelid = c.oid
407        JOIN pg_namespace n ON n.oid = c.relnamespace
408        LEFT JOIN pg_stats s ON s.schemaname = n.nspname AND s.tablename = c.relname AND s.attname = a.attname
409        LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
410        WHERE a.attnum > 0 AND NOT a.attisdropped
411          AND c.relkind IN ('r', 'p', 'v', 'm')
412          AND n.nspname NOT IN ('pg_catalog', 'information_schema')
413          {schema_filter_with_fk}
414        ORDER BY n.nspname, c.relname;
415    ");
416
417    for row in client.query(&col_query, &[&schema_values])? {
418        let schema_name: String = row.get("schema_name");
419        let relation_name: String = row.get("relation_name");
420        let column_name: String = row.get("column_name");
421        let type_name: String = row.get("type_name");
422        let not_null: bool = row.get("not_null");
423        let avg_width: Option<i32> = row.get("avg_width");
424        let default_expr_text: Option<String> = row.get("default_expr_text");
425        let type_modifier: Option<i32> = row.get("type_modifier");
426
427        let relation_id = ObjectId::new(&schema_name, &relation_name);
428        if let Some(rel) = cache.relations.get_mut(&relation_id) {
429            rel.columns.push(crate::model::column::Column {
430                name: column_name,
431                data_type: Some(type_name),
432                is_nullable: !not_null,
433                default: None,
434                avg_width,
435                default_expr_text,
436                type_modifier,
437            });
438        }
439    }
440
441    // Query 4: Triggers & Policies
442    let tp_query = format!("
443        SELECT 
444            n.nspname AS schema_name,
445            c.relname AS relation_name,
446            COALESCE(array_agg(DISTINCT t.tgname) FILTER (WHERE t.tgname IS NOT NULL AND t.tgisinternal = false), '{{}}') as triggers,
447            COALESCE(array_agg(DISTINCT p.polname) FILTER (WHERE p.polname IS NOT NULL), '{{}}') as policies
448        FROM pg_class c
449        JOIN pg_namespace n ON n.oid = c.relnamespace
450        LEFT JOIN pg_trigger t ON t.tgrelid = c.oid
451        LEFT JOIN pg_policy p ON p.polrelid = c.oid
452        WHERE c.relkind IN ('r', 'p', 'v', 'm') AND n.nspname NOT IN ('pg_catalog', 'information_schema')
453        {schema_filter_with_fk}
454        GROUP BY n.nspname, c.relname;
455    ");
456
457    for row in client.query(&tp_query, &[&schema_values])? {
458        let schema_name: String = row.get("schema_name");
459        let relation_name: String = row.get("relation_name");
460        let triggers: Vec<String> = row.get("triggers");
461        let policies: Vec<String> = row.get("policies");
462
463        let object_id = ObjectId::new(&schema_name, &relation_name);
464
465        if let Some(rel) = cache.relations.get_mut(&object_id) {
466            rel.triggers.extend(triggers);
467            rel.policies.extend(policies);
468        }
469    }
470
471    // Query 4.25: Explicit non-owner relation privileges.
472    let acl_query = format!(
473        "
474        SELECT
475            n.nspname AS schema_name,
476            c.relname AS relation_name,
477            CASE
478                WHEN acl.grantee = 0 THEN 'public'
479                ELSE pg_catalog.pg_get_userbyid(acl.grantee)
480            END AS grantee,
481            acl.privilege_type
482        FROM pg_class c
483        JOIN pg_namespace n ON n.oid = c.relnamespace
484        CROSS JOIN LATERAL pg_catalog.aclexplode(c.relacl) acl
485        WHERE c.relkind IN ('r', 'p', 'v', 'm')
486          AND n.nspname NOT IN ('pg_catalog', 'information_schema')
487          AND acl.grantee <> c.relowner
488          {schema_filter_with_fk};
489        "
490    );
491
492    for row in client.query(&acl_query, &[&schema_values])? {
493        let schema_name: String = row.get("schema_name");
494        let relation_name: String = row.get("relation_name");
495        let grantee: String = row.get("grantee");
496        let privilege_type: String = row.get("privilege_type");
497        let privilege = match privilege_type.as_str() {
498            "SELECT" => crate::model::relation::Privilege::Select,
499            "INSERT" => crate::model::relation::Privilege::Insert,
500            "UPDATE" => crate::model::relation::Privilege::Update,
501            "DELETE" => crate::model::relation::Privilege::Delete,
502            "TRUNCATE" => crate::model::relation::Privilege::Truncate,
503            "REFERENCES" => crate::model::relation::Privilege::References,
504            "TRIGGER" => crate::model::relation::Privilege::Trigger,
505            _ => continue,
506        };
507        if let Some(relation) = cache
508            .relations
509            .get_mut(&ObjectId::new(&schema_name, &relation_name))
510        {
511            relation.privileges.grant(
512                ObjectId::new("", grantee),
513                [privilege].into_iter().collect(),
514            );
515        }
516    }
517
518    // Query 4.5: Trigger Functions
519    let trig_query = format!(
520        "
521        SELECT 
522            n.nspname AS table_schema,
523            c.relname AS table_name,
524            t.tgname AS trigger_name,
525            t.tgenabled::text AS enabled_mode,
526            fn.nspname AS function_schema,
527            f.proname || '()' AS function_name
528        FROM pg_trigger t
529        JOIN pg_class c ON c.oid = t.tgrelid
530        JOIN pg_namespace n ON n.oid = c.relnamespace
531        JOIN pg_proc f ON f.oid = t.tgfoid
532        JOIN pg_namespace fn ON fn.oid = f.pronamespace
533        WHERE t.tgisinternal = false
534          AND n.nspname NOT IN ('pg_catalog', 'information_schema')
535          {schema_filter_with_fk};
536    "
537    );
538
539    for row in client.query(&trig_query, &[&schema_values])? {
540        let table_schema: String = row.get("table_schema");
541        let table_name: String = row.get("table_name");
542        let trigger_name: String = row.get("trigger_name");
543        let enabled_mode: String = row.get("enabled_mode");
544        let function_schema: String = row.get("function_schema");
545        let function_name: String = row.get("function_name");
546
547        cache.triggers.push(crate::db::cache::TriggerCache {
548            trigger_id: ObjectId::new(&table_schema, &trigger_name),
549            table_id: ObjectId::new(&table_schema, &table_name),
550            function_id: ObjectId::new(&function_schema, &function_name),
551            enabled_mode: crate::model::trigger::TriggerEnableMode::from_pg_code(&enabled_mode)
552                .ok_or_else(|| {
553                    anyhow::anyhow!("unknown pg_trigger.tgenabled value {enabled_mode}")
554                })?,
555        });
556    }
557
558    // Query 4.75: Table constraints
559    let constraint_query = format!(
560        "
561        SELECT
562            n.nspname AS table_schema,
563            c.relname AS table_name,
564            con.conname AS constraint_name,
565            con.contype::text AS constraint_type,
566            con.convalidated AS validated
567        FROM pg_constraint con
568        JOIN pg_class c ON c.oid = con.conrelid
569        JOIN pg_namespace n ON n.oid = c.relnamespace
570        WHERE con.contype IN ('c', 'f', 'p', 'u', 'x')
571          AND n.nspname NOT IN ('pg_catalog', 'information_schema')
572          {schema_filter};
573        "
574    );
575
576    for row in client.query(&constraint_query, &[&schema_values])? {
577        let table_schema: String = row.get("table_schema");
578        let table_name: String = row.get("table_name");
579        let constraint_name: String = row.get("constraint_name");
580        let constraint_type: String = row.get("constraint_type");
581        let validated: bool = row.get("validated");
582        let kind = match constraint_type.as_str() {
583            "c" => crate::model::constraint::ConstraintKind::Check,
584            "f" => crate::model::constraint::ConstraintKind::ForeignKey,
585            "p" => crate::model::constraint::ConstraintKind::PrimaryKey,
586            "u" => crate::model::constraint::ConstraintKind::Unique,
587            "x" => crate::model::constraint::ConstraintKind::Exclusion,
588            _ => continue,
589        };
590        cache
591            .constraints
592            .push(crate::model::constraint::ConstraintState {
593                table_id: ObjectId::new(&table_schema, &table_name),
594                name: constraint_name,
595                kind,
596                validated,
597            });
598    }
599
600    // Query 5: Foreign Keys
601    let fk_query = format!(
602        "
603        SELECT 
604            c.conname AS constraint_name,
605            n1.nspname AS from_schema, t1.relname AS from_table,
606            n2.nspname AS to_schema, t2.relname AS to_table
607        FROM pg_constraint c
608        JOIN pg_class t1 ON t1.oid = c.conrelid
609        JOIN pg_namespace n1 ON n1.oid = t1.relnamespace
610        JOIN pg_class t2 ON t2.oid = c.confrelid
611        JOIN pg_namespace n2 ON n2.oid = t2.relnamespace
612        WHERE c.contype = 'f'
613        {schema_filter_n1_or_n2};
614    "
615    );
616
617    for row in client.query(&fk_query, &[&schema_values])? {
618        let constraint_name: String = row.get("constraint_name");
619        let from_schema: String = row.get("from_schema");
620        let from_table: String = row.get("from_table");
621        let to_schema: String = row.get("to_schema");
622        let to_table: String = row.get("to_table");
623
624        if let Some(s) = schemas
625            && (!s.contains(&from_schema) || !s.contains(&to_schema))
626        {
627            // Determine which one is out of scope to print a helpful warning
628            let out_of_scope_schema = if !s.contains(&from_schema) {
629                &from_schema
630            } else {
631                &to_schema
632            };
633            let out_of_scope_table = if !s.contains(&from_schema) {
634                &from_table
635            } else {
636                &to_table
637            };
638            eprintln!(
639                "[WARN] Foreign key '{}' crosses schema boundary. Table '{}.{}' was pulled into cache as a dependency to evaluate cross-team locks.",
640                constraint_name, out_of_scope_schema, out_of_scope_table
641            );
642        }
643
644        cache.foreign_keys.push(ForeignKeyCache {
645            constraint_name,
646            from_table: ObjectId::new(&from_schema, &from_table),
647            to_table: ObjectId::new(&to_schema, &to_table),
648        });
649    }
650
651    // Query 6: Indexes
652    let idx_query = format!(
653        "
654        SELECT 
655            n_i.nspname AS index_schema, i.relname AS index_name,
656            n_t.nspname AS table_schema, t.relname AS table_name
657        FROM pg_index x
658        JOIN pg_class i ON i.oid = x.indexrelid
659        JOIN pg_namespace n_i ON n_i.oid = i.relnamespace
660        JOIN pg_class t ON t.oid = x.indrelid
661        JOIN pg_namespace n_t ON n_t.oid = t.relnamespace
662        WHERE x.indisvalid = true
663          AND n_i.nspname !~ '^pg_'
664          AND n_i.nspname <> 'information_schema'
665          AND n_t.nspname !~ '^pg_'
666          AND n_t.nspname <> 'information_schema'
667        {schema_filter_nt};
668    "
669    );
670
671    for row in client.query(&idx_query, &[&schema_values])? {
672        let index_schema: String = row.get("index_schema");
673        let index_name: String = row.get("index_name");
674        let table_schema: String = row.get("table_schema");
675        let table_name: String = row.get("table_name");
676
677        if is_system_schema(&index_schema) || is_system_schema(&table_schema) {
678            continue;
679        }
680
681        cache.indexes.push(IndexCache {
682            index_id: ObjectId::new(&index_schema, &index_name),
683            table_id: ObjectId::new(&table_schema, &table_name),
684        });
685    }
686
687    // Query 7: Functions
688    let func_query = format!(
689        "
690        SELECT
691            n.nspname AS schema_name,
692            p.proname AS func_name,
693            COALESCE(
694                (SELECT string_agg(pg_catalog.format_type(t, NULL), ',' ORDER BY n)
695                 FROM unnest(p.proargtypes::int[]) WITH ORDINALITY AS u(t, n)),
696                ''
697            ) AS arg_types,
698            pg_catalog.pg_get_function_result(p.oid) AS return_type,
699            p.provolatile::text AS volatility,
700            l.lanname AS language,
701            p.prosecdef AS security_definer
702        FROM pg_proc p
703        JOIN pg_namespace n ON n.oid = p.pronamespace
704        JOIN pg_language l ON l.oid = p.prolang
705        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
706          AND p.prokind = 'f'
707          {schema_filter};
708    "
709    );
710
711    for row in client.query(&func_query, &[&schema_values])? {
712        let schema_name: String = row.get("schema_name");
713        let func_name: String = row.get("func_name");
714        let arg_types_str: String = row.get("arg_types");
715        let return_type: Option<String> = row.get("return_type");
716        let volatility_char: String = row.get("volatility");
717        let language: String = row.get("language");
718        let security_definer: bool = row.get("security_definer");
719
720        let volatility = match volatility_char.as_str() {
721            "v" => crate::model::function::Volatility::Volatile,
722            "s" => crate::model::function::Volatility::Stable,
723            "i" => crate::model::function::Volatility::Immutable,
724            _ => crate::model::function::Volatility::Volatile,
725        };
726
727        let security = if security_definer {
728            crate::model::function::SecurityMode::Definer
729        } else {
730            crate::model::function::SecurityMode::Invoker
731        };
732
733        // Normalize argument types in sync just like in resolver
734        let arg_types_str = arg_types_str
735            .split(',')
736            .map(|s| s.trim().to_lowercase())
737            .collect::<Vec<_>>()
738            .join(",");
739
740        let id = ObjectId::new(&schema_name, format!("{}({})", func_name, arg_types_str));
741
742        let arg_types = if arg_types_str.is_empty() {
743            Vec::new()
744        } else {
745            arg_types_str.split(',').map(|s| s.to_string()).collect()
746        };
747
748        cache.functions.insert(
749            id.clone(),
750            crate::model::function::FunctionState {
751                id,
752                arg_types,
753                return_type: return_type.unwrap_or_default(),
754                volatility,
755                language,
756                security,
757            },
758        );
759    }
760
761    // Query 8: User-defined types, including ordered enum labels and domains.
762    let type_query = format!(
763        "
764        SELECT
765            n.nspname AS schema_name,
766            t.typname AS type_name,
767            t.typtype::text AS type_kind,
768            CASE WHEN t.typtype = 'd'
769                THEN pg_catalog.format_type(t.typbasetype, t.typtypmod)
770                ELSE NULL
771            END AS domain_base_type,
772            COALESCE(
773                array_agg(e.enumlabel ORDER BY e.enumsortorder)
774                    FILTER (WHERE e.enumlabel IS NOT NULL),
775                ARRAY[]::text[]
776            ) AS enum_labels
777        FROM pg_type t
778        JOIN pg_namespace n ON n.oid = t.typnamespace
779        LEFT JOIN pg_enum e ON e.enumtypid = t.oid
780        WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
781          AND t.typtype IN ('e', 'd')
782          {schema_filter}
783        GROUP BY n.nspname, t.typname, t.typtype, t.typbasetype, t.typtypmod;
784        "
785    );
786
787    for row in client.query(&type_query, &[&schema_values])? {
788        let schema_name: String = row.get("schema_name");
789        let type_name: String = row.get("type_name");
790        let type_kind: String = row.get("type_kind");
791        let domain_base_type: Option<String> = row.get("domain_base_type");
792        let enum_labels: Vec<String> = row.get("enum_labels");
793        let kind = match type_kind.as_str() {
794            "e" => crate::model::types::TypeKind::Enum {
795                variants: enum_labels,
796            },
797            "d" => crate::model::types::TypeKind::Domain {
798                base_type: domain_base_type.unwrap_or_default(),
799            },
800            _ => continue,
801        };
802        let id = ObjectId::new(&schema_name, &type_name);
803        cache.types.insert(
804            id.clone(),
805            crate::model::types::TypeState {
806                id,
807                generation: 0,
808                kind,
809            },
810        );
811    }
812
813    // Query 9: Dependencies (pg_depend)
814    let depend_query = r#"
815        SELECT
816            d.classid, d.objid, d.objsubid,
817            d.refclassid, d.refobjid, d.refobjsubid,
818            d.deptype::text,
819            COALESCE(n1.nspname, n1p.nspname, n1t.nspname) AS obj_schema,
820            COALESCE(c1.relname, p1.proname, t1.typname) AS obj_name,
821            COALESCE(n2.nspname, n2p.nspname, n2t.nspname) AS ref_schema,
822            COALESCE(c2.relname, p2.proname, t2.typname) AS ref_name
823        FROM pg_depend d
824        LEFT JOIN pg_class c1 ON c1.oid = d.objid AND d.classid = 'pg_class'::regclass
825        LEFT JOIN pg_namespace n1 ON n1.oid = c1.relnamespace
826        LEFT JOIN pg_proc p1 ON p1.oid = d.objid AND d.classid = 'pg_proc'::regclass
827        LEFT JOIN pg_namespace n1p ON n1p.oid = p1.pronamespace
828        LEFT JOIN pg_type t1 ON t1.oid = d.objid AND d.classid = 'pg_type'::regclass
829        LEFT JOIN pg_namespace n1t ON n1t.oid = t1.typnamespace
830        LEFT JOIN pg_class c2 ON c2.oid = d.refobjid AND d.refclassid = 'pg_class'::regclass
831        LEFT JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
832        LEFT JOIN pg_proc p2 ON p2.oid = d.refobjid AND d.refclassid = 'pg_proc'::regclass
833        LEFT JOIN pg_namespace n2p ON n2p.oid = p2.pronamespace
834        LEFT JOIN pg_type t2 ON t2.oid = d.refobjid AND d.refclassid = 'pg_type'::regclass
835        LEFT JOIN pg_namespace n2t ON n2t.oid = t2.typnamespace
836        WHERE d.deptype IN ('n', 'a', 'i')
837          AND COALESCE(n1.nspname, n1p.nspname, n1t.nspname) IS NOT NULL
838          AND COALESCE(n1.nspname, n1p.nspname, n1t.nspname)
839              NOT IN ('pg_catalog', 'information_schema')
840          AND (
841              $1::text[] IS NULL
842              OR COALESCE(n1.nspname, n1p.nspname, n1t.nspname) = ANY($1)
843          )
844    "#;
845
846    for row in client.query(depend_query, &[&schema_values])? {
847        let classid: u32 = row.get(0);
848        let objid: u32 = row.get(1);
849        let objsubid: i32 = row.get(2);
850        let refclassid: u32 = row.get(3);
851        let refobjid: u32 = row.get(4);
852        let refobjsubid: i32 = row.get(5);
853        let deptype: String = row.get(6);
854        let obj_schema: Option<String> = row.get(7);
855        let obj_name: Option<String> = row.get(8);
856        let ref_schema: Option<String> = row.get(9);
857        let ref_name: Option<String> = row.get(10);
858
859        cache.dependencies.push(crate::db::cache::DependencyCache {
860            classid,
861            objid,
862            objsubid,
863            refclassid,
864            refobjid,
865            refobjsubid,
866            deptype,
867            obj_schema,
868            obj_name,
869            ref_schema,
870            ref_name,
871        });
872    }
873
874    // View dependencies are owned by pg_rewrite entries, so the generic pg_depend
875    // query above cannot recover the dependent view's schema-qualified identity.
876    let view_depend_query = r#"
877        SELECT DISTINCT
878            'pg_class'::regclass::oid AS classid,
879            vc.oid AS objid,
880            0 AS objsubid,
881            'pg_class'::regclass::oid AS refclassid,
882            tc.oid AS refobjid,
883            0 AS refobjsubid,
884            vn.nspname AS obj_schema,
885            vc.relname AS obj_name,
886            tn.nspname AS ref_schema,
887            tc.relname AS ref_name
888        FROM pg_rewrite rw
889        JOIN pg_class vc ON vc.oid = rw.ev_class
890        JOIN pg_namespace vn ON vn.oid = vc.relnamespace
891        JOIN pg_depend d ON d.objid = rw.oid
892        JOIN pg_class tc ON tc.oid = d.refobjid
893        JOIN pg_namespace tn ON tn.oid = tc.relnamespace
894        WHERE vc.relkind IN ('v', 'm')
895          AND d.deptype = 'n'
896          -- PostgreSQL 14/15 expose an internal rewrite-rule self-edge. It is
897          -- not a dependency of the view definition and must not enter the
898          -- modeled dependency graph.
899          AND tc.oid <> vc.oid
900          AND (
901              $1::text[] IS NULL
902              OR (vn.nspname = ANY($1) AND tn.nspname = ANY($1))
903          )
904    "#;
905
906    for row in client.query(view_depend_query, &[&schema_values])? {
907        cache.dependencies.push(crate::db::cache::DependencyCache {
908            classid: row.get(0),
909            objid: row.get(1),
910            objsubid: row.get(2),
911            refclassid: row.get(3),
912            refobjid: row.get(4),
913            refobjsubid: row.get(5),
914            deptype: "view".to_string(),
915            obj_schema: Some(row.get(6)),
916            obj_name: Some(row.get(7)),
917            ref_schema: Some(row.get(8)),
918            ref_name: Some(row.get(9)),
919        });
920    }
921
922    // Role identity and membership are required to distinguish a valid
923    // `SET ROLE` from a migration that PostgreSQL would reject. pg_roles does
924    // not expose password hashes or other credentials.
925    for row in client.query(
926        "SELECT rolname, rolcanlogin, rolsuper FROM pg_roles ORDER BY rolname;",
927        &[],
928    )? {
929        let name: String = row.get(0);
930        let id = ObjectId::new("", &name);
931        cache.roles.insert(
932            id.clone(),
933            crate::model::role::RoleState {
934                id,
935                can_login: row.get(1),
936                is_superuser: row.get(2),
937                member_of: Vec::new(),
938                can_set_role_to: Vec::new(),
939                granted_privileges: Vec::new(),
940            },
941        );
942    }
943
944    let membership_query = if cache.pg_version_num.unwrap_or_default() >= 160_000 {
945        "SELECT member.rolname, parent.rolname, membership.set_option
946         FROM pg_auth_members membership
947         JOIN pg_roles member ON member.oid = membership.member
948         JOIN pg_roles parent ON parent.oid = membership.roleid;"
949    } else {
950        "SELECT member.rolname, parent.rolname, true AS set_option
951         FROM pg_auth_members membership
952         JOIN pg_roles member ON member.oid = membership.member
953         JOIN pg_roles parent ON parent.oid = membership.roleid;"
954    };
955    for row in client.query(membership_query, &[])? {
956        let member = ObjectId::new("", row.get::<_, String>(0));
957        let parent = ObjectId::new("", row.get::<_, String>(1));
958        let set_option: bool = row.get(2);
959        if let Some(role) = cache.roles.get_mut(&member) {
960            role.member_of.push(parent.clone());
961            if set_option {
962                role.can_set_role_to.push(parent);
963            }
964        }
965    }
966
967    Ok(cache)
968}
969
970#[cfg(test)]
971mod atomic_write_tests {
972    use super::*;
973    use crate::db::cache::DbCacheVersioned;
974    use std::fs;
975    use std::io::Read;
976
977    #[test]
978    fn production_cache_writer_atomically_replaces_and_decodes() {
979        let temp_dir = tempfile::tempdir().unwrap();
980        let cache_path = temp_dir.path().join("baseline.cache");
981        fs::write(&cache_path, b"old-cache").unwrap();
982
983        let mut cache = DbCache::new();
984        cache.pg_version_num = Some(180002);
985        write_cache(&cache_path, cache, false).unwrap();
986
987        let encoded = fs::read(&cache_path).unwrap();
988        assert_ne!(encoded, b"old-cache");
989        let reader = std::io::Cursor::new(encoded);
990        let mut decoder = zstd::stream::Decoder::new(reader).unwrap();
991        let mut payload = Vec::new();
992        decoder.read_to_end(&mut payload).unwrap();
993        let payload = payload
994            .strip_prefix(CACHE_V4_MAGIC)
995            .expect("writer must prefix V4 cache payloads");
996        let config = bincode::config::standard().with_variable_int_encoding();
997        let versioned: DbCacheVersioned = bincode::serde::decode_from_slice(payload, config)
998            .unwrap()
999            .0;
1000        assert_eq!(versioned.into_cache().unwrap().pg_version_num, Some(180002));
1001        assert_eq!(fs::read_dir(temp_dir.path()).unwrap().count(), 1);
1002    }
1003
1004    #[test]
1005    fn production_cache_writer_preserves_old_bytes_after_pre_install_failure() {
1006        let temp_dir = tempfile::tempdir().unwrap();
1007        let cache_path = temp_dir.path().join("baseline.cache");
1008        fs::write(&cache_path, b"known-good-cache").unwrap();
1009
1010        let error = write_cache_with_protection(&cache_path, DbCache::new(), |_| {
1011            Err(anyhow::anyhow!("injected payload-protection failure"))
1012        })
1013        .unwrap_err();
1014
1015        assert!(
1016            error
1017                .to_string()
1018                .contains("injected payload-protection failure")
1019        );
1020        assert_eq!(fs::read(&cache_path).unwrap(), b"known-good-cache");
1021        assert_eq!(fs::read_dir(temp_dir.path()).unwrap().count(), 1);
1022    }
1023}