Files
windmill/backend/windmill-api-workspaces/src/datatable_extensions.rs
T
76bfdf32a9 feat: let a data table name tables its forks copy without rows (#12825)
* feat: let a data table name tables its forks copy without rows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: leave hierarchical continuous aggregates out and recheck patterns after the dump

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: point at the replay change of the companion EE branch

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: match only chunk names when leaving a hypertable's chunks out

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: update ee-repo-ref to 2afccf8964aef7d7d318d6a14868a0757dbc0e13

This commit updates the EE repository reference after PR #1045 was merged in windmill-ee-private.

Previous ee-repo-ref: dd7749a6d20e777e7e27bf0a2e27f5ac9ac4d0b1

New ee-repo-ref: 2afccf8964aef7d7d318d6a14868a0757dbc0e13

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
2026-12-02 23:08:59 +01:00

817 lines
32 KiB
Rust

/*
* Author: Ruben Fiszel
* Copyright: Windmill Labs, Inc 2022
* This file and its contents are licensed under the AGPLv3 License.
* Please see the included NOTICE for copyright information and
* LICENSE-AGPL for a copy of the license.
*/
//! Copying a database that uses extensions.
//!
//! A copy is replayed as the target's own connection role, which can neither create an extension
//! only a superuser may create nor comment on one it does not own, and `pg_dump` writes both for
//! every extension. So the dump leaves extensions out, and the copy is given them first: by its
//! cluster's administrator when Windmill manages it, as it creates the database
//! ([`ExtensionPlan::database_extensions`]), by the target's role otherwise.
//!
//! The dump is an archive, and what of it is replayed is chosen entry by entry, by the source
//! object each entry is for ([`ExtensionPlan::skipped_entries`]).
use std::collections::BTreeSet;
use std::io::Write;
use windmill_common::error::{pg_error_message, Error, Result};
use windmill_common::{DatabaseExtension, PgDatabase, DB};
use crate::workspaces::{
pg_dump_database, pg_import_dump, pg_restore_list, pg_restore_script, DumpFile, PgDumpOptions,
};
const TIMESCALEDB: &str = "timescaledb";
const TIMESCALEDB_INTERNAL: &str = "_timescaledb_internal";
/// What a copy of one database needs done about the extensions it uses.
#[derive(Default)]
pub(crate) struct ExtensionPlan {
/// In creation order, so an extension comes after those it requires.
extensions: Vec<DatabaseExtension>,
/// Schemas holding an extension that the dump creates too. The copy needs them before its
/// extensions, so they are made first, with their comments, and the dump's `CREATE SCHEMA` and
/// `COMMENT ON SCHEMA` are not replayed: the copy's role may not own one it did not make.
extension_schemas: Vec<String>,
/// The source objects whose archive entries are not replayed, as `(catalog oid, object oid)`.
skipped_entries: BTreeSet<(u32, u32)>,
/// The data table's `schema_only_tables` patterns, in a copy with data.
patterns: Vec<String>,
/// The tables a copy with data copies without rows, as `(schema, name)`.
schema_only_tables: BTreeSet<(String, String)>,
/// The data table's `schema_only_tables` patterns that match no table.
unmatched_patterns: Vec<String>,
/// The TimescaleDB id of every hypertable, its continuous aggregates' included.
hypertables: BTreeSet<i32>,
/// The quoted `"schema"."prefix_"` each hypertable's chunks are named with.
chunk_prefixes: Vec<String>,
/// The hypertables users made, quoted, which the copy has as plain tables.
plain_hypertables: Vec<String>,
/// Continuous aggregates and the views built on them, quoted: the copy goes without them.
left_out_views: Vec<String>,
}
fn quote_ident(name: &str) -> String {
format!("\"{}\"", name.replace('"', "\"\""))
}
fn source_err(dbname: &str) -> impl FnOnce(tokio_postgres::Error) -> Error + '_ {
move |e| {
Error::internal_err(format!(
"Failed to read the extensions of database '{dbname}': {}",
pg_error_message(&e)
))
}
}
/// Read what copying `source` takes: its extensions and the tables it copies without rows.
/// Refuses, before anything is created, what a copy cannot carry.
pub(crate) async fn read_extension_plan(
db: &DB,
source: &PgDatabase,
schema_only: bool,
schema_only_tables: &[String],
) -> Result<ExtensionPlan> {
let (client, connection) = source.connect(Some(db)).await?;
let join_handle = tokio::spawn(async move { connection.await });
let plan = read_plan(&client, &source.dbname, schema_only, schema_only_tables).await;
drop(client);
windmill_common::shutdown_pg_connection(join_handle).await?;
plan
}
async fn read_plan(
client: &tokio_postgres::Client,
dbname: &str,
schema_only: bool,
schema_only_tables: &[String],
) -> Result<ExtensionPlan> {
// An extension's schema is dumped unless it is Postgres's own, `public`, which every database
// already has, or one an extension created as part of itself.
let rows = client
.query(
"SELECT e.extname::text, n.nspname::text,
n.nspname NOT IN ('public', 'pg_catalog') AND NOT EXISTS (
SELECT 1 FROM pg_depend d
WHERE d.classid = 'pg_namespace'::regclass AND d.objid = n.oid
AND d.deptype = 'e'),
'pg_namespace'::regclass::oid, n.oid, obj_description(n.oid, 'pg_namespace')
FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace
WHERE e.extname <> 'plpgsql'
ORDER BY e.oid",
&[],
)
.await
.map_err(source_err(dbname))?;
let mut plan = ExtensionPlan::default();
let mut extension_schemas = BTreeSet::new();
for row in rows {
let dumped_schema = row.get::<_, bool>(2);
if dumped_schema {
extension_schemas.insert(row.get::<_, String>(1));
plan.skipped_entries.insert((row.get(3), row.get(4)));
}
plan.extensions.push(DatabaseExtension {
name: row.get(0),
schema: row.get(1),
schema_comment: if dumped_schema { row.get(5) } else { None },
});
}
plan.extension_schemas = extension_schemas.into_iter().collect();
if !schema_only {
read_schema_only_tables(client, dbname, schema_only_tables, &mut plan).await?;
}
if plan.uses_timescaledb() {
read_hypertables(client, dbname, schema_only, &mut plan).await?;
}
if !schema_only {
refuse_extension_rows(client, dbname).await?;
}
Ok(plan)
}
/// Refuse a copy with data of a database whose extensions' configuration tables hold rows of its
/// users, such as PostGIS's custom spatial references: leaving the extensions out of the dump
/// leaves those rows out too, and the copy's role could not write them anyway. TimescaleDB's always
/// hold bookkeeping its copy in the new database writes again, and its hypertables are read on
/// their own.
async fn refuse_extension_rows(client: &tokio_postgres::Client, dbname: &str) -> Result<()> {
// `extcondition` is the filter pg_dump applies to pick the rows that are the user's.
let tables = client
.query(
"SELECT e.extname::text, c.oid::regclass::text, COALESCE(e.extcondition[i], '')
FROM pg_extension e
CROSS JOIN LATERAL generate_subscripts(e.extconfig, 1) AS i
JOIN pg_class c ON c.oid = e.extconfig[i]
WHERE c.relkind = 'r' AND e.extname <> $1
ORDER BY 1, 2",
&[&TIMESCALEDB],
)
.await
.map_err(source_err(dbname))?;
let mut holding = vec![];
for table in tables {
let (extension, relation, condition): (String, String, String) =
(table.get(0), table.get(1), table.get(2));
let has_rows: bool = client
.query_one(
&format!("SELECT EXISTS (SELECT 1 FROM {relation} {condition})"),
&[],
)
.await
.map_err(source_err(dbname))?
.get(0);
if has_rows {
holding.push(format!("{relation} of {extension}"));
}
}
if !holding.is_empty() {
return Err(Error::BadRequest(format!(
"Database '{dbname}' has rows of its own in tables of its extensions ({}), which a \
copy with data cannot carry: copy its schema only",
holding.join(", ")
)));
}
Ok(())
}
/// The tables `patterns` match, as `(pattern index from 1, the table and its oid)`, with no table
/// for a pattern that matches none.
async fn match_patterns(
client: &tokio_postgres::Client,
dbname: &str,
patterns: &[String],
) -> Result<Vec<(i64, Option<(String, String, u32)>)>> {
let (schemas, names): (Vec<String>, Vec<String>) = patterns
.iter()
.map(|p| windmill_common::workspaces::schema_only_table_like(p))
.unzip();
// `_wm_migrations` never matches: in a copy with data its rows are what tells the copy which
// migrations its schema already has. Nor does an extension's own table, whose rows are its.
let rows = client
.query(
"SELECT p.i, n.nspname::text, c.relname::text, c.oid
FROM unnest($1::text[], $2::text[]) WITH ORDINALITY AS p(schema_like, name_like, i)
LEFT JOIN (pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace)
ON c.relkind IN ('r', 'p', 'm')
AND n.nspname NOT IN ('pg_catalog', 'information_schema', $3)
AND n.nspname NOT LIKE 'pg\\_%'
AND c.relname <> '_wm_migrations'
AND NOT EXISTS (SELECT 1 FROM pg_depend x
WHERE x.classid = 'pg_class'::regclass AND x.objid = c.oid
AND x.deptype = 'e')
AND n.nspname LIKE p.schema_like AND c.relname LIKE p.name_like
ORDER BY 1, 2, 3",
&[&schemas, &names, &TIMESCALEDB_INTERNAL],
)
.await
.map_err(source_err(dbname))?;
Ok(rows
.iter()
.map(|row| {
let table = match (row.get(1), row.get(2), row.get(3)) {
(Some(schema), Some(name), Some(oid)) => Some((schema, name, oid)),
_ => None,
};
(row.get(0), table)
})
.collect())
}
/// Resolve the `schema_only_tables` patterns of the data table being copied to the tables they
/// match.
async fn read_schema_only_tables(
client: &tokio_postgres::Client,
dbname: &str,
patterns: &[String],
plan: &mut ExtensionPlan,
) -> Result<()> {
if patterns.is_empty() {
return Ok(());
}
plan.patterns = patterns.to_vec();
let mut oids: Vec<u32> = vec![];
for (i, table) in match_patterns(client, dbname, patterns).await? {
match table {
Some((schema, name, oid)) => {
plan.schema_only_tables.insert((schema, name));
oids.push(oid);
}
None => plan
.unmatched_patterns
.push(patterns[i as usize - 1].clone()),
}
}
// A foreign key checks the rows already there when post-data adds it, so a table copied with
// its rows cannot reference one copied without. The partitions and chunks of a matched table
// are copied without rows too.
let references: Vec<String> = client
.query(
"WITH RECURSIVE emptied(oid) AS (
SELECT unnest($1::oid[])
UNION
SELECT i.inhrelid FROM pg_inherits i JOIN emptied e ON i.inhparent = e.oid
)
SELECT DISTINCT format(
'%s references %s',
COALESCE(pg_partition_root(k.conrelid), k.conrelid::regclass),
COALESCE(pg_partition_root(k.confrelid), k.confrelid::regclass))
FROM pg_constraint k
WHERE k.contype = 'f'
AND k.confrelid IN (SELECT oid FROM emptied)
AND k.conrelid NOT IN (SELECT oid FROM emptied)
AND k.conrelid NOT IN (
SELECT c.oid FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = $2)
ORDER BY 1",
&[&oids, &TIMESCALEDB_INTERNAL],
)
.await
.map_err(source_err(dbname))?
.iter()
.map(|row| row.get(0))
.collect();
if !references.is_empty() {
return Err(Error::BadRequest(format!(
"Database '{dbname}' has tables copied with their rows that reference tables its \
schema_only_tables leave empty ({}): add the referencing tables to the patterns too",
references.join(", ")
)));
}
Ok(())
}
struct Hypertable {
/// TimescaleDB's id for it, which a hypertable made again under the same name does not keep.
id: i32,
schema: String,
name: String,
chunk_schema: String,
chunk_prefix: String,
/// Not a continuous aggregate's, nor one TimescaleDB keeps compressed chunks in.
users: bool,
}
async fn list_hypertables(
client: &tokio_postgres::Client,
dbname: &str,
) -> Result<Vec<Hypertable>> {
Ok(client
.query(
"SELECT h.id, h.schema_name::text, h.table_name::text,
h.associated_schema_name::text, h.associated_table_prefix::text,
NOT EXISTS (SELECT 1 FROM _timescaledb_catalog.continuous_agg a
WHERE a.mat_hypertable_id = h.id)
AND NOT EXISTS (SELECT 1 FROM _timescaledb_catalog.hypertable o
WHERE o.compressed_hypertable_id = h.id)
FROM _timescaledb_catalog.hypertable h
ORDER BY 2, 3",
&[],
)
.await
.map_err(source_err(dbname))?
.iter()
.map(|row| Hypertable {
id: row.get(0),
schema: row.get(1),
name: row.get(2),
chunk_schema: row.get(3),
chunk_prefix: row.get(4),
users: row.get(5),
})
.collect())
}
/// A hypertable's rows live in chunk tables and catalog rows of TimescaleDB's, in schemas only it
/// may write to, which a replay as the copy's role can neither write nor reproduce. So a copy has
/// only the hypertables it copies without rows, as plain empty tables: their chunks are left out,
/// and so are the triggers TimescaleDB put on them, which refuse writes to a plain table. A
/// continuous aggregate reads a table in `_timescaledb_internal`, so it is left out, with every
/// view built on it.
async fn read_hypertables(
client: &tokio_postgres::Client,
dbname: &str,
schema_only: bool,
plan: &mut ExtensionPlan,
) -> Result<()> {
let mut with_rows = vec![];
for h in list_hypertables(client, dbname).await? {
plan.chunk_prefixes.push(format!(
"{}.{}",
quote_ident(&h.chunk_schema),
quote_ident(&format!("{}_", h.chunk_prefix))
));
let relation = format!("{}.{}", quote_ident(&h.schema), quote_ident(&h.name));
if h.users {
if !schema_only
&& !plan
.schema_only_tables
.contains(&(h.schema.clone(), h.name.clone()))
{
with_rows.push(relation.clone());
}
plan.plain_hypertables.push(relation);
}
plan.hypertables.insert(h.id);
}
if !with_rows.is_empty() {
return Err(Error::BadRequest(format!(
"Database '{dbname}' has TimescaleDB hypertables ({}), whose rows a copy cannot carry: \
add them to the data table's tables forked without rows, and the copy has them as \
plain empty tables",
with_rows.join(", ")
)));
}
let triggers = client
.query(
"SELECT 'pg_trigger'::regclass::oid, t.oid
FROM pg_trigger t
JOIN pg_depend d ON d.classid = 'pg_proc'::regclass AND d.objid = t.tgfoid
AND d.refclassid = 'pg_extension'::regclass AND d.deptype = 'e'
JOIN pg_extension e ON e.oid = d.refobjid AND e.extname = $1
WHERE NOT t.tgisinternal",
&[&TIMESCALEDB],
)
.await
.map_err(source_err(dbname))?;
plan.skipped_entries
.extend(triggers.iter().map(|row| (row.get(0), row.get(1))));
let left_out = client
.query(
"WITH RECURSIVE dependent(oid) AS (
SELECT format('%I.%I', view_schema, view_name)::regclass::oid
FROM timescaledb_information.continuous_aggregates
UNION
SELECT r.ev_class FROM dependent
JOIN pg_depend d ON d.refclassid = 'pg_class'::regclass AND d.refobjid = dependent.oid
JOIN pg_rewrite r ON d.classid = 'pg_rewrite'::regclass AND r.oid = d.objid
WHERE r.ev_class <> dependent.oid
)
SELECT n.nspname::text, c.relname::text, c.oid
FROM dependent
JOIN pg_class c ON c.oid = dependent.oid
JOIN pg_namespace n ON n.oid = c.relnamespace
ORDER BY 1, 2",
&[],
)
.await
.map_err(source_err(dbname))?;
// An aggregate built on another one has internal views among them, left out with
// `_timescaledb_internal`.
plan.left_out_views = left_out
.iter()
.filter(|row| row.get::<_, &str>(0) != TIMESCALEDB_INTERNAL)
.map(|row| {
format!(
"{}.{}",
quote_ident(row.get::<_, &str>(0)),
quote_ident(row.get::<_, &str>(1))
)
})
.collect();
// Anything else built on them, such as a function returning a view's row type, would be dumped
// and fail to replay without them.
let oids: Vec<u32> = left_out.iter().map(|row| row.get(2)).collect();
let dependents: Vec<String> = client
.query(
"SELECT DISTINCT pg_describe_object(d.classid, d.objid, d.objsubid)
FROM pg_depend d
WHERE d.deptype = 'n'
AND (d.refclassid = 'pg_class'::regclass AND d.refobjid = ANY($1)
OR d.refclassid = 'pg_type'::regclass AND d.refobjid IN (
SELECT reltype FROM pg_class WHERE oid = ANY($1)))
AND NOT (d.classid = 'pg_rewrite'::regclass AND EXISTS (
SELECT 1 FROM pg_rewrite r WHERE r.oid = d.objid AND r.ev_class = ANY($1)))
ORDER BY 1",
&[&oids],
)
.await
.map_err(source_err(dbname))?
.iter()
.map(|row| row.get(0))
.collect();
if !dependents.is_empty() {
return Err(Error::BadRequest(format!(
"Database '{dbname}' has objects built on TimescaleDB continuous aggregates, which a \
copy leaves out: {}",
dependents.join(", ")
)));
}
Ok(())
}
impl ExtensionPlan {
fn uses_timescaledb(&self) -> bool {
self.extensions.iter().any(|e| e.name == TIMESCALEDB)
}
/// What the copy goes without, for the user who asked for it.
pub(crate) fn warnings(&self) -> Vec<String> {
let mut warnings = vec![];
if !self.left_out_views.is_empty() {
warnings.push(format!(
"Not copied: TimescaleDB continuous aggregates and the views built on them ({})",
self.left_out_views.join(", ")
));
}
if !self.plain_hypertables.is_empty() {
warnings.push(format!(
"Copied as plain empty tables, without TimescaleDB's partitioning: {}",
self.plain_hypertables.join(", ")
));
}
if !self.unmatched_patterns.is_empty() {
warnings.push(format!(
"Tables forked without rows: patterns matching no table: {}",
self.unmatched_patterns.join(", ")
));
}
warnings
}
fn filter_lines(&self) -> Vec<String> {
let mut lines: Vec<String> = self
.extensions
.iter()
.map(|e| format!("exclude extension {}", quote_ident(&e.name)))
.collect();
if self.uses_timescaledb() {
lines.push(format!(
"exclude schema {}",
quote_ident(TIMESCALEDB_INTERNAL)
));
}
// TimescaleDB names a chunk `<prefix>_<n>_chunk`, and a custom prefix in a custom schema
// can begin a user's table name too. A quoted `*` is literal: the wildcard is unquoted.
lines.extend(
self.chunk_prefixes
.iter()
.map(|prefix| format!("exclude table {prefix}*\"_chunk\""))
.chain(
self.left_out_views
.iter()
.map(|view| format!("exclude table {view}")),
),
);
// With its partitions' rows: a partition is matched by its own name, not its parent's.
lines.extend(self.schema_only_tables.iter().map(|(schema, name)| {
format!(
"exclude table_data_and_children {}.{}",
quote_ident(schema),
quote_ident(name)
)
}));
lines
}
/// The extensions a database made to be this copy is created with, on a cluster Windmill
/// manages, by its administrator.
pub(crate) fn database_extensions(&self) -> Vec<DatabaseExtension> {
self.extensions.clone()
}
/// Dump `source`, the database this plan was read from, as the script [`Self::restore`]
/// replays. Extensions are left out, their dependents with them, which leaving their archive
/// entries out of the replay would not do. `no_acl` as in [`PgDumpOptions`]; ownership never
/// carries over, as the restore runs as the target's connection user.
pub(crate) async fn dump(
&self,
db: &DB,
source: &PgDatabase,
schema_only: bool,
no_acl: bool,
) -> Result<DumpFile> {
let filter = write_lines(&self.filter_lines())?;
let archive = pg_dump_database(
source,
PgDumpOptions {
schema_only,
archive: true,
filter: filter.as_ref().map(|f| f.path.as_path()),
..Default::default()
},
)
.await?;
if self.uses_timescaledb() || !self.patterns.is_empty() {
let (client, connection) = source.connect(Some(db)).await?;
let join_handle = tokio::spawn(async move { connection.await });
let changed = self.changed_since_read(&client, &source.dbname).await;
drop(client);
windmill_common::shutdown_pg_connection(join_handle).await?;
if let Some(changed) = changed? {
return Err(Error::BadRequest(format!(
"Database '{}' changed while it was copied ({changed}): retry",
source.dbname
)));
}
}
let list = self.restore_list(&archive).await?;
pg_restore_script(
&archive,
list.as_ref().map(|l| l.path.as_path()),
true,
no_acl,
)
.await
}
/// What the dump may have copied that the plan did not provide for, read after it. A table
/// matching a pattern, or a hypertable, made (or made again) since the plan was read would be
/// dumped with its rows, and a hypertable with TimescaleDB's triggers, which refuse writes to
/// the copy's plain table. One made after the dump's snapshot is not in the dump at all.
async fn changed_since_read(
&self,
client: &tokio_postgres::Client,
dbname: &str,
) -> Result<Option<String>> {
let mut added: Vec<String> = vec![];
if !self.patterns.is_empty() {
added.extend(
match_patterns(client, dbname, &self.patterns)
.await?
.into_iter()
.filter_map(|(_, table)| table)
.filter(|(schema, name, _)| {
!self
.schema_only_tables
.contains(&(schema.clone(), name.clone()))
})
.map(|(schema, name, _)| format!("new table {schema}.{name}")),
);
}
if self.uses_timescaledb() {
added.extend(
list_hypertables(client, dbname)
.await?
.into_iter()
.filter(|h| !self.hypertables.contains(&h.id))
.map(|h| format!("new hypertable {}.{}", h.schema, h.name)),
);
}
Ok((!added.is_empty()).then(|| added.join(", ")))
}
/// The `--use-list` file replaying every entry of `archive` but the skipped ones, when any is.
async fn restore_list(&self, archive: &DumpFile) -> Result<Option<DumpFile>> {
if self.skipped_entries.is_empty() && self.extension_schemas.is_empty() {
return Ok(None);
}
let listing = pg_restore_list(archive).await?;
let kept = skip_entries(&listing, &self.skipped_entries, &self.extension_schemas);
write_lines(&[kept])
}
/// Replay `dump` into `target`: its extensions first, which its role creates when it lacks
/// one, then the dump.
///
/// Authorization: none. Callers MUST have authorized writing to `target`.
pub(crate) async fn restore(
&self,
db: &DB,
dump: &DumpFile,
target: &PgDatabase,
) -> Result<()> {
self.prepare_target(db, target).await?;
pg_import_dump(target, dump).await
}
/// Give `target`, as its own role, the schemas extensions live in and the extensions it lacks.
/// A database made from a template, or by a cluster administrator, may have them already.
async fn prepare_target(&self, db: &DB, target: &PgDatabase) -> Result<()> {
if self.extensions.is_empty() {
return Ok(());
}
let (client, connection) = target.connect(Some(db)).await?;
let join_handle = tokio::spawn(async move { connection.await });
let prepared = self.prepare_on(&client, target).await;
drop(client);
windmill_common::shutdown_pg_connection(join_handle).await?;
prepared
}
async fn prepare_on(&self, client: &tokio_postgres::Client, target: &PgDatabase) -> Result<()> {
let target_err = |e: tokio_postgres::Error| {
Error::internal_err(format!(
"Failed to prepare database '{}' for a copy: {}",
target.dbname,
pg_error_message(&e)
))
};
for schema in &self.extension_schemas {
client
.batch_execute(&format!(
"CREATE SCHEMA IF NOT EXISTS {}",
quote_ident(schema)
))
.await
.map_err(target_err)?;
}
// The replay leaves these to the copy, as a cluster administrator may have set them. The
// server quotes the comment, so no `standard_conforming_strings` lets it end the literal.
for extension in &self.extensions {
let Some(comment) = &extension.schema_comment else {
continue;
};
let statement: Option<String> = client
.query_opt(
"SELECT format('COMMENT ON SCHEMA %I IS %L', $1::text, $2::text)
FROM pg_namespace
WHERE nspname = $1::text
AND obj_description(oid, 'pg_namespace') IS DISTINCT FROM $2::text",
&[&extension.schema, comment],
)
.await
.map_err(target_err)?
.map(|row| row.get(0));
let Some(statement) = statement else {
continue;
};
// A schema the database already had can be another role's: the copy goes without the
// comment rather than not at all.
if let Err(e) = client.batch_execute(&statement).await {
tracing::warn!(
"Not copying the comment on schema '{}' to '{}': {}",
extension.schema,
target.dbname,
pg_error_message(&e)
);
}
}
// Creating an extension the database has would still need the rights to.
let present: BTreeSet<String> = client
.query("SELECT extname::text FROM pg_extension", &[])
.await
.map_err(target_err)?
.iter()
.map(|row| row.get(0))
.collect();
for extension in self
.extensions
.iter()
.filter(|e| !present.contains(&e.name))
{
client
.batch_execute(&format!(
"CREATE EXTENSION IF NOT EXISTS {} WITH SCHEMA {} CASCADE",
quote_ident(&extension.name),
quote_ident(&extension.schema)
))
.await
.map_err(|e| {
Error::BadRequest(format!(
"The copy needs extension '{}', which its database does not have and \
role '{}' may not create: {}. Install the extension in the server's \
template1 database, which new databases are made from, or let the role \
create it.",
extension.name,
target.login_name(),
pg_error_message(&e).trim_end_matches('.')
))
})?;
}
Ok(())
}
}
/// `lines` in a file of their own, or none when there are no lines.
fn write_lines(lines: &[String]) -> Result<Option<DumpFile>> {
if lines.is_empty() {
return Ok(None);
}
let file = DumpFile::new()?;
std::fs::File::create(&file.path)
.and_then(|mut f| f.write_all(lines.join("\n").as_bytes()))
.map_err(|e| Error::internal_err(format!("Failed to write a dump's file: {e}")))?;
Ok(Some(file))
}
/// `listing`, as `pg_restore --list` prints it, with the entries for `skipped` objects and the
/// comments on `uncommented_schemas` commented out. An entry reads `<id>; <catalog oid>
/// <object oid> <type> <schema> <name> <owner>`. A comment's entry carries no oids, and names the
/// schema it is on as pg_dump writes it, quoted only when it has to be.
fn skip_entries(
listing: &str,
skipped: &BTreeSet<(u32, u32)>,
uncommented_schemas: &[String],
) -> String {
let skip = |line: &str| -> bool {
let Some((_, entry)) = line.split_once("; ") else {
return false;
};
let mut oids = entry.split_whitespace();
let object = (
oids.next().and_then(|o| o.parse().ok()),
oids.next().and_then(|o| o.parse().ok()),
);
if let (Some(catalog), Some(oid)) = object {
if skipped.contains(&(catalog, oid)) {
return true;
}
}
let Some(commented) = entry.strip_prefix("0 0 COMMENT - SCHEMA ") else {
return false;
};
uncommented_schemas.iter().any(|schema| {
[schema.clone(), quote_ident(schema)]
.iter()
.any(|name| commented == name || commented.starts_with(&format!("{name} ")))
})
};
listing
.lines()
.map(|line| {
if skip(line) {
format!(";{line}")
} else {
line.to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
}
#[cfg(test)]
mod tests {
use super::skip_entries;
#[test]
fn skip_entries_comments_out_only_the_skipped_objects() {
let listing = ";\n; Archive created at 2026-11-28\n\
278; 1259 17838 TABLE public m postgres\n\
3711; 2620 17842 TRIGGER public m retired postgres\n\
3712; 2620 17843 TRIGGER public m audit postgres\n\
6459; 0 0 COMMENT - SCHEMA \"My Ext\" postgres\n\
6461; 0 0 COMMENT - SCHEMA extensions postgres\n\
6462; 0 0 COMMENT - SCHEMA extensions_old postgres\n\
6463; 0 0 COMMENT - EXTENSION extensions ";
let kept = skip_entries(
listing,
&[(2620, 17842)].into_iter().collect(),
&["My Ext".to_string(), "extensions".to_string()],
);
assert_eq!(
kept.lines().collect::<Vec<_>>(),
[
";",
"; Archive created at 2026-11-28",
"278; 1259 17838 TABLE public m postgres",
";3711; 2620 17842 TRIGGER public m retired postgres",
"3712; 2620 17843 TRIGGER public m audit postgres",
";6459; 0 0 COMMENT - SCHEMA \"My Ext\" postgres",
";6461; 0 0 COMMENT - SCHEMA extensions postgres",
"6462; 0 0 COMMENT - SCHEMA extensions_old postgres",
"6463; 0 0 COMMENT - EXTENSION extensions ",
]
);
}
}