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>
This commit is contained in:
Ruben Fiszel
2026-12-02 23:08:59 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot]
parent d303cb855a
commit 76bfdf32a9
14 changed files with 653 additions and 58 deletions
+1 -1
View File
@@ -1 +1 @@
2a59a3b336ae88f9314dfb25e0e7d4552b40b867
2afccf8964aef7d7d318d6a14868a0757dbc0e13
@@ -0,0 +1 @@
ALTER TABLE workspace_fork_creation DROP COLUMN IF EXISTS warnings;
@@ -0,0 +1,3 @@
-- What a fork created in the background goes without, such as objects its data table copies could
-- not carry, for whoever polls for it.
ALTER TABLE workspace_fork_creation ADD COLUMN IF NOT EXISTS warnings TEXT[];
@@ -52,6 +52,11 @@ pub(crate) struct MadeCopy {
pub(crate) replayed: bool,
/// For a resource-backed copy, the resource and variables its connection was resolved from.
pub(crate) connection: Option<ConnectionSnapshot>,
/// What the copy goes without, for the user who forked.
pub(crate) warnings: Vec<String>,
/// The source's `schema_only_tables` the copy was made with, which the fork's entry takes: a
/// save to the source's while it was copied must not leave the two disagreeing.
pub(crate) schema_only_tables: Vec<String>,
}
/// What a resource-backed data table's connection is resolved from: its resource, and every
@@ -280,7 +285,13 @@ pub(crate) async fn authorize_copies(
.iter()
.find(|(_, earlier)| same_source(earlier, &governing))
{
ensure_shares_copy(first.name, first.behavior, request)?;
ensure_shares_copy(
first.name,
first.behavior,
&first_governing.datatable.schema_only_tables,
request,
&governing,
)?;
if first_governing.datatable.permissions.is_some() != under_roles {
return Err(Error::BadRequest(format!(
"Data tables '{}' and '{}' use the same database, which the fork copies once, \
@@ -304,11 +315,17 @@ fn same_source(a: &GoverningDatatable, b: &GoverningDatatable) -> bool {
.is_some_and(|d| d.resource_type.is_windmill_managed()))
}
fn pattern_set(patterns: &[String]) -> BTreeSet<&str> {
patterns.iter().map(String::as_str).collect()
}
/// Data tables on one database get one copy, made as the first of them asks.
fn ensure_shares_copy(
first: &str,
behavior: DataTableForkBehavior,
first_tables: &[String],
request: &CopyRequest<'_>,
governing: &GoverningDatatable,
) -> Result<()> {
if behavior != request.behavior {
return Err(Error::BadRequest(format!(
@@ -317,6 +334,14 @@ fn ensure_shares_copy(
first, request.name
)));
}
// Even for a schema-only copy: the fork's entries all take the list the copy was made with.
if pattern_set(first_tables) != pattern_set(&governing.datatable.schema_only_tables) {
return Err(Error::BadRequest(format!(
"Data tables '{}' and '{}' use the same database, which the fork copies once, but \
name different tables to copy without rows: give them the same list",
first, request.name
)));
}
Ok(())
}
@@ -340,7 +365,14 @@ pub(crate) async fn make_copies(
};
let shared = sources.iter().position(|s| same_source(s, &governing));
if let Some(c) = shared {
if let Err(e) = ensure_shares_copy(&copies[c].names[0], copies[c].behavior, request) {
if let Err(e) = ensure_shares_copy(
&copies[c].names[0],
copies[c].behavior,
// What the copy was made with, which a save since the first read may have changed.
&copies[c].schema_only_tables,
request,
&governing,
) {
return Err(drop_copies_after(db, copies, e).await);
}
copies[c].names.push(request.name.to_string());
@@ -468,7 +500,13 @@ 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 extensions = read_extension_plan(
db,
&server,
schema_only,
&governing.datatable.schema_only_tables,
)
.await?;
let dump = extensions.dump(db, &server, schema_only, managed).await?;
let applied = match migrations_lock {
Some(client) => Some(read_applied_migrations(&client).await?),
@@ -529,6 +567,12 @@ async fn make_copy(
source_database,
replayed,
connection,
warnings: extensions
.warnings()
.into_iter()
.map(|w| format!("Data table '{}': {w}", request.name))
.collect(),
schema_only_tables: governing.datatable.schema_only_tables.clone(),
}),
Err(e) => {
if let Err(drop_err) = drop_copy(db, &source_database, request.dbname).await {
@@ -28,6 +28,7 @@ use crate::workspaces::{
};
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)]
@@ -40,6 +41,20 @@ 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)>,
/// 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 {
@@ -55,16 +70,17 @@ 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 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).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
@@ -74,6 +90,7 @@ 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.
@@ -108,8 +125,11 @@ 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 {
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?;
@@ -120,7 +140,7 @@ 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
/// 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.
@@ -162,30 +182,337 @@ 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
/// 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 format('%I.%I', hypertable_schema, hypertable_name)
FROM timescaledb_information.hypertables ORDER BY 1",
&[],
"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 !hypertables.is_empty() {
if !references.is_empty() {
return Err(Error::BadRequest(format!(
"Database '{dbname}' has TimescaleDB hypertables ({}), which a copy cannot carry yet",
hypertables.join(", ")
"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> {
@@ -203,13 +530,7 @@ impl ExtensionPlan {
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<_>>(),
)?;
let filter = write_lines(&self.filter_lines())?;
let archive = pg_dump_database(
source,
PgDumpOptions {
@@ -220,15 +541,18 @@ impl ExtensionPlan {
},
)
.await?;
// A hypertable made since the plan was read would be dumped as a plain table without its
// chunks. One made after the dump's snapshot is not in the dump at all.
if self.extensions.iter().any(|e| e.name == TIMESCALEDB) {
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 refused = refuse_hypertables(&client, &source.dbname).await;
let changed = self.changed_since_read(&client, &source.dbname).await;
drop(client);
windmill_common::shutdown_pg_connection(join_handle).await?;
refused?;
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(
@@ -240,6 +564,42 @@ impl ExtensionPlan {
.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() {
@@ -4383,9 +4383,12 @@ async fn import_pg_database(
return Ok("No action needed for KeepOriginal behavior".to_string());
}
let mut schema_only_tables = vec![];
if let Some(reference) = req.source.strip_prefix("datatable://") {
let (name, _) = parse_datatable_ref_for(&db, &w_id, reference).await?;
ensure_copied_without_roles(&ensure_datatable_is_clonable(&db, &w_id, &name).await?)?;
let governing = ensure_datatable_is_clonable(&db, &w_id, &name).await?;
ensure_copied_without_roles(&governing)?;
schema_only_tables = governing.datatable.schema_only_tables;
}
if req.fork_behavior == DataTableForkBehavior::SchemaAndData {
@@ -4457,8 +4460,13 @@ async fn import_pg_database(
} else {
None
};
let extensions =
crate::datatable_extensions::read_extension_plan(&db, &source_pg, schema_only).await?;
let extensions = crate::datatable_extensions::read_extension_plan(
&db,
&source_pg,
schema_only,
&schema_only_tables,
)
.await?;
let dump = extensions.dump(&db, &source_pg, schema_only, no_acl).await?;
let applied = match migrations_lock {
Some(client) => Some(crate::datatable_migrations::read_applied_migrations(&client).await?),
@@ -4478,10 +4486,11 @@ async fn import_pg_database(
tx.commit().await?;
}
Ok(format!(
"Imported from '{}' into '{}'",
req.source, target_pg.dbname
))
let mut message = format!("Imported from '{}' into '{}'", req.source, target_pg.dbname);
for warning in extensions.warnings() {
message.push_str(&format!("\n{warning}"));
}
Ok(message)
}
#[derive(Deserialize)]
@@ -9777,6 +9786,7 @@ async fn point_kept_datatables_at_parent(
forked_from: None,
migrations_enabled: dt.migrations_enabled,
permissions: None,
schema_only_tables: vec![],
})
.map_err(|e| Error::internal_err(format!("serializing data table '{name}': {e}")))?;
changed = true;
@@ -10044,6 +10054,25 @@ async fn apply_forked_datatable(
.execute(&mut **tx)
.await?;
// The rule the copy was made with: a pointer handed down by the settings clone carries none,
// and the source's may have been saved since the copy was made.
sqlx::query(
r#"UPDATE workspace_settings
SET datatable = CASE WHEN $3::jsonb IS NULL
THEN datatable #- ARRAY['datatables', $2, 'schema_only_tables']
ELSE jsonb_set(datatable, ARRAY['datatables', $2, 'schema_only_tables'], $3::jsonb)
END
WHERE workspace_id = $1"#,
)
.bind(forked_w_id)
.bind(&fdt.name)
.bind(
(!copy.schema_only_tables.is_empty())
.then(|| serde_json::json!(copy.schema_only_tables)),
)
.execute(&mut **tx)
.await?;
Ok(())
}
@@ -10433,7 +10462,7 @@ async fn create_workspace_fork(
created_by = EXCLUDED.created_by,
creation_id = EXCLUDED.creation_id,
started_at = now(), heartbeat_at = now(), step = NULL, finished_at = NULL,
error = NULL
error = NULL, warnings = NULL
WHERE workspace_fork_creation.finished_at IS NOT NULL
OR workspace_fork_creation.heartbeat_at < now() - $4 * interval '1 second'
RETURNING creation_id",
@@ -10562,6 +10591,9 @@ struct ForkCreationStatus {
step: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
/// What a completed fork goes without.
#[serde(skip_serializing_if = "Vec::is_empty")]
warnings: Vec<String>,
}
async fn get_fork_creation_status(
@@ -10570,7 +10602,7 @@ async fn get_fork_creation_status(
Path((parent_workspace_id, creation_id)): Path<(String, Uuid)>,
) -> JsonResult<ForkCreationStatus> {
let row = sqlx::query(
"SELECT c.created_by, c.finished_at IS NOT NULL AS finished, c.error, c.step,
"SELECT c.created_by, c.finished_at IS NOT NULL AS finished, c.error, c.step, c.warnings,
c.heartbeat_at < now() - $3 * interval '1 second' AS stale
FROM workspace_fork_creation c
WHERE c.creation_id = $1 AND c.parent_workspace_id = $2",
@@ -10589,8 +10621,20 @@ async fn get_fork_creation_status(
let error: Option<String> = row.get("error");
let status = if row.get::<bool, _>("finished") {
match error {
Some(error) => ForkCreationStatus { status: "failed", step: None, error: Some(error) },
None => ForkCreationStatus { status: "completed", step: None, error: None },
Some(error) => ForkCreationStatus {
status: "failed",
step: None,
error: Some(error),
warnings: vec![],
},
None => ForkCreationStatus {
status: "completed",
step: None,
error: None,
warnings: row
.get::<Option<Vec<String>>, _>("warnings")
.unwrap_or_default(),
},
}
} else if row.get::<bool, _>("stale") {
ForkCreationStatus {
@@ -10601,9 +10645,15 @@ async fn get_fork_creation_status(
and whether the fork exists before retrying"
.to_string(),
),
warnings: vec![],
}
} else {
ForkCreationStatus { status: "running", step: row.get("step"), error: None }
ForkCreationStatus {
status: "running",
step: row.get("step"),
error: None,
warnings: vec![],
}
};
Ok(Json(status))
}
@@ -11287,13 +11337,15 @@ async fn write_workspace_fork(
(!copied.is_empty()).then(|| [("copied_datatables", copied.as_str())].into()),
)
.await?;
let warnings: Vec<String> = copies.iter().flat_map(|c| c.warnings.clone()).collect();
// Committed with the fork, so its attempt reads complete exactly when the fork exists.
if let Some(creation_id) = progress.creation_id {
sqlx::query(
"UPDATE workspace_fork_creation SET finished_at = now(), error = NULL
"UPDATE workspace_fork_creation SET finished_at = now(), error = NULL, warnings = $2
WHERE creation_id = $1",
)
.bind(creation_id)
.bind((!warnings.is_empty()).then_some(&warnings))
.execute(&mut *tx)
.await?;
}
@@ -11314,7 +11366,11 @@ async fn write_workspace_fork(
}
// Clients that ask for a background fork recognise a server without it by this answer.
Ok(format!("Created forked workspace {}", &forked_id))
let mut message = format!("Created forked workspace {}", &forked_id);
for warning in &warnings {
message.push_str(&format!("\n{warning}"));
}
Ok(message)
}
#[derive(Deserialize)]
+13
View File
@@ -1769,6 +1769,11 @@ paths:
description: the part of the copy a running fork is in
error:
type: string
warnings:
type: array
items:
type: string
description: what a completed fork goes without, such as objects its data table copies could not carry
required:
- status
@@ -41308,6 +41313,14 @@ components:
migrations_enabled:
type: boolean
description: Whether the SQL migrations feature is opted in for this data table
schema_only_tables:
type: array
items:
type: string
description: >-
Tables a fork's copy with data copies without their rows, as `[schema.]name`
patterns where `*` matches any characters and an unqualified name matches in
every schema.
forked_from:
type: object
description: Fork origin info with schema snapshot
+41
View File
@@ -1773,6 +1773,26 @@ pub struct DataTable {
/// makes repo write access a second door onto the access decision.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<DataTablePermissions>,
/// Tables a copy with data copies without their rows, as `[schema.]name` patterns where `*`
/// matches any characters and an unqualified name matches in every schema. Read from the entry
/// that owns the database, when a fork copies it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub schema_only_tables: Vec<String>,
}
/// A `schema_only_tables` pattern as the `LIKE` patterns its schema and name match: `*` is any
/// characters, and the rest is taken literally.
pub fn schema_only_table_like(pattern: &str) -> (String, String) {
let like = |part: &str| {
part.replace('\\', "\\\\")
.replace('%', "\\%")
.replace('_', "\\_")
.replace('*', "%")
};
match pattern.split_once('.') {
Some((schema, name)) => (like(schema), like(name)),
None => ("%".to_string(), like(pattern)),
}
}
/// A pointer at another workspace's data table entry.
@@ -1820,6 +1840,15 @@ const DATATABLE_REFERENCE_MAX_DEPTH: usize = 20;
/// `permissions` beside it. Called wherever an entry is persisted, so nothing downstream has to
/// handle an entry that is both or neither, or a clone with a decision of its own.
pub fn validate_datatable_shape(name: &str, dt: &DataTable) -> Result<()> {
for pattern in &dt.schema_only_tables {
let parts: Vec<&str> = pattern.split('.').collect();
if parts.len() > 2 || parts.iter().any(|p| p.is_empty() || p.trim() != *p) {
return Err(Error::BadRequest(format!(
"Data table '{name}': schema-only table pattern '{pattern}' must be a table name or \
schema.table, where * matches any characters"
)));
}
}
if dt.governed_by.is_some() && (dt.database.is_none() || dt.permissions.is_some()) {
return Err(Error::BadRequest(format!(
"Data table '{name}' is a clone, which owns a database and takes its roles from the \
@@ -4287,6 +4316,17 @@ mod tests {
}
}
#[test]
fn schema_only_table_patterns_take_only_star_as_a_wildcard() {
let like = |p: &str| {
let (schema, name) = schema_only_table_like(p);
format!("{schema}|{name}")
};
assert_eq!(like("history_*"), "%|history\\_%");
assert_eq!(like("archive.*"), "archive|%");
assert_eq!(like("a%b\\c"), "%|a\\%b\\\\c");
}
#[test]
fn an_entry_owns_a_database_or_points_at_one_but_never_both() {
let terminal = DataTable {
@@ -4299,6 +4339,7 @@ mod tests {
forked_from: None,
migrations_enabled: None,
permissions: None,
schema_only_tables: vec![],
};
assert!(validate_datatable_shape("main", &terminal).is_ok());
+1 -1
View File
@@ -221,7 +221,7 @@ async function create(
`Workspace already has datatable(s): ${existing
.map((d) => d.name)
.join(", ")}. Re-run with --force to add '${dtName}' ` +
"(note: fork metadata on existing datatables is not preserved)",
"(note: fork metadata and settings such as tables forked without rows are not preserved on existing datatables)",
);
}
+18 -6
View File
@@ -23,8 +23,14 @@ import {
readConfigFile,
} from "../../core/conf.ts";
/** Wait for a fork creation started in the background, by the id its request answered with. */
async function waitForForkCreation(parentWorkspace: string, creationId: string) {
/**
* Wait for a fork creation started in the background, by the id its request answered with.
* Resolves to what the created fork goes without.
*/
async function waitForForkCreation(
parentWorkspace: string,
creationId: string,
): Promise<string[]> {
let failingSince: number | undefined;
let lastStep: string | undefined;
while (true) {
@@ -47,7 +53,7 @@ async function waitForForkCreation(parentWorkspace: string, creationId: string)
lastStep = result.step;
log.info(colors.gray(`${lastStep}...`));
}
if (result?.status === "completed") return;
if (result?.status === "completed") return result.warnings ?? [];
if (result?.status === "failed") {
throw new Error(result.error ?? "Unknown error");
}
@@ -355,7 +361,7 @@ async function createWorkspaceFork(
)
);
await wmill.importPgDatabase({
const imported = await wmill.importPgDatabase({
workspace: workspace.workspaceId,
requestBody: {
source: `datatable://${dt.name}`,
@@ -365,6 +371,9 @@ async function createWorkspaceFork(
},
});
for (const warning of imported.split("\n").slice(1)) {
log.warn(colors.yellow(` ${warning}`));
}
log.info(colors.green(` ✓ Datatable "${dt.name}" cloned.`));
forkedDatatables.push({ name: dt.name, new_dbname: newDbName });
} catch (e) {
@@ -420,8 +429,11 @@ async function createWorkspaceFork(
},
});
// A server without background forks ignores the flag and answers once the fork is created.
if (!response.startsWith("Created forked workspace")) {
await waitForForkCreation(workspace.workspaceId, response);
const warnings = response.startsWith("Created forked workspace")
? response.split("\n").slice(1)
: await waitForForkCreation(workspace.workspaceId, response);
for (const warning of warnings) {
log.warn(colors.yellow(warning));
}
log.info(colors.green(`✅ Created forked workspace ${trueWorkspaceId}`));
@@ -334,7 +334,7 @@
if (!target) return
importLoading = true
try {
await WorkspaceService.importPgDatabase({
const imported = await WorkspaceService.importPgDatabase({
workspace: ws,
requestBody: {
source: toSourceIdentifier(importSource),
@@ -343,6 +343,10 @@
}
})
sendUserToast('Database import completed successfully')
// The lines after the first name what the import went without.
for (const warning of imported.split('\n').slice(1)) {
sendUserToast(warning, 'warning', [], undefined, 20000)
}
importDrawerOpen = false
importSource = undefined
dbManagerContent?.refresh()
@@ -16,6 +16,8 @@
* owns no database of its own. Read-only here — only forking writes it, and the server
* carries it across a save rather than taking it from this form. */
reference?: { workspace_id: string; datatable: string }
/** The `schema_only_tables` patterns as typed, comma-separated. */
schemaOnlyTables: string
}[]
}
@@ -24,11 +26,12 @@
): DataTableSettingsType {
const s: DataTableSettingsType = { dataTables: [] }
if (settings?.datatables) {
for (const [name, rest] of Object.entries(settings.datatables)) {
for (const [name, { schema_only_tables, ...rest }] of Object.entries(settings.datatables)) {
s.dataTables.push({
id: randomUUID(),
name,
...rest,
schemaOnlyTables: (schema_only_tables ?? []).join(', '),
// A pointer entry owns no database. The row renders read-only in that case, so this
// placeholder is never shown or sent.
database: rest.database ?? { resource_type: 'instance' }
@@ -55,8 +58,13 @@
if (database.resource_type === 'instance' && database.resource_path === 'windmill')
throw dataTable.name + ' database cannot be called "windmill"'
const schemaOnlyTables = dataTable.schemaOnlyTables
.split(',')
.map((pattern) => pattern.trim())
.filter((pattern) => pattern !== '')
s.datatables[dataTable.name] = {
database: dataTable.database
database: dataTable.database,
...(schemaOnlyTables.length > 0 ? { schema_only_tables: schemaOnlyTables } : {})
}
}
return s
@@ -104,6 +112,7 @@
import Alert from '../common/alert/Alert.svelte'
import EmptyState from '../common/emptyState/EmptyState.svelte'
import Label from '../Label.svelte'
import CollapseLink from '../CollapseLink.svelte'
import MissingWorkerTagAlert from '../jobs/MissingWorkerTagAlert.svelte'
import { isCloudHosted } from '$lib/cloud'
import AddDataTableWizard from './AddDataTableWizard.svelte'
@@ -117,6 +126,12 @@
let { dataTableSettings = $bindable() }: Props = $props()
// Starts open on a data table whose saved settings already list tables, so they stay visible.
let forkSettingsOpen = $state<Record<string, boolean>>({})
function savedSchemaOnlyTables(id: string): string {
return dataTableSettings.dataTables.find((d) => d.id === id)?.schemaOnlyTables ?? ''
}
// Result of the last "Test connection", shown in that data table's card: the grant
// statements have to stay selectable, which rules out a toast.
let connectionCheck = $state<
@@ -530,6 +545,27 @@
/>
{/if}
</div>
{#if !dataTable.reference}
<CollapseLink
text="Fork settings"
bind:open={
() =>
forkSettingsOpen[dataTable.id] ??
savedSchemaOnlyTables(dataTable.id).trim() !== '',
(open) => (forkSettingsOpen[dataTable.id] = open)
}
>
<Label
label="Tables forked without rows"
tooltip="When a fork copies this data table with its data, these tables are created empty. Separate patterns with commas: a table name, or schema.table, where * matches any characters, like history_* or archive.*. A name without a schema matches in every schema. TimescaleDB hypertables must be listed, and are created as plain tables."
>
<TextInput
bind:value={dataTable.schemaOnlyTables}
inputProps={{ placeholder: 'history_*, archive.*' }}
/>
</Label>
</CollapseLink>
{/if}
{#if connectionCheck?.name === dataTable.name && !connectionCheck.loading}
<DataTableConnectionReport
name={connectionCheck.name}
@@ -7,7 +7,10 @@ vi.mock('$lib/gen', () => ({
}
}))
vi.mock('$lib/toast', () => ({ sendUserToast: vi.fn() }))
import { WorkspaceService } from '$lib/gen'
import { sendUserToast } from '$lib/toast'
import { createWorkspaceForkAndWait } from './forkCreation'
const svc = vi.mocked(WorkspaceService)
@@ -60,4 +63,12 @@ describe('createWorkspaceForkAndWait', () => {
svc.getForkCreationStatus.mockRejectedValue(new Error('upstream request timeout'))
expect(await run()).toBe('failed: upstream request timeout')
})
it('tells the user what a completed fork goes without, either way it was created', async () => {
svc.getForkCreationStatus.mockResolvedValueOnce({ status: 'completed', warnings: ['a'] })
expect(await run()).toBe('completed')
svc.createWorkspaceFork.mockResolvedValue('Created forked workspace wm-fork-x\nb')
expect(await run()).toBe('completed')
expect(vi.mocked(sendUserToast).mock.calls.map((c) => c[0])).toEqual(['a', 'b'])
})
})
+16 -2
View File
@@ -1,4 +1,5 @@
import { WorkspaceService, type CreateWorkspaceFork } from '$lib/gen'
import { sendUserToast } from '$lib/toast'
const POLL_INTERVAL_MS = 1500
// How long polls may keep failing, which a rolling deploy's replicas without the status route cause.
@@ -10,6 +11,13 @@ export function forkDatatableDbName(forkId: string, name: string): string {
return `wm_fork_${forkId.replace(/^wm-fork-/, '').replace(/-/g, '_')}__${name}`
}
/** What a created fork goes without, such as objects a data table copy could not carry. */
function reportForkWarnings(warnings: string[]) {
for (const warning of warnings) {
if (warning) sendUserToast(warning, 'warning', [], undefined, 20000)
}
}
/**
* Create a fork and resolve once it exists, rejecting with the reason it could not be created.
*
@@ -29,7 +37,10 @@ export async function createWorkspaceForkAndWait(
requestBody: fork
})
// A server without background forks ignores the flag and answers once the fork is created.
if (response.startsWith('Created forked workspace')) return
if (response.startsWith('Created forked workspace')) {
reportForkWarnings(response.split('\n').slice(1))
return
}
opts.onCreationStarted?.(response)
await waitForForkCreation(parentWorkspace, response, opts.onStep)
}
@@ -60,7 +71,10 @@ export async function waitForForkCreation(
if (Date.now() - failingSince >= maxFailingMs) throw e
}
if (result?.status === 'running' && result.step) onStep?.(result.step)
if (result?.status === 'completed') return
if (result?.status === 'completed') {
reportForkWarnings(result.warnings ?? [])
return
}
if (result?.status === 'failed') throw new Error(result.error ?? 'Unknown error')
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS))
}