diff --git a/crates/dbx-core/src/db/postgres.rs b/crates/dbx-core/src/db/postgres.rs index a1e128ca37..635a3c8efb 100644 --- a/crates/dbx-core/src/db/postgres.rs +++ b/crates/dbx-core/src/db/postgres.rs @@ -7970,6 +7970,39 @@ fn postgres_sequence_last_values_sql() -> &'static str { WHERE c.relkind = 'S' AND n.nspname = $1" } +// PostgreSQL 9.x sibling of `postgres_sequences_sql`: the `pg_sequence` catalog +// (and the `pg_sequence_last_value` function used below) were only added in +// PostgreSQL 10. Older servers still expose the same properties through the +// portable `information_schema.sequences` view, which is what openGauss's +// tier already relies on for the same reason. +fn postgres_sequences_compat_sql() -> &'static str { + "SELECT s.sequence_name, \ + COALESCE(s.data_type::text, 'bigint'), \ + COALESCE(s.start_value::text, '1'), \ + COALESCE(s.minimum_value::text, '1'), \ + COALESCE(s.maximum_value::text, '9223372036854775807'), \ + COALESCE(s.increment::text, '1'), \ + COALESCE(s.cycle_option::text, 'NO') \ + FROM information_schema.sequences s \ + WHERE s.sequence_schema = $1 \ + ORDER BY s.sequence_name" +} + +// Pre-PG10 servers have no `pg_sequence_last_value(oid)` function to read an +// arbitrary sequence's current value from a single batched query, so the +// compat tier falls back to querying each sequence relation directly (the +// pre-10 way of reading `last_value`), one round trip per sequence. +async fn postgres_sequence_last_value_compat( + client: &deadpool_postgres::Client, + schema: &str, + sequence_name: &str, +) -> Result, tokio_postgres::Error> { + let qualified = format!("{}.{}", pg_quote_ident(schema), pg_quote_ident(sequence_name)); + let sql = format!("SELECT last_value::text FROM {qualified}"); + let rows = postgres_query_cached(client, &sql, &[]).await?; + Ok(rows.first().and_then(|row| row.try_get::<_, Option>(0).ok().flatten())) +} + fn opengauss_sequence_last_values_sql() -> &'static str { "SELECT c.relname, (pg_sequence_last_value(c.oid)).last_value::text \ FROM pg_class c \ @@ -8018,15 +8051,58 @@ async fn list_sequences_with_sql( } pub async fn list_sequences(pool: &Pool, schema: &str, with_last_values: bool) -> Result, String> { - // PostgreSQL 10+ stores sequence properties in pg_sequence. - list_sequences_with_sql( - pool, - schema, - with_last_values, - postgres_sequences_sql(), - postgres_sequence_last_values_sql(), - ) - .await + let client = checkout_postgres_client(pool, None, super::connection_timeout()).await?; + + // PostgreSQL 10+ stores sequence properties in pg_sequence; older servers + // fall back to the portable information_schema.sequences view. + let (rows, is_legacy) = match postgres_query_cached(&client, postgres_sequences_sql(), &[&schema]).await { + Ok(rows) => (rows, false), + Err(primary_error) => match postgres_query_cached(&client, postgres_sequences_compat_sql(), &[&schema]).await { + Ok(rows) => { + log::debug!( + "[postgres][sequences:compat-used] pg_sequence catalog unavailable ({}); serving sequence metadata from information_schema.sequences", + pg_error_to_string(primary_error) + ); + (rows, true) + } + Err(_) => return Err(primary_error.to_string()), + }, + }; + + let mut sequences: Vec = rows + .iter() + .map(|row| SequenceInfo { + name: pg_row_try_string(row, 0), + data_type: pg_row_try_string(row, 1), + start_value: pg_row_try_string(row, 2), + min_value: pg_row_try_string(row, 3), + max_value: pg_row_try_string(row, 4), + increment: pg_row_try_string(row, 5), + cycle: pg_row_try_string(row, 6) == "YES", + last_value: None, + }) + .collect(); + + if with_last_values { + if is_legacy { + for seq in sequences.iter_mut() { + if let Ok(Some(value)) = postgres_sequence_last_value_compat(&client, schema, &seq.name).await { + seq.last_value = Some(value); + } + } + } else if let Ok(rows) = postgres_query_cached(&client, postgres_sequence_last_values_sql(), &[&schema]).await { + for row in rows { + let name: String = pg_row_try_string(&row, 0); + if let Ok(Some(value)) = row.try_get::<_, Option>(1) { + if let Some(seq) = sequences.iter_mut().find(|s| s.name == name) { + seq.last_value = Some(value); + } + } + } + } + } + + Ok(sequences) } pub async fn list_opengauss_sequences( @@ -9511,6 +9587,16 @@ mod tests { } async fn start_docker_postgres() -> Option { + start_docker_postgres_image("postgres:16-alpine", &[]).await + } + + // PostgreSQL 9.3 (pre-pg_sequence/pg_sequence_last_value) only ships an + // amd64 image, so Apple Silicon hosts need explicit emulation. + async fn start_docker_postgres_9_3() -> Option { + start_docker_postgres_image("postgres:9.3", &["--platform", "linux/amd64"]).await + } + + async fn start_docker_postgres_image(image: &str, extra_args: &[&str]) -> Option { if !docker_ready() { eprintln!("skipping docker-backed postgres test because Docker is unavailable"); return None; @@ -9520,12 +9606,9 @@ mod tests { let container = DockerPostgres { name: format!("dbx-postgres-enum-{}", uuid::Uuid::new_v4()), port }; let status = Command::new("docker") + .args(["run", "-d", "--rm", "--name", &container.name]) + .args(extra_args) .args([ - "run", - "-d", - "--rm", - "--name", - &container.name, "-e", "POSTGRES_PASSWORD=postgres", "-e", @@ -9534,7 +9617,7 @@ mod tests { "POSTGRES_DB=postgres", "-p", &format!("{port}:5432"), - "postgres:16-alpine", + image, ]) .status() .expect("start docker postgres"); @@ -11332,6 +11415,33 @@ mod tests { assert!(postgres_sequence_last_values_sql().contains("pg_sequence_last_value(c.oid)::text")); } + #[test] + fn postgres_sequences_compat_sql_avoids_pg10_only_catalog() { + let sql = postgres_sequences_compat_sql(); + assert!(!sql.contains("pg_sequence")); + assert!(sql.contains("information_schema.sequences")); + assert!(sql.contains("sequence_schema = $1")); + } + + #[tokio::test] + async fn list_sequences_falls_back_on_postgres_9_without_pg_sequence_catalog() { + let Some(container) = start_docker_postgres_9_3().await else { + return; + }; + + let pool = connect(&container.url(), Duration::from_secs(5)).await.expect("connect postgres 9.3"); + execute_query(&pool, "CREATE SEQUENCE demo_seq START 5").await.expect("create sequence"); + execute_query(&pool, "SELECT nextval('demo_seq')").await.expect("advance sequence"); + + let sequences = list_sequences(&pool, "public", true).await.expect("list_sequences should not 500 on PG9"); + + let demo_seq = sequences.iter().find(|s| s.name == "demo_seq").expect("demo_seq present"); + assert_eq!(demo_seq.last_value.as_deref(), Some("5")); + assert_eq!(demo_seq.start_value, "5"); + assert_eq!(demo_seq.increment, "1"); + assert!(!demo_seq.cycle); + } + #[test] fn extension_member_query_filters_only_owned_relations_and_routines() { let sql = list_extension_member_objects_sql();