feat: say why a restore failed, and add the user_schemas reset mode
- the agent reports the client's primary ERROR/FATAL line with a failed restore step; the hub keeps it as failure_reason (administrators only), logs it and audits restore.failed. psql runs with VERBOSITY=terse and DETAIL/CONTEXT/statement text is dropped so row data never travels - reset mode user_schemas empties every non-system schema in the restore transaction, so multi-schema databases restore without DROP DATABASE; proven against a real PostgreSQL server Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -292,7 +292,7 @@ async fn run_pg(
|
||||
.env_remove("PGPASSWORD")
|
||||
.stdin(process.stdin)
|
||||
.stdout(process.stdout)
|
||||
.stderr(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.context("starting PostgreSQL client")?
|
||||
@@ -301,13 +301,41 @@ async fn run_pg(
|
||||
.context("waiting for PostgreSQL client")?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"{} failed ({})",
|
||||
"{} failed ({}){}",
|
||||
process.program,
|
||||
output.status
|
||||
output.status,
|
||||
client_reason(&output.stderr)
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// The reason a PostgreSQL client gave for failing, reduced to what is safe to report: only the primary
|
||||
/// `ERROR:`/`FATAL:` lines. `DETAIL`, `CONTEXT`, `LINE`, `STATEMENT` and `HINT` are left out because they
|
||||
/// quote rows and statements, and the location prefix (`psql:-:1234:`) is not needed. At most two lines.
|
||||
pub(crate) fn client_reason(stderr: &[u8]) -> String {
|
||||
let text = String::from_utf8_lossy(stderr);
|
||||
let lines: Vec<String> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let line = line.trim();
|
||||
let line = match line.find(": ").filter(|_| line.starts_with("psql:")) {
|
||||
Some(_) => line.splitn(4, ':').nth(3).unwrap_or(line).trim(),
|
||||
None => line,
|
||||
};
|
||||
let primary = ["ERROR:", "FATAL:", "pg_dump: error:", "pg_restore: error:"]
|
||||
.iter()
|
||||
.any(|prefix| line.starts_with(prefix));
|
||||
primary.then(|| line.to_string())
|
||||
})
|
||||
.take(2)
|
||||
.collect();
|
||||
if lines.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(": {}", lines.join(" | "))
|
||||
}
|
||||
}
|
||||
|
||||
fn write_pgpass(target: &PgTarget, any_database: bool) -> Result<tempfile::NamedTempFile> {
|
||||
let fields = [
|
||||
&target.host,
|
||||
@@ -358,6 +386,23 @@ impl BackupProvider for PostgresProvider {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_client_failure_names_its_error_without_quoting_data() {
|
||||
let stderr =
|
||||
b"psql:-:42: ERROR: duplicate key value violates unique constraint \"users_pkey\"\n\
|
||||
DETAIL: Key (email)=(alice@example.test) already exists.\n\
|
||||
CONTEXT: COPY users, line 7: \"7\\talice@example.test\"\n\
|
||||
psql:-:99: ERROR: schema \"drizzle\" already exists\n";
|
||||
let reason = client_reason(stderr);
|
||||
assert_eq!(
|
||||
reason,
|
||||
": ERROR: duplicate key value violates unique constraint \"users_pkey\" | ERROR: schema \"drizzle\" already exists"
|
||||
);
|
||||
assert!(!reason.contains("alice") && !reason.contains("COPY"));
|
||||
assert_eq!(client_reason(b""), "");
|
||||
assert_eq!(client_reason(b"just noise\n"), "");
|
||||
}
|
||||
|
||||
use super::*;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
|
||||
@@ -20,6 +20,11 @@ pub enum PostgresReset {
|
||||
#[serde(default = "public")]
|
||||
schema: String,
|
||||
},
|
||||
/// Empty every non-system schema of the database (not only `public`), in the same transaction as the
|
||||
/// restore. For databases that keep tables in several schemas, so that a dump's `CREATE SCHEMA` for
|
||||
/// one of them does not collide with the copy already there. Roles, extensions' own catalog entries,
|
||||
/// publications and other objects that live outside schemas are left alone.
|
||||
UserSchemas,
|
||||
RecreateDatabase,
|
||||
}
|
||||
|
||||
@@ -118,6 +123,15 @@ impl PostgresRestore {
|
||||
writeln!(script, "CREATE SCHEMA public;")?;
|
||||
}
|
||||
}
|
||||
PostgresReset::UserSchemas => {
|
||||
writeln!(script, "BEGIN;")?;
|
||||
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
|
||||
writeln!(
|
||||
script,
|
||||
"DO $tessera$\nDECLARE s text;\nBEGIN\n FOR s IN SELECT nspname FROM pg_catalog.pg_namespace\n WHERE nspname !~ '^pg_' AND nspname <> 'information_schema'\n LOOP\n EXECUTE pg_catalog.format('DROP SCHEMA %I CASCADE', s);\n END LOOP;\nEND\n$tessera$;"
|
||||
)?;
|
||||
writeln!(script, "CREATE SCHEMA public;")?;
|
||||
}
|
||||
PostgresReset::RecreateDatabase => {
|
||||
ensure!(
|
||||
expected
|
||||
@@ -141,8 +155,11 @@ impl PostgresRestore {
|
||||
writeln!(script, "\\restrict {key}")?;
|
||||
let skip_timeout = self.omit_transaction_timeout;
|
||||
let skip_extension = self.omit_pg_stat_statements;
|
||||
let create_public =
|
||||
matches!(&self.mode, PostgresReset::Schema { schema } if schema == "public");
|
||||
let create_public = match &self.mode {
|
||||
PostgresReset::Schema { schema } => schema == "public",
|
||||
PostgresReset::UserSchemas => true,
|
||||
PostgresReset::RecreateDatabase => false,
|
||||
};
|
||||
let post_sql = self.post_restore_sql.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
append_dump(
|
||||
@@ -168,9 +185,21 @@ impl PostgresRestore {
|
||||
pub async fn apply(&self, script: File) -> Result<()> {
|
||||
let database = match self.mode {
|
||||
PostgresReset::RecreateDatabase => Some("postgres"),
|
||||
PostgresReset::Schema { .. } => None,
|
||||
PostgresReset::Schema { .. } | PostgresReset::UserSchemas => None,
|
||||
};
|
||||
let args = ["-X", "-w", "-q", "-v", "ON_ERROR_STOP=1", "-f", "-"].map(String::from);
|
||||
// VERBOSITY=terse keeps psql from quoting statements and row data in its errors
|
||||
let args = [
|
||||
"-X",
|
||||
"-w",
|
||||
"-q",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-v",
|
||||
"VERBOSITY=terse",
|
||||
"-f",
|
||||
"-",
|
||||
]
|
||||
.map(String::from);
|
||||
self.connection
|
||||
.run("psql", &args, database, Stdio::from(script), Stdio::null())
|
||||
.await?;
|
||||
@@ -263,3 +292,223 @@ fn append_dump(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
|
||||
fn restore(mode: &str) -> PostgresRestore {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"connection": {"host": "127.0.0.1", "port": 5432, "database": "app", "user": "u",
|
||||
"password_file": "/nonexistent", "tls": {"mode": "disable"}},
|
||||
"mode": serde_json::from_str::<serde_json::Value>(mode).unwrap(),
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn script(restore: &PostgresRestore) -> String {
|
||||
let mut dump = tempfile::tempfile().unwrap();
|
||||
writeln!(
|
||||
dump,
|
||||
"CREATE SCHEMA drizzle;\nCREATE SCHEMA public;\nCREATE TABLE drizzle.t (id int);"
|
||||
)
|
||||
.unwrap();
|
||||
let identity = DatabaseIdentity {
|
||||
instance: "7300000000000000001".into(),
|
||||
database: "app".into(),
|
||||
};
|
||||
let mut file = restore
|
||||
.prepare(dump, CaptureFormat::PostgresSql, &identity)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut text = String::new();
|
||||
file.read_to_string(&mut text).unwrap();
|
||||
text
|
||||
}
|
||||
|
||||
fn psql_with_restricted_mode() -> bool {
|
||||
std::process::Command::new("psql")
|
||||
.arg("--help=commands")
|
||||
.output()
|
||||
.is_ok_and(|out| String::from_utf8_lossy(&out.stdout).contains("\\restrict"))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_schemas_mode_empties_every_non_system_schema_inside_the_transaction() {
|
||||
if !psql_with_restricted_mode() {
|
||||
return;
|
||||
}
|
||||
let text = script(&restore(r#"{"reset": "user_schemas"}"#)).await;
|
||||
let begin = text.find("BEGIN;").unwrap();
|
||||
let identity_check = text.find("pg_control_system()").unwrap();
|
||||
let drop_all = text
|
||||
.find("DROP SCHEMA %I CASCADE")
|
||||
.expect("drops schemas by name");
|
||||
let dump = text.find("CREATE SCHEMA drizzle;").unwrap();
|
||||
assert!(
|
||||
begin < identity_check && identity_check < drop_all && drop_all < dump,
|
||||
"{text}"
|
||||
);
|
||||
// system schemas are never touched
|
||||
assert!(
|
||||
text.contains("nspname !~ '^pg_'") && text.contains("nspname <> 'information_schema'")
|
||||
);
|
||||
// public is created once by us; the dump's own CREATE becomes harmless
|
||||
assert_eq!(text.matches("CREATE SCHEMA public;").count(), 1, "{text}");
|
||||
assert!(text.contains("CREATE SCHEMA IF NOT EXISTS public;"));
|
||||
assert!(text.trim_end().contains("COMMIT;"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn schema_mode_still_only_drops_the_one_schema() {
|
||||
if !psql_with_restricted_mode() {
|
||||
return;
|
||||
}
|
||||
let text = script(&restore(r#"{"reset": "schema", "schema": "public"}"#)).await;
|
||||
assert!(text.contains("DROP SCHEMA IF EXISTS \"public\" CASCADE;"));
|
||||
assert!(!text.contains("DROP SCHEMA %I"));
|
||||
}
|
||||
|
||||
async fn prepared(restore: &PostgresRestore, dump: &[u8], identity: &DatabaseIdentity) -> File {
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
file.write_all(dump).unwrap();
|
||||
restore
|
||||
.prepare(file, CaptureFormat::PostgresSql, identity)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn sh(port: &str, db: &str, sql: &str) -> String {
|
||||
let out = std::process::Command::new("psql")
|
||||
.args([
|
||||
"-X",
|
||||
"-q",
|
||||
"-At",
|
||||
"-h",
|
||||
"127.0.0.1",
|
||||
"-p",
|
||||
port,
|
||||
"-U",
|
||||
"postgres",
|
||||
"-d",
|
||||
db,
|
||||
"-c",
|
||||
sql,
|
||||
])
|
||||
.env("PGPASSWORD", "pw")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{sql}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
/// Needs a throwaway PostgreSQL server (user `postgres`, password `pw`) whose port is in
|
||||
/// `TESSERA_TEST_PG_PORT`. Run with `--ignored`.
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn multi_schema_databases_restore_with_user_schemas_and_fail_readably_without() {
|
||||
let port = std::env::var("TESSERA_TEST_PG_PORT").expect("TESSERA_TEST_PG_PORT");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let password = dir.path().join("pw");
|
||||
fs::write(&password, "pw\n").unwrap();
|
||||
for db in ["src_db", "dst_db"] {
|
||||
sh(&port, "postgres", &format!("DROP DATABASE IF EXISTS {db}"));
|
||||
sh(&port, "postgres", &format!("CREATE DATABASE {db}"));
|
||||
}
|
||||
// the source: public plus a second schema, like an app that keeps its migrations in `drizzle`
|
||||
sh(&port, "src_db", "CREATE SCHEMA drizzle; CREATE TABLE drizzle.migrations (id int, hash text); INSERT INTO drizzle.migrations VALUES (1, 'a'), (2, 'b'); CREATE TABLE public.users (id int, email text); INSERT INTO public.users VALUES (1, 'alice@example.test')");
|
||||
// the target: already has `drizzle`, a dev-only table in it, and a stale public table
|
||||
sh(&port, "dst_db", "CREATE SCHEMA drizzle; CREATE TABLE drizzle.roles (id int); CREATE SCHEMA extra; CREATE TABLE extra.t (id int); CREATE TABLE public.stale (id int)");
|
||||
let dump = std::process::Command::new("pg_dump")
|
||||
.args([
|
||||
"-h",
|
||||
"127.0.0.1",
|
||||
"-p",
|
||||
&port,
|
||||
"-U",
|
||||
"postgres",
|
||||
"-d",
|
||||
"src_db",
|
||||
"--no-owner",
|
||||
"--no-acl",
|
||||
"-Fp",
|
||||
])
|
||||
.env("PGPASSWORD", "pw")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(dump.status.success());
|
||||
let sid = sh(
|
||||
&port,
|
||||
"dst_db",
|
||||
"SELECT system_identifier FROM pg_control_system()",
|
||||
);
|
||||
let identity = DatabaseIdentity {
|
||||
instance: sid,
|
||||
database: "dst_db".into(),
|
||||
};
|
||||
let target = |mode: serde_json::Value| -> PostgresRestore {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"connection": {"host": "127.0.0.1", "port": port.parse::<u16>().unwrap(), "database": "dst_db", "user": "postgres",
|
||||
"password_file": password, "tls": {"mode": "disable"}},
|
||||
"mode": mode,
|
||||
}))
|
||||
.unwrap()
|
||||
};
|
||||
// 1. `schema` mode on a multi-schema database: fails, says why, and changes nothing
|
||||
let one = target(serde_json::json!({"reset": "schema"}));
|
||||
let error = one
|
||||
.apply(prepared(&one, &dump.stdout, &identity).await)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(
|
||||
error.contains("ERROR:") && error.contains("already exists"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
!error.contains("alice"),
|
||||
"no row data in the reason: {error}"
|
||||
);
|
||||
assert_eq!(
|
||||
sh(&port, "dst_db", "SELECT count(*) FROM drizzle.roles"),
|
||||
"0"
|
||||
);
|
||||
assert_eq!(
|
||||
sh(
|
||||
&port,
|
||||
"dst_db",
|
||||
"SELECT count(*) FROM information_schema.tables WHERE table_name = 'stale'"
|
||||
),
|
||||
"1"
|
||||
);
|
||||
|
||||
// 2. `user_schemas` mode: the database becomes the source, nothing of the old target survives
|
||||
let all = target(serde_json::json!({"reset": "user_schemas"}));
|
||||
all.apply(prepared(&all, &dump.stdout, &identity).await)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sh(&port, "dst_db", "SELECT count(*) FROM drizzle.migrations"),
|
||||
"2"
|
||||
);
|
||||
assert_eq!(
|
||||
sh(&port, "dst_db", "SELECT email FROM public.users"),
|
||||
"alice@example.test"
|
||||
);
|
||||
let names = sh(&port, "dst_db", "SELECT string_agg(table_schema || '.' || table_name, ',' ORDER BY 1) FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog','information_schema')");
|
||||
assert_eq!(names, "drizzle.migrations,public.users");
|
||||
assert_eq!(
|
||||
sh(
|
||||
&port,
|
||||
"dst_db",
|
||||
"SELECT count(*) FROM pg_namespace WHERE nspname = 'extra'"
|
||||
),
|
||||
"0"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user