feat: let a data table name tables its forks copy without rows (#12817)

* feat: let a data table name tables its forks copy without rows

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

* fix: refuse schema-only copies a foreign key or a shared copy would break

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

* fix: give a fork's copy the schema-only tables it was made with, catch foreign keys into a partition

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

* fix: refuse shared copies naming different schema-only tables whatever the behavior

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

* fix: compare a shared copy's later data tables with the list it was made with

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

* feat: put tables forked without rows under a collapsed fork settings section

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-12-02 15:49:06 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 5b2de8088c
commit db9f2368ae
6 changed files with 280 additions and 16 deletions
@@ -54,6 +54,9 @@ pub(crate) struct MadeCopy {
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
@@ -282,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, \
@@ -306,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!(
@@ -319,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(())
}
@@ -342,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());
@@ -470,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 mut extensions = read_extension_plan(db, &server, schema_only).await?;
let mut extensions = read_extension_plan(
db,
&server,
schema_only,
&governing.datatable.schema_only_tables,
)
.await?;
let dump = extensions.dump(&server, schema_only, managed).await?;
let applied = match migrations_lock {
Some(client) => Some(read_applied_migrations(&client).await?),
@@ -536,6 +572,7 @@ async fn make_copy(
.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 {
@@ -56,6 +56,10 @@ pub(crate) struct ExtensionPlan {
/// Continuous aggregates and the views built on them, quoted as `chunks`: the copy goes
/// without them.
left_out_views: 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>,
/// With TimescaleDB, the session the hypertables and chunks were read in, and the snapshot it
/// exported for the dump.
snapshot: Option<(SnapshotSession, String)>,
@@ -108,11 +112,15 @@ 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 read = async {
let plan = read_plan(&client, &source.dbname, schema_only).await?;
let mut plan = read_plan(&client, &source.dbname, schema_only).await?;
if !schema_only {
read_schema_only_tables(&client, &source.dbname, schema_only_tables, &mut plan).await?;
}
let hypertables: Vec<String> = if plan.uses_timescaledb() {
client
.query(
@@ -260,6 +268,94 @@ async fn refuse_extension_rows(client: &tokio_postgres::Client, dbname: &str) ->
Ok(())
}
/// Resolve the `schema_only_tables` patterns of the data table being copied to the tables they
/// match, so each table's rows and each hypertable's are left out by the same decision.
async fn read_schema_only_tables(
client: &tokio_postgres::Client,
dbname: &str,
patterns: &[String],
plan: &mut ExtensionPlan,
) -> Result<()> {
if patterns.is_empty() {
return Ok(());
}
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.
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 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))?;
let mut oids: Vec<u32> = vec![];
for row in rows {
let i: i64 = row.get(0);
match (
row.get::<_, Option<String>>(1),
row.get::<_, Option<String>>(2),
) {
(Some(schema), Some(name)) => {
plan.schema_only_tables.insert((schema, name));
oids.push(row.get(3));
}
_ => 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(())
}
async fn read_hypertables(
client: &tokio_postgres::Client,
dbname: &str,
@@ -553,18 +649,33 @@ impl ExtensionPlan {
.chain(&self.left_out_views)
.map(|relation| format!("exclude table {relation}")),
);
// 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
}
/// What the copy goes without, for whoever asked for it to be told.
pub(crate) fn warnings(&self) -> Vec<String> {
if self.left_out_views.is_empty() {
return vec![];
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(", ")
));
}
vec![format!(
"Not copied: TimescaleDB continuous aggregates and the views built on them ({})",
self.left_out_views.join(", ")
)]
if !self.unmatched_patterns.is_empty() {
warnings.push(format!(
"Schema-only table patterns matching no table: {}",
self.unmatched_patterns.join(", ")
));
}
warnings
}
/// Dump `source`, the database this plan was read from, in the snapshot it was read in when it
@@ -931,7 +1042,10 @@ impl ExtensionPlan {
return Err(refused);
}
}
if let Some(source) = rows {
let schema_only = self
.schema_only_tables
.contains(&(hypertable.schema.clone(), hypertable.name.clone()));
if let Some(source) = rows.filter(|_| !schema_only) {
copy_rows(source, &tx, hypertable)
.await
.map_err(|e| format!("copying the rows of {relation}: {e}"))?;
@@ -4393,9 +4393,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 {
@@ -4467,8 +4470,13 @@ async fn import_pg_database(
} else {
None
};
let mut extensions =
crate::datatable_extensions::read_extension_plan(&db, &source_pg, schema_only).await?;
let mut extensions = crate::datatable_extensions::read_extension_plan(
&db,
&source_pg,
schema_only,
&schema_only_tables,
)
.await?;
let dump = extensions.dump(&source_pg, schema_only, no_acl).await?;
let applied = match migrations_lock {
Some(client) => Some(crate::datatable_migrations::read_applied_migrations(&client).await?),
@@ -9779,6 +9787,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;
@@ -10046,6 +10055,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(())
}
+8
View File
@@ -41194,6 +41194,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());
@@ -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."
>
<TextInput
bind:value={dataTable.schemaOnlyTables}
inputProps={{ placeholder: 'history_*, archive.*' }}
/>
</Label>
</CollapseLink>
{/if}
{#if connectionCheck?.name === dataTable.name && !connectionCheck.loading}
<DataTableConnectionReport
name={connectionCheck.name}