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:
2026-11-15 12:29:48 +07:00
parent fb277249f7
commit 43709aeeab
9 changed files with 565 additions and 31 deletions

View File

@@ -359,6 +359,33 @@ impl Hub {
.await?
}
/// Like `post` for a restore report, with the reason for a failure in a header.
pub(super) async fn post_with_reason(
self: &Arc<Self>,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String> {
let hub = Arc::clone(self);
tokio::task::spawn_blocking(move || {
let restore = restore.to_string();
let mut headers = vec![
("x-tessera-upload-token", hub.token.as_str()),
("x-tessera-restore-token", restore.as_str()),
];
if let Some(reason) = reason.as_deref() {
headers.push((tessera_core::restore::FAILURE_REASON_HEADER, reason));
}
http::post_json(
&format!("{}/api/v1/wormhole/{path}", hub.url),
&body,
&headers,
)
})
.await?
}
async fn report(
self: &Arc<Self>,
lease: &CaptureLease,

View File

@@ -117,8 +117,8 @@ async fn run(
.await;
let script = match downloaded {
Ok(Ok(script)) => script,
_ => {
report(hub, lease, RestoreProgress::InvalidPayload).await?;
other => {
report_failed(hub, lease, RestoreProgress::InvalidPayload, why(other)).await?;
return Ok(());
}
};
@@ -144,8 +144,8 @@ async fn run(
.await;
let identity = match verified {
Ok(Ok(identity)) => identity,
_ => {
report(hub, lease, RestoreProgress::WrongTarget).await?;
other => {
report_failed(hub, lease, RestoreProgress::WrongTarget, why(other)).await?;
return Ok(());
}
};
@@ -171,7 +171,7 @@ async fn run(
})
.await;
if !matches!(safety, Ok(Ok(()))) {
report(hub, lease, RestoreProgress::SafetyFailed).await?;
report_failed(hub, lease, RestoreProgress::SafetyFailed, why(safety)).await?;
return Ok(());
}
@@ -182,20 +182,35 @@ async fn run(
Some(lease.token),
)
.await?;
let applied = matches!(
tokio::time::timeout(timeout, target.apply(script)).await,
Ok(Ok(()))
);
report(
hub,
lease,
if applied {
RestoreProgress::Applied
} else {
RestoreProgress::ApplyFailed
},
match tokio::time::timeout(timeout, target.apply(script)).await {
Ok(Ok(())) => report(hub, lease, RestoreProgress::Applied).await,
other => report_failed(hub, lease, RestoreProgress::ApplyFailed, why(other)).await,
}
}
/// Why a step did not succeed, in words: the error chain, or that it ran out of time.
fn why<T>(result: Result<Result<T>, tokio::time::error::Elapsed>) -> String {
match result {
Ok(Ok(_)) => "unknown".into(),
Ok(Err(error)) => format!("{error:#}"),
Err(_) => "timed out".into(),
}
}
async fn report_failed(
hub: &Arc<Hub>,
lease: &RestoreLease,
progress: RestoreProgress,
reason: String,
) -> Result<()> {
hub.post_with_reason(
format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?,
lease.token,
tessera_core::restore::clean_failure_reason(&reason),
)
.await
.await?;
Ok(())
}
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> {

View File

@@ -79,6 +79,9 @@ pub struct RestoreJob {
pub safety_snapshot_id: Option<Uuid>,
pub created_at: i64,
pub updated_at: i64,
/// Why the job failed, as the agent reported it (cleaned). Only administrators ever see it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure_reason: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
@@ -95,6 +98,27 @@ pub struct RestoreLease {
pub artifact: RestoreArtifact,
}
/// Header on a restore report that carries the reason for a failure.
pub const FAILURE_REASON_HEADER: &str = "x-tessera-failure-reason";
const FAILURE_REASON_MAX: usize = 300;
/// Make a failure reason safe to store, log and send in a header: printable ASCII on one line, at most 300
/// bytes. Anything else becomes a space (control characters) or `?` (non-ASCII). Empty input gives `None`.
pub fn clean_failure_reason(text: &str) -> Option<String> {
let mapped: String = text
.chars()
.map(|c| match c {
c if c.is_ascii_graphic() => c,
c if c.is_ascii() => ' ',
_ => '?',
})
.collect();
let line = mapped.split_whitespace().collect::<Vec<_>>().join(" ");
let line: String = line.chars().take(FAILURE_REASON_MAX).collect();
let line = line.trim_end().to_string();
(!line.is_empty()).then_some(line)
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RestoreProgress {

View File

@@ -412,6 +412,10 @@ impl Lab {
assert_eq!(status, StatusCode::NO_CONTENT);
}
fn audit_log(&self) -> Vec<(String, String)> {
self.state.db.audit_log_events()
}
fn restore_jobs(&self) -> i64 {
self.scalar("SELECT COUNT(*) FROM restore_jobs")
}
@@ -1518,3 +1522,125 @@ async fn only_an_administrator_can_change_a_profile() {
StatusCode::UNAUTHORIZED
);
}
// ---- why a restore failed ----
impl Lab {
async fn report_with_reason(
&self,
job: &str,
token: &str,
progress: &str,
reason: &str,
) -> StatusCode {
self.agent_json(
"POST",
&format!("/api/v1/wormhole/restore/{job}/report"),
&[
("x-tessera-restore-token", token.to_string()),
("x-tessera-failure-reason", reason.to_string()),
],
json!(progress),
)
.await
.0
}
}
#[tokio::test]
async fn a_failed_restore_says_why_to_administrators_only() {
let lab = fresh().await;
let (qa, _) = lab.refresher("qa");
let run = lab.start(&qa, "why").await.1["id"]
.as_str()
.unwrap()
.to_string();
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, token) = lab.restore_until_ready().await.unwrap();
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
let reason = "psql failed (exit status: 3): ERROR: schema \"drizzle\" already exists";
assert_eq!(
lab.report_with_reason(&job, &token, "apply_failed", reason)
.await,
StatusCode::NO_CONTENT
);
let (status, view) = lab
.send(
&lab.admin(),
"GET",
&format!("/api/v1/restore-jobs/{job}"),
None,
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(view["phase"], "apply_failed");
// whitespace is normalised on the way in (psql pads "ERROR: ")
assert_eq!(
view["failure_reason"],
"psql failed (exit status: 3): ERROR: schema \"drizzle\" already exists"
);
assert!(lab
.audit_log()
.iter()
.any(|(event, detail)| event == "restore.failed" && detail.contains("drizzle")));
// the person who started the refresh sees that it failed, never the database's own words
lab.tick().await;
let (_, seen) = lab
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{run}"), None)
.await;
assert_eq!(seen["status"], "recovery_required", "{seen}");
assert!(
!seen.to_string().contains("drizzle") && seen.get("failure_reason").is_none(),
"{seen}"
);
}
#[tokio::test]
async fn a_failure_reason_is_only_kept_for_failures_and_is_cleaned_and_bounded() {
let lab = fresh().await;
lab.start(&lab.admin(), "clean").await;
lab.capture(&Lab::production_identity(), false)
.await
.unwrap();
lab.tick().await;
let (job, token) = lab.restore_until_ready().await.unwrap();
// a heartbeat that carries a reason does not create one
assert_eq!(
lab.report_with_reason(&job, &token, "heartbeat", "ignored")
.await,
StatusCode::NO_CONTENT
);
let admin = lab.admin();
let uri = format!("/api/v1/restore-jobs/{job}");
assert!(lab
.send(&admin, "GET", &uri, None)
.await
.1
.get("failure_reason")
.is_none());
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
let long = format!("ERROR:\t{}\tend", "x".repeat(2000));
assert_eq!(
lab.report_with_reason(&job, &token, "apply_failed", &long)
.await,
StatusCode::NO_CONTENT
);
let reason = lab.send(&admin, "GET", &uri, None).await.1["failure_reason"]
.as_str()
.unwrap()
.to_string();
assert!(
reason.len() <= 300 && reason.starts_with("ERROR: xxx"),
"{}",
reason.len()
);
assert!(
reason.chars().all(|c| c.is_ascii() && !c.is_control()),
"{reason:?}"
);
}

View File

@@ -365,13 +365,22 @@ async fn report(
) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
// Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not
// with what ends up in the database and the log.
let reason = headers
.get(tessera_core::restore::FAILURE_REASON_HEADER)
.and_then(|value| value.to_str().ok())
.and_then(tessera_core::restore::clean_failure_reason);
if !state
.db
.report_restore(outpost, id, token, progress, now())
.report_restore(outpost, id, token, progress, reason.as_deref(), now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
if let Some(reason) = &reason {
tracing::warn!(job = %id, ?progress, %reason, "restore step failed");
}
Ok(StatusCode::NO_CONTENT)
}

View File

@@ -27,17 +27,20 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
lease_token TEXT,
lease_until INTEGER,
attempt_safety_id TEXT,
safety_id TEXT
safety_id TEXT,
failure_reason TEXT
);
CREATE INDEX IF NOT EXISTS restore_jobs_target ON restore_jobs(target_id, status);
CREATE INDEX IF NOT EXISTS restore_jobs_snapshot ON restore_jobs(snapshot_id, safety_id, status);",
)?;
// databases created before failure reasons existed
ensure_column(conn, "restore_jobs", "failure_reason", "TEXT")?;
Ok(())
}
const VIEW: &str =
"SELECT j.id, j.snapshot_id, t.profile, j.actor, j.status, j.phase, j.safety_id, j.created_at,
j.updated_at, j.artifact, j.attempt_safety_id
j.updated_at, j.artifact, j.attempt_safety_id, j.failure_reason
FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
@@ -63,6 +66,7 @@ fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
.map_err(|err| invalid_column(6, err))?,
created_at: row.get(7)?,
updated_at: row.get(8)?,
failure_reason: row.get(11)?,
})
}
@@ -319,6 +323,7 @@ impl Db {
id: Uuid,
token: Uuid,
progress: RestoreProgress,
reason: Option<&str>,
now: i64,
) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
@@ -348,6 +353,24 @@ impl Db {
if !matches!(progress, RestoreProgress::Heartbeat) {
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?;
}
let failed = matches!(
progress,
RestoreProgress::InvalidPayload
| RestoreProgress::WrongTarget
| RestoreProgress::SafetyFailed
| RestoreProgress::ApplyFailed
);
if let (true, Some(reason)) = (failed, reason) {
tx.execute(
"UPDATE restore_jobs SET failure_reason = ?2 WHERE id = ?1",
params![id.to_string(), reason],
)?;
audit(
&tx,
"restore.failed",
&format!("job={id} phase={phase} reason={reason}"),
)?;
}
tx.commit()?;
Ok(true)
}
@@ -568,10 +591,24 @@ mod tests {
.authorize_apply(outpost, job.id, lease.token, 104)
.unwrap());
assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104)
.report_restore(
outpost,
job.id,
lease.token,
RestoreProgress::Checking,
None,
104
)
.unwrap());
assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105)
.report_restore(
outpost,
job.id,
lease.token,
RestoreProgress::Safety,
None,
105
)
.unwrap());
assert!(db
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(

View File

@@ -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;

View File

@@ -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"
);
}
}