feat: copy TimescaleDB hypertables in data table copies

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-29 12:10:59 +01:00
co-authored by Claude Opus 5.5
parent 5c7d7dee0c
commit ebe8a55783
5 changed files with 634 additions and 60 deletions
+1 -1
View File
@@ -1 +1 @@
88fac323b86968314ffe60900dcff26fff7cb33a
66507e64c45b7b4b09f26fbdb99543cf2dc88654
+2 -2
View File
@@ -20,7 +20,7 @@ private = [
]
cloud = ["windmill-common/cloud"]
no_auth = ["windmill-api-auth/no_auth"]
parquet = ["windmill-object-store/parquet", "dep:futures"]
parquet = ["windmill-object-store/parquet"]
[dependencies]
windmill-common = { workspace = true, default-features = false }
@@ -38,7 +38,7 @@ windmill-store.workspace = true
axum.workspace = true
chrono.workspace = true
constant_time_eq.workspace = true
futures = { workspace = true, optional = true }
futures.workspace = true
hex.workspace = true
magic-crypt.workspace = true
http.workspace = true
@@ -28,13 +28,13 @@ use windmill_common::workspaces::{
use windmill_common::{PgDatabase, DB};
use crate::datatable_acl::connect_with_notices;
use crate::datatable_extensions::{read_extension_plan, ExtensionPlan};
use crate::datatable_extensions::{read_extension_plan, ExtensionPlan, PlannedDump};
use crate::datatable_migrations::{
lock_migration_runs_on, read_applied_migrations, write_applied_migrations, AppliedMigrations,
};
use crate::datatable_permissions::ensure_reaches_governing_datatable;
use crate::workspaces::{
copy_database_settings, create_database_on_server, ensure_datatable_is_clonable, DumpFile,
copy_database_settings, create_database_on_server, ensure_datatable_is_clonable,
};
/// A database this request created and filled for the data tables of the fork on one source
@@ -468,7 +468,7 @@ async fn make_copy(
// Ownership never carries over: the restore runs as the target's connection user. Grants do,
// except on a cluster Windmill manages, which plants its own and where the replay below is what
// reproduces the roles'.
let extensions = read_extension_plan(db, &server, schema_only).await?;
let mut extensions = read_extension_plan(db, &server, schema_only).await?;
let dump = extensions.dump(&server, schema_only, managed).await?;
let applied = match migrations_lock {
Some(client) => Some(read_applied_migrations(&client).await?),
@@ -516,7 +516,7 @@ async fn make_copy(
&governing,
&server,
&target,
&dump,
dump,
&extensions,
applied.as_ref(),
)
@@ -558,7 +558,7 @@ async fn fill(
governing: &GoverningDatatable,
source: &PgDatabase,
target: &PgDatabase,
dump: &DumpFile,
dump: PlannedDump,
extensions: &ExtensionPlan,
applied: Option<&AppliedMigrations>,
) -> Result<bool> {
@@ -16,10 +16,18 @@
//!
//! 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`]).
//!
//! TimescaleDB keeps a hypertable's rows in chunk tables and bookkeeping of its own, which a replay
//! can neither write nor reproduce. The chunks are left out of the dump and each hypertable is made
//! one again in the copy. Its rows are streamed from the source between the dump's pre-data and
//! data sections, where pg_dump would load them: before the triggers that would fire on them and
//! the materialized views refreshed from them, and in the dump's own snapshot.
use std::collections::BTreeSet;
use std::io::Write;
use futures::{SinkExt, StreamExt};
use tokio_postgres::types::ToSql;
use windmill_common::error::{pg_error_message, Error, Result};
use windmill_common::{DatabaseExtension, PgDatabase, DB};
@@ -28,6 +36,8 @@ use crate::workspaces::{
};
const TIMESCALEDB: &str = "timescaledb";
/// Where TimescaleDB keeps the relations it makes for itself, compressed chunks among them.
const TIMESCALEDB_INTERNAL: &str = "_timescaledb_internal";
/// What a copy of one database needs done about the extensions it uses.
#[derive(Default)]
@@ -40,6 +50,34 @@ pub(crate) struct ExtensionPlan {
extension_schemas: Vec<String>,
/// The source objects whose archive entries are not replayed, as `(catalog oid, object oid)`.
skipped_entries: BTreeSet<(u32, u32)>,
hypertables: Vec<Hypertable>,
/// Every chunk of every hypertable, `"schema"."table"` as pg_dump patterns read them.
chunks: Vec<String>,
/// With TimescaleDB, the session the hypertables and chunks were read in, and the snapshot it
/// exported for the dump.
snapshot: Option<(SnapshotSession, String)>,
}
struct Hypertable {
schema: String,
name: String,
/// In dimension order: the first is the one `create_hypertable` takes.
dimensions: Vec<Dimension>,
/// The columns a `COPY` carries: every one but the generated, which the copy computes itself.
columns: Vec<String>,
}
struct Dimension {
column: String,
time_interval: Option<String>,
integer_interval: Option<i64>,
num_partitions: Option<i16>,
}
impl Hypertable {
fn relation(&self) -> String {
format!("{}.{}", quote_ident(&self.schema), quote_ident(&self.name))
}
}
fn quote_ident(name: &str) -> String {
@@ -55,8 +93,8 @@ fn source_err(dbname: &str) -> impl FnOnce(tokio_postgres::Error) -> Error + '_
}
}
/// Read what copying `source` takes: its extensions. Refuses, before anything is created, what a
/// copy cannot carry.
/// Read what copying `source` takes: its extensions and, with TimescaleDB, its hypertables.
/// Refuses, before anything is created, what a copy cannot carry.
pub(crate) async fn read_extension_plan(
db: &DB,
source: &PgDatabase,
@@ -64,10 +102,65 @@ pub(crate) async fn read_extension_plan(
) -> 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).await;
let read = async {
let plan = read_plan(&client, &source.dbname, schema_only).await?;
let hypertables: Vec<String> = if plan.uses_timescaledb() {
client
.query(
"SELECT format('%I.%I', hypertable_schema, hypertable_name)
FROM timescaledb_information.hypertables ORDER BY 1",
&[],
)
.await
.map_err(source_err(&source.dbname))?
.iter()
.map(|row| row.get(0))
.collect()
} else {
vec![]
};
Ok::<_, Error>((plan, hypertables))
}
.await;
drop(client);
windmill_common::shutdown_pg_connection(join_handle).await?;
plan
let (mut plan, hypertables) = read?;
// The chunks to leave out are read in the snapshot the dump is then taken in: a chunk made in
// between would otherwise be dumped as a table of its own, inheriting from its hypertable.
if plan.uses_timescaledb() {
let (snapshot, snapshot_id) = SnapshotSession::open(db, source, &hypertables).await?;
let read = async {
read_hypertables(&snapshot.client, &source.dbname, &mut plan).await?;
// A chunk made between the lock `open` takes and its snapshot is in the snapshot but
// not locked. Locking every chunk the snapshot sees fails on one dropped since, rather
// than copying a hypertable without its rows.
if !plan.chunks.is_empty() {
snapshot
.client
.batch_execute(&format!(
"LOCK TABLE {} IN ACCESS SHARE MODE",
plan.chunks.join(", ")
))
.await
.map_err(|e| {
Error::BadRequest(format!(
"A chunk of database '{}' was dropped while it was being copied, \
try again: {}",
source.dbname,
pg_error_message(&e)
))
})?;
}
Ok::<_, Error>(())
}
.await;
if let Err(e) = read {
snapshot.close().await;
return Err(e);
}
plan.snapshot = Some((snapshot, snapshot_id));
}
Ok(plan)
}
async fn read_plan(
@@ -108,9 +201,6 @@ async fn read_plan(
}
plan.extension_schemas = extension_schemas.into_iter().collect();
if plan.extensions.iter().any(|e| e.name == TIMESCALEDB) {
refuse_hypertables(client, dbname).await?;
}
if !schema_only {
refuse_extension_rows(client, dbname).await?;
}
@@ -119,9 +209,8 @@ async fn read_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 refused on
/// their own.
/// leaves those rows out too, and the copy's role could not write them anyway. TimescaleDB's are
/// its catalog, which the copy rebuilds.
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
@@ -162,13 +251,17 @@ async fn refuse_extension_rows(client: &tokio_postgres::Client, dbname: &str) ->
Ok(())
}
/// Refuse a database with TimescaleDB hypertables: their rows live in chunk tables and catalog
/// rows of TimescaleDB's, which a replay as the copy's role can neither write nor reproduce.
async fn refuse_hypertables(client: &tokio_postgres::Client, dbname: &str) -> Result<()> {
let hypertables: Vec<String> = client
async fn read_hypertables(
client: &tokio_postgres::Client,
dbname: &str,
plan: &mut ExtensionPlan,
) -> Result<()> {
// A continuous aggregate's view reads a materialization hypertable among the relations the
// dump leaves out, so its definition would fail to replay.
let aggregates: Vec<String> = client
.query(
"SELECT format('%I.%I', hypertable_schema, hypertable_name)
FROM timescaledb_information.hypertables ORDER BY 1",
"SELECT format('%I.%I', view_schema, view_name)
FROM timescaledb_information.continuous_aggregates ORDER BY 1",
&[],
)
.await
@@ -176,57 +269,281 @@ async fn refuse_hypertables(client: &tokio_postgres::Client, dbname: &str) -> Re
.iter()
.map(|row| row.get(0))
.collect();
if !hypertables.is_empty() {
if !aggregates.is_empty() {
return Err(Error::BadRequest(format!(
"Database '{dbname}' has TimescaleDB hypertables ({}), which a copy cannot carry yet",
hypertables.join(", ")
"Database '{dbname}' has TimescaleDB continuous aggregates ({}), which a copy cannot \
carry yet",
aggregates.join(", ")
)));
}
// A chunk inherits from its hypertable, internal compressed ones included, in every
// TimescaleDB version, while its catalog's columns differ between them.
plan.chunks = client
.query(
"SELECT n.nspname::text, c.relname::text
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE i.inhparent IN (
SELECT format('%I.%I', schema_name, table_name)::regclass
FROM _timescaledb_catalog.hypertable)
ORDER BY 1, 2",
&[],
)
.await
.map_err(source_err(dbname))?
.iter()
.map(|row| {
format!(
"{}.{}",
quote_ident(row.get::<_, &str>(0)),
quote_ident(row.get::<_, &str>(1))
)
})
.collect();
let rows = client
.query(
"SELECT d.hypertable_schema::text, d.hypertable_name::text, d.column_name::text,
d.time_interval::text, d.integer_interval::bigint, d.num_partitions::smallint
FROM timescaledb_information.dimensions d
ORDER BY d.hypertable_schema, d.hypertable_name, d.dimension_number",
&[],
)
.await
.map_err(source_err(dbname))?;
for row in rows {
let (schema, name): (String, String) = (row.get(0), row.get(1));
let dimension = Dimension {
column: row.get(2),
time_interval: row.get(3),
integer_interval: row.get(4),
num_partitions: row.get(5),
};
match plan.hypertables.last_mut() {
Some(last) if last.schema == schema && last.name == name => {
last.dimensions.push(dimension)
}
_ => plan.hypertables.push(Hypertable {
schema,
name,
dimensions: vec![dimension],
columns: vec![],
}),
}
}
for hypertable in &mut plan.hypertables {
hypertable.columns = client
.query(
"SELECT attname::text FROM pg_attribute
WHERE attrelid = $1::text::regclass AND attnum > 0 AND NOT attisdropped
AND attgenerated = ''
ORDER BY attnum",
&[&hypertable.relation()],
)
.await
.map_err(source_err(dbname))?
.iter()
.map(|row| row.get(0))
.collect();
}
// `ts_insert_blocker`, the trigger older TimescaleDB versions put on a hypertable, is made by
// `create_hypertable` again: the dump's would already exist.
let blockers = client
.query(
"SELECT 'pg_trigger'::regclass::oid, t.oid FROM pg_trigger t
WHERE t.tgname = 'ts_insert_blocker' AND NOT t.tgisinternal
AND t.tgrelid IN (
SELECT format('%I.%I', hypertable_schema, hypertable_name)::regclass
FROM timescaledb_information.hypertables)",
&[],
)
.await
.map_err(source_err(dbname))?;
plan.skipped_entries
.extend(blockers.iter().map(|row| (row.get(0), row.get(1))));
Ok(())
}
/// A dump of a source, made by [`ExtensionPlan::dump`] and replayed by
/// [`ExtensionPlan::restore`].
pub(crate) enum PlannedDump {
Whole(DumpFile),
/// A copy with data of hypertables, whose rows load between `pre_data` and `data` through
/// `snapshot`, the session whose snapshot the dump was taken in.
Sections {
pre_data: DumpFile,
data: DumpFile,
post_data: DumpFile,
snapshot: SnapshotSession,
},
}
/// A session holding open the transaction whose snapshot a dump was taken in.
pub(crate) struct SnapshotSession {
client: tokio_postgres::Client,
join_handle: tokio::task::JoinHandle<std::result::Result<(), tokio_postgres::Error>>,
}
impl SnapshotSession {
/// `hypertables` are quoted qualified names, locked with their chunks before the snapshot is
/// taken and until the session closes: a chunk dropped meanwhile, by a retention policy say,
/// takes its rows with it even from a snapshot that still sees them.
async fn open(db: &DB, source: &PgDatabase, hypertables: &[String]) -> Result<(Self, String)> {
let (client, connection) = source.connect(Some(db)).await?;
let join_handle = tokio::spawn(async move { connection.await });
let session = Self { client, join_handle };
let snapshot = async {
// The plan's intervals are read as text and handed back to TimescaleDB on the copy.
session
.client
.batch_execute(
"BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SET LOCAL IntervalStyle = 'postgres'",
)
.await?;
if !hypertables.is_empty() {
// Before any query, which would take the snapshot.
session
.client
.batch_execute(&format!(
"LOCK TABLE {} IN ACCESS SHARE MODE",
hypertables.join(", ")
))
.await?;
}
Ok::<String, tokio_postgres::Error>(
session
.client
.query_one("SELECT pg_export_snapshot()", &[])
.await?
.get(0),
)
}
.await;
match snapshot {
Ok(snapshot) => Ok((session, snapshot)),
Err(e) => {
session.close().await;
Err(Error::internal_err(format!(
"Failed to take a snapshot of database '{}': {}",
source.dbname,
pg_error_message(&e)
)))
}
}
}
async fn close(self) {
drop(self.client);
if let Err(e) = windmill_common::shutdown_pg_connection(self.join_handle).await {
tracing::warn!("Closing a snapshot session: {e}");
}
}
}
impl ExtensionPlan {
fn uses_timescaledb(&self) -> bool {
self.extensions.iter().any(|e| e.name == TIMESCALEDB)
}
/// 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.
/// The `--filter` lines leaving out what the copy gets otherwise: every extension, and every
/// relation TimescaleDB makes for itself. Dependents go with them, which leaving their archive
/// entries out of the replay would not do.
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)
));
}
lines.extend(
self.chunks
.iter()
.map(|chunk| format!("exclude table {chunk}")),
);
lines
}
/// Dump `source`, the database this plan was read from, in the snapshot it was read in when it
/// has one. `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,
&mut self,
source: &PgDatabase,
schema_only: bool,
no_acl: bool,
) -> Result<DumpFile> {
let filter = write_lines(
&self
.extensions
.iter()
.map(|e| format!("exclude extension {}", quote_ident(&e.name)))
.collect::<Vec<_>>(),
)?;
) -> Result<PlannedDump> {
let filter = write_lines(&self.filter_lines())?;
let (snapshot, snapshot_id) = match self.snapshot.take() {
Some((session, id)) => (Some(session), Some(id)),
None => (None, None),
};
let archive = pg_dump_database(
source,
PgDumpOptions {
schema_only,
archive: true,
filter: filter.as_ref().map(|f| f.path.as_path()),
snapshot: snapshot_id.as_deref(),
..Default::default()
},
)
.await?;
let list = self.restore_list(&archive).await?;
pg_restore_script(
&archive,
list.as_ref().map(|l| l.path.as_path()),
true,
no_acl,
)
.await
.await;
let sectioned = !schema_only && !self.hypertables.is_empty();
let snapshot = match (snapshot, sectioned) {
(Some(snapshot), true) => snapshot,
(snapshot, _) => {
if let Some(snapshot) = snapshot {
snapshot.close().await;
}
if sectioned {
return Err(Error::internal_err(
"the hypertables of a copy were read outside a snapshot",
));
}
let archive = archive?;
let list = self.restore_list(&archive).await?;
let list = list.as_ref().map(|l| l.path.as_path());
return Ok(PlannedDump::Whole(
pg_restore_script(&archive, None, list, true, no_acl).await?,
));
}
};
let sections = async {
let archive = archive?;
let list = self.restore_list(&archive).await?;
let list = list.as_ref().map(|l| l.path.as_path());
Ok::<_, Error>((
pg_restore_script(&archive, Some("pre-data"), list, true, no_acl).await?,
pg_restore_script(&archive, Some("data"), list, true, no_acl).await?,
pg_restore_script(&archive, Some("post-data"), list, true, no_acl).await?,
))
}
.await;
match sections {
Ok((pre_data, data, post_data)) => {
Ok(PlannedDump::Sections { pre_data, data, post_data, snapshot })
}
Err(e) => {
snapshot.close().await;
Err(e)
}
}
}
/// The `--use-list` file replaying every entry of `archive` but the skipped ones, when any is.
@@ -240,17 +557,70 @@ impl ExtensionPlan {
}
/// Replay `dump` into `target`: its extensions first, which its role creates when it lacks
/// one, then the dump.
/// one, then the dump, with each hypertable made one again and, in a copy with data, its rows
/// loaded where pg_dump would load them. A copy with data of hypertables replays in several
/// transactions, so one that fails part way leaves `target` partly filled.
///
/// Authorization: none. Callers MUST have authorized writing to `target`.
pub(crate) async fn restore(
&self,
db: &DB,
dump: &DumpFile,
dump: PlannedDump,
target: &PgDatabase,
) -> Result<()> {
self.prepare_target(db, target).await?;
pg_import_dump(target, dump).await
match dump {
PlannedDump::Whole(script) => {
self.prepare_target(db, target).await?;
pg_import_dump(target, &script).await?;
self.make_hypertables(db, target, None).await
}
PlannedDump::Sections { pre_data, data, post_data, snapshot } => {
let restored = async {
self.prepare_target(db, target).await?;
pg_import_dump(target, &pre_data).await?;
self.make_hypertables(db, target, Some(&snapshot.client))
.await?;
pg_import_dump(target, &data).await?;
self.drop_only_on_hypertables(&post_data).await?;
pg_import_dump(target, &post_data).await
}
.await;
snapshot.close().await;
restored
}
}
}
/// TimescaleDB refuses `ALTER TABLE ONLY` on a hypertable, which the post-data section,
/// replayed once they are hypertables, adds constraints with. Without `ONLY` the constraint
/// goes on the hypertable, and TimescaleDB gives each chunk its own.
async fn drop_only_on_hypertables(&self, post_data: &DumpFile) -> Result<()> {
let io_err =
|e: std::io::Error| Error::internal_err(format!("Failed to patch dump file: {e}"));
let text = tokio::fs::read_to_string(&post_data.path)
.await
.map_err(io_err)?;
let hypertables: BTreeSet<(&str, &str)> = self
.hypertables
.iter()
.map(|h| (h.schema.as_str(), h.name.as_str()))
.collect();
let mut patched = String::with_capacity(text.len());
for line in text.split_inclusive('\n') {
let only_on_hypertable = line
.trim_end()
.strip_prefix("ALTER TABLE ONLY ")
.and_then(parse_qualified)
.is_some_and(|(schema, name)| hypertables.contains(&(&schema, &name)));
if only_on_hypertable {
patched.push_str(&line.replacen("ALTER TABLE ONLY ", "ALTER TABLE ", 1));
} else {
patched.push_str(line);
}
}
tokio::fs::write(&post_data.path, patched)
.await
.map_err(io_err)
}
/// Give `target`, as its own role, the schemas extensions live in and the extensions it lacks.
@@ -349,6 +719,158 @@ impl ExtensionPlan {
}
Ok(())
}
/// Make each hypertable of the source one again in `target`, streaming its rows from `rows`
/// when given. A hypertable `target` already has is left as it is.
async fn make_hypertables(
&self,
db: &DB,
target: &PgDatabase,
rows: Option<&tokio_postgres::Client>,
) -> Result<()> {
if self.hypertables.is_empty() {
return Ok(());
}
let (mut client, connection) = target.connect(Some(db)).await?;
let join_handle = tokio::spawn(async move { connection.await });
let result = self.make_hypertables_on(&mut client, rows).await;
drop(client);
windmill_common::shutdown_pg_connection(join_handle).await?;
result.map_err(|e| {
Error::internal_err(format!(
"Failed to restore the hypertables of the copy '{}': {e}",
target.dbname
))
})
}
async fn make_hypertables_on(
&self,
target: &mut tokio_postgres::Client,
rows: Option<&tokio_postgres::Client>,
) -> std::result::Result<(), String> {
let pg = |e: tokio_postgres::Error| pg_error_message(&e);
// Qualified: copying rows narrows the search path for the rest of the transaction.
let timescaledb = self
.extensions
.iter()
.find(|e| e.name == TIMESCALEDB)
.map(|e| quote_ident(&e.schema))
.ok_or("hypertables without TimescaleDB")?;
let tx = target.transaction().await.map_err(pg)?;
for hypertable in &self.hypertables {
let relation = hypertable.relation();
let exists: bool = tx
.query_one(
"SELECT EXISTS (SELECT 1 FROM timescaledb_information.hypertables
WHERE hypertable_schema = $1 AND hypertable_name = $2)",
&[&hypertable.schema, &hypertable.name],
)
.await
.map_err(pg)?
.get(0);
if exists {
continue;
}
for (i, dimension) in hypertable.dimensions.iter().enumerate() {
// The replay makes the source's indexes, the default ones among them.
let (function, extra) = if i == 0 {
("create_hypertable", ", create_default_indexes => false")
} else {
("add_dimension", "")
};
let partitions = dimension.num_partitions.map(i32::from);
let (argument, value): (&str, Option<&(dyn ToSql + Sync)>) = match (
&dimension.time_interval,
&dimension.integer_interval,
&partitions,
) {
(Some(interval), _, _) => (
", chunk_time_interval => $3::text::interval",
Some(interval),
),
(None, Some(interval), _) => {
(", chunk_time_interval => $3::bigint", Some(interval))
}
(None, None, Some(partitions)) => {
(", number_partitions => $3::int", Some(partitions))
}
(None, None, None) => ("", None),
};
let mut params: Vec<&(dyn ToSql + Sync)> = vec![&relation, &dimension.column];
params.extend(value);
tx.execute(
&format!(
"SELECT {timescaledb}.{function}($1::text::regclass, \
$2::text::name{argument}{extra})"
),
&params,
)
.await
.map_err(|e| format!("{relation}: {}", pg_error_message(&e)))?;
}
if let Some(source) = rows {
copy_rows(source, &tx, hypertable)
.await
.map_err(|e| format!("copying the rows of {relation}: {e}"))?;
}
}
tx.commit().await.map_err(pg)
}
}
/// What both sides of [`copy_rows`] set, so each value's text reads the same on the target as it
/// was written on the source. Not binary: that carries OIDs, which differ between databases, for
/// `regclass` values and the element types of arrays and composites of user-defined types. With
/// only `pg_catalog` on the search path, `regclass` and its kin are written schema-qualified.
const PORTABLE_TEXT_SETTINGS: &str = "SET LOCAL DateStyle = 'ISO, YMD';
SET LOCAL IntervalStyle = 'postgres';
SET LOCAL TimeZone = 'UTC';
SET LOCAL extra_float_digits = 3;
SET LOCAL bytea_output = 'hex';
SET LOCAL lc_monetary = 'C';
SET LOCAL search_path = pg_catalog";
/// Stream the rows of `hypertable` from `source`, a session inside the dump's snapshot, into
/// `target`. A `COPY` of a hypertable itself reads none of its rows, which live in its chunks: the
/// source side copies a query instead.
async fn copy_rows(
source: &tokio_postgres::Client,
target: &tokio_postgres::Transaction<'_>,
hypertable: &Hypertable,
) -> std::result::Result<(), String> {
let pg = |e: tokio_postgres::Error| pg_error_message(&e);
let relation = hypertable.relation();
let columns = hypertable
.columns
.iter()
.map(|c| quote_ident(c))
.collect::<Vec<_>>()
.join(", ");
source
.batch_execute(PORTABLE_TEXT_SETTINGS)
.await
.map_err(pg)?;
target
.batch_execute(PORTABLE_TEXT_SETTINGS)
.await
.map_err(pg)?;
let rows = source
.copy_out(&format!(
"COPY (SELECT {columns} FROM {relation}) TO STDOUT"
))
.await
.map_err(pg)?;
let sink = target
.copy_in(&format!("COPY {relation} ({columns}) FROM STDIN"))
.await
.map_err(pg)?;
futures::pin_mut!(rows, sink);
while let Some(chunk) = rows.next().await {
sink.send(chunk.map_err(pg)?).await.map_err(pg)?;
}
sink.finish().await.map_err(pg)?;
Ok(())
}
/// `lines` in a file of their own, or none when there are no lines.
@@ -408,15 +930,57 @@ fn skip_entries(
.join("\n")
}
/// A `schema.name` as pg_dump writes it, each part double-quoted only when it has to be, unquoted.
fn parse_qualified(qualified: &str) -> Option<(String, String)> {
let (schema, rest) = parse_ident(qualified)?;
let (name, rest) = parse_ident(rest.strip_prefix('.')?)?;
rest.is_empty().then_some((schema, name))
}
fn parse_ident(s: &str) -> Option<(String, &str)> {
let Some(quoted) = s.strip_prefix('"') else {
let end = s
.find(|c: char| c == '.' || c.is_whitespace())
.unwrap_or(s.len());
return (end > 0).then(|| (s[..end].to_string(), &s[end..]));
};
let mut ident = String::new();
let mut rest = quoted;
loop {
let close = rest.find('"')?;
ident.push_str(&rest[..close]);
rest = &rest[close + 1..];
match rest.strip_prefix('"') {
Some(after) => {
ident.push('"');
rest = after;
}
None => return Some((ident, rest)),
}
}
}
#[cfg(test)]
mod tests {
use super::skip_entries;
use super::{parse_qualified, skip_entries};
#[test]
fn parse_qualified_unquotes_what_pg_dump_quotes() {
let parsed = |s: &str| parse_qualified(s).map(|(a, b)| format!("{a}|{b}"));
assert_eq!(parsed("public.metrics").as_deref(), Some("public|metrics"));
assert_eq!(
parsed("\"My.Schema\".\"a\"\"b\"").as_deref(),
Some("My.Schema|a\"b")
);
assert_eq!(parsed("public.metrics ADD"), None);
assert_eq!(parsed("metrics"), None);
}
#[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\
3711; 2620 17842 TRIGGER public m ts_insert_blocker 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\
@@ -433,7 +997,7 @@ mod tests {
";",
"; Archive created at 2026-11-28",
"278; 1259 17838 TABLE public m postgres",
";3711; 2620 17842 TRIGGER public m retired postgres",
";3711; 2620 17842 TRIGGER public m ts_insert_blocker postgres",
"3712; 2620 17843 TRIGGER public m audit postgres",
";6459; 0 0 COMMENT - SCHEMA \"My Ext\" postgres",
";6461; 0 0 COMMENT - SCHEMA extensions postgres",
@@ -3511,6 +3511,8 @@ pub(crate) struct PgDumpOptions<'a> {
pub(crate) exclude_tables: &'a [&'a str],
/// A `--filter` file of what else to leave out (pg_dump 17+).
pub(crate) filter: Option<&'a std::path::Path>,
/// Dump as of a snapshot another session exported, rather than one of its own.
pub(crate) snapshot: Option<&'a str>,
/// Write an archive for `pg_restore` rather than a `psql` script. `no_owner` and `no_acl` then
/// apply when restoring it ([`pg_restore_script`]).
pub(crate) archive: bool,
@@ -3557,6 +3559,9 @@ fn pg_dump_command(
if let Some(filter) = opts.filter {
cmd.arg("--filter").arg(filter);
}
if let Some(snapshot) = opts.snapshot {
cmd.arg(format!("--snapshot={snapshot}"));
}
if opts.schema_only {
cmd.arg("--schema-only");
}
@@ -3658,10 +3663,12 @@ pub(crate) async fn pg_restore_list(archive: &DumpFile) -> Result<String> {
.map_err(|e| Error::internal_err(format!("pg_restore listed a non-UTF-8 entry: {e}")))
}
/// A [`PgDumpOptions::archive`] dump as a script [`pg_import_dump`] replays, restricted to the
/// entries `list` keeps ([`pg_restore_list`]'s format) when given.
/// A [`PgDumpOptions::archive`] dump as a script [`pg_import_dump`] replays: one `section`
/// (`pre-data`, `data` or `post-data`) or all of it, restricted to the entries `list` keeps
/// ([`pg_restore_list`]'s format) when given.
pub(crate) async fn pg_restore_script(
archive: &DumpFile,
section: Option<&str>,
list: Option<&std::path::Path>,
no_owner: bool,
no_acl: bool,
@@ -3669,6 +3676,9 @@ pub(crate) async fn pg_restore_script(
let script = DumpFile::new()?;
let mut cmd = tokio::process::Command::new("pg_restore");
cmd.arg("--file").arg(&script.path);
if let Some(section) = section {
cmd.arg(format!("--section={section}"));
}
if let Some(list) = list {
cmd.arg("--use-list").arg(list);
}
@@ -4452,7 +4462,7 @@ async fn import_pg_database(
} else {
None
};
let extensions =
let mut extensions =
crate::datatable_extensions::read_extension_plan(&db, &source_pg, schema_only).await?;
let dump = extensions.dump(&source_pg, schema_only, no_acl).await?;
let applied = match migrations_lock {
@@ -4462,7 +4472,7 @@ async fn import_pg_database(
// The target's role creates any extension it lacks. A cluster administrator creates them only
// with a database, before anyone may write to it, and this target was created by an earlier
// request.
extensions.restore(&db, &dump, &target_pg).await?;
extensions.restore(&db, dump, &target_pg).await?;
if let Some(applied) = applied {
crate::datatable_migrations::write_applied_migrations(&db, &target_pg, &applied).await?;
}